ox-texinfo: Fix parse tree corruption
[org-mode.git] / lisp / org.el
blob9c18677592b608eb7c627e81e2661b14def4fc82
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-add-archive-files "org-archive" (files))
116 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
117 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
118 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
119 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
120 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
121 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
122 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
123 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
124 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
125 (declare-function org-clock-update-time-maybe "org-clock" ())
126 (declare-function org-clocktable-shift "org-clock" (dir n))
128 (declare-function orgtbl-mode "org-table" (&optional arg))
129 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
130 (declare-function org-beamer-mode "ox-beamer" ())
131 (declare-function org-table-edit-field "org-table" (arg))
132 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
133 (declare-function org-table-set-constants "org-table" ())
134 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
135 (declare-function org-id-get-create "org-id" (&optional force))
136 (declare-function org-id-find-id-file "org-id" (id))
137 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
138 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
139 (declare-function org-agenda-redo "org-agenda" (&optional all))
140 (declare-function org-table-align "org-table" ())
141 (declare-function org-table-begin "org-table" (&optional table-type))
142 (declare-function org-table-blank-field "org-table" ())
143 (declare-function org-table-end "org-table" (&optional table-type))
144 (declare-function org-table-insert-row "org-table" (&optional arg))
145 (declare-function org-table-paste-rectangle "org-table" ())
146 (declare-function org-table-maybe-eval-formula "org-table" ())
147 (declare-function org-table-maybe-recalculate-line "org-table" ())
149 (declare-function org-element--parse-objects "org-element"
150 (beg end acc restriction))
151 (declare-function org-element-at-point "org-element" (&optional keep-trail))
152 (declare-function org-element-contents "org-element" (element))
153 (declare-function org-element-context "org-element" (&optional element))
154 (declare-function org-element-interpret-data "org-element"
155 (data &optional parent))
156 (declare-function org-element-map "org-element"
157 (data types fun &optional info first-match no-recursion))
158 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
159 (declare-function org-element-parse-buffer "org-element"
160 (&optional granularity visible-only))
161 (declare-function org-element-property "org-element" (property element))
162 (declare-function org-element-put-property "org-element"
163 (element property value))
164 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
165 (declare-function org-element--parse-objects "org-element"
166 (beg end acc restriction))
167 (declare-function org-element-parse-buffer "org-element"
168 (&optional granularity visible-only))
169 (declare-function org-element-restriction "org-element" (element))
170 (declare-function org-element-type "org-element" (element))
172 ;; load languages based on value of `org-babel-load-languages'
173 (defvar org-babel-load-languages)
175 ;;;###autoload
176 (defun org-babel-do-load-languages (sym value)
177 "Load the languages defined in `org-babel-load-languages'."
178 (set-default sym value)
179 (mapc (lambda (pair)
180 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
181 (if active
182 (progn
183 (require (intern (concat "ob-" lang))))
184 (progn
185 (funcall 'fmakunbound
186 (intern (concat "org-babel-execute:" lang)))
187 (funcall 'fmakunbound
188 (intern (concat "org-babel-expand-body:" lang)))))))
189 org-babel-load-languages))
191 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
192 ;;;###autoload
193 (defun org-babel-load-file (file &optional compile)
194 "Load Emacs Lisp source code blocks in the Org-mode FILE.
195 This function exports the source code using `org-babel-tangle'
196 and then loads the resulting file using `load-file'. With prefix
197 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
198 file to byte-code before it is loaded."
199 (interactive "fFile to load: \nP")
200 (require 'ob-core)
201 (let* ((age (lambda (file)
202 (float-time
203 (time-subtract (current-time)
204 (nth 5 (or (file-attributes (file-truename file))
205 (file-attributes file)))))))
206 (base-name (file-name-sans-extension file))
207 (exported-file (concat base-name ".el")))
208 ;; tangle if the org-mode file is newer than the elisp file
209 (unless (and (file-exists-p exported-file)
210 (> (funcall age file) (funcall age exported-file)))
211 (setq exported-file
212 (car (org-babel-tangle-file file exported-file "emacs-lisp"))))
213 (message "%s %s"
214 (if compile
215 (progn (byte-compile-file exported-file 'load)
216 "Compiled and loaded")
217 (progn (load-file exported-file) "Loaded"))
218 exported-file)))
220 (defcustom org-babel-load-languages '((emacs-lisp . t))
221 "Languages which can be evaluated in Org-mode buffers.
222 This list can be used to load support for any of the languages
223 below, note that each language will depend on a different set of
224 system executables and/or Emacs modes. When a language is
225 \"loaded\", then code blocks in that language can be evaluated
226 with `org-babel-execute-src-block' bound by default to C-c
227 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
228 be set to remove code block evaluation from the C-c C-c
229 keybinding. By default only Emacs Lisp (which has no
230 requirements) is loaded."
231 :group 'org-babel
232 :set 'org-babel-do-load-languages
233 :version "24.1"
234 :type '(alist :tag "Babel Languages"
235 :key-type
236 (choice
237 (const :tag "Awk" awk)
238 (const :tag "C" C)
239 (const :tag "R" R)
240 (const :tag "Asymptote" asymptote)
241 (const :tag "Calc" calc)
242 (const :tag "Clojure" clojure)
243 (const :tag "CSS" css)
244 (const :tag "Ditaa" ditaa)
245 (const :tag "Dot" dot)
246 (const :tag "Emacs Lisp" emacs-lisp)
247 (const :tag "Fortran" fortran)
248 (const :tag "Gnuplot" gnuplot)
249 (const :tag "Haskell" haskell)
250 (const :tag "IO" io)
251 (const :tag "Java" java)
252 (const :tag "Javascript" js)
253 (const :tag "LaTeX" latex)
254 (const :tag "Ledger" ledger)
255 (const :tag "Lilypond" lilypond)
256 (const :tag "Lisp" lisp)
257 (const :tag "Makefile" makefile)
258 (const :tag "Maxima" maxima)
259 (const :tag "Matlab" matlab)
260 (const :tag "Mscgen" mscgen)
261 (const :tag "Ocaml" ocaml)
262 (const :tag "Octave" octave)
263 (const :tag "Org" org)
264 (const :tag "Perl" perl)
265 (const :tag "Pico Lisp" picolisp)
266 (const :tag "PlantUML" plantuml)
267 (const :tag "Python" python)
268 (const :tag "Ruby" ruby)
269 (const :tag "Sass" sass)
270 (const :tag "Scala" scala)
271 (const :tag "Scheme" scheme)
272 (const :tag "Screen" screen)
273 (const :tag "Shell Script" sh)
274 (const :tag "Shen" shen)
275 (const :tag "Sql" sql)
276 (const :tag "Sqlite" sqlite))
277 :value-type (boolean :tag "Activate" :value t)))
279 ;;;; Customization variables
280 (defcustom org-clone-delete-id nil
281 "Remove ID property of clones of a subtree.
282 When non-nil, clones of a subtree don't inherit the ID property.
283 Otherwise they inherit the ID property with a new unique
284 identifier."
285 :type 'boolean
286 :version "24.1"
287 :group 'org-id)
289 ;;; Version
290 (org-check-version)
292 ;;;###autoload
293 (defun org-version (&optional here full message)
294 "Show the org-mode version in the echo area.
295 With prefix argument HERE, insert it at point.
296 When FULL is non-nil, use a verbose version string.
297 When MESSAGE is non-nil, display a message with the version."
298 (interactive "P")
299 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
300 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
301 (load-suffixes (list ".el"))
302 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
303 (org-trash (or
304 (and (fboundp 'org-release) (fboundp 'org-git-version))
305 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
306 (load-suffixes save-load-suffixes)
307 (org-version (org-release))
308 (git-version (org-git-version))
309 (version (format "Org-mode version %s (%s @ %s)"
310 org-version
311 git-version
312 (if org-install-dir
313 (if (string= org-dir org-install-dir)
314 org-install-dir
315 (concat "mixed installation! " org-install-dir " and " org-dir))
316 "org-loaddefs.el can not be found!")))
317 (version1 (if full version org-version)))
318 (if (org-called-interactively-p 'interactive)
319 (if here
320 (insert version)
321 (message version))
322 (if message (message version1))
323 version1)))
325 (defconst org-version (org-version))
327 ;;; Compatibility constants
329 ;;; The custom variables
331 (defgroup org nil
332 "Outline-based notes management and organizer."
333 :tag "Org"
334 :group 'outlines
335 :group 'calendar)
337 (defcustom org-mode-hook nil
338 "Mode hook for Org-mode, run after the mode was turned on."
339 :group 'org
340 :type 'hook)
342 (defcustom org-load-hook nil
343 "Hook that is run after org.el has been loaded."
344 :group 'org
345 :type 'hook)
347 (defcustom org-log-buffer-setup-hook nil
348 "Hook that is run after an Org log buffer is created."
349 :group 'org
350 :version "24.1"
351 :type 'hook)
353 (defvar org-modules) ; defined below
354 (defvar org-modules-loaded nil
355 "Have the modules been loaded already?")
357 (defun org-load-modules-maybe (&optional force)
358 "Load all extensions listed in `org-modules'."
359 (when (or force (not org-modules-loaded))
360 (mapc (lambda (ext)
361 (condition-case nil (require ext)
362 (error (message "Problems while trying to load feature `%s'" ext))))
363 org-modules)
364 (setq org-modules-loaded t)))
366 (defun org-set-modules (var value)
367 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
368 (set var value)
369 (when (featurep 'org)
370 (org-load-modules-maybe 'force)))
372 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
373 "Modules that should always be loaded together with org.el.
375 If a description starts with <C>, the file is not part of Emacs
376 and loading it will require that you have downloaded and properly
377 installed the Org mode distribution.
379 You can also use this system to load external packages (i.e. neither Org
380 core modules, nor modules from the CONTRIB directory). Just add symbols
381 to the end of the list. If the package is called org-xyz.el, then you need
382 to add the symbol `xyz', and the package must have a call to:
384 \(provide 'org-xyz)
386 For export specific modules, see also `org-export-backends'."
387 :group 'org
388 :set 'org-set-modules
389 :version "24.4"
390 :package-version '(Org . "8.0")
391 :type
392 '(set :greedy t
393 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
394 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
395 (const :tag " crypt: Encryption of subtrees" org-crypt)
396 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
397 (const :tag " docview: Links to doc-view buffers" org-docview)
398 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
399 (const :tag " habit: Track your consistency with habits" org-habit)
400 (const :tag " id: Global IDs for identifying entries" org-id)
401 (const :tag " info: Links to Info nodes" org-info)
402 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
403 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
404 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
405 (const :tag " mouse: Additional mouse support" org-mouse)
406 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
407 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
408 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
410 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
411 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
412 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
413 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
414 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
415 (const :tag "C collector: Collect properties into tables" org-collector)
416 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
417 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
418 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
419 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
420 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
421 (const :tag "C eval: Include command output as text" org-eval)
422 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
423 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
424 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
425 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
426 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
427 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
428 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
429 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
430 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
431 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
432 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
433 (const :tag "C mew: Links to Mew folders/messages" org-mew)
434 (const :tag "C mtags: Support for muse-like tags" org-mtags)
435 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
436 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
437 (const :tag "C registry: A registry for Org-mode links" org-registry)
438 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
439 (const :tag "C secretary: Team management with org-mode" org-secretary)
440 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
441 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
442 (const :tag "C track: Keep up with Org-mode development" org-track)
443 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
444 (const :tag "C vm: Links to VM folders/messages" org-vm)
445 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
446 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
447 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
449 (defvar org-export--registered-backends) ; From ox.el.
450 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
451 (declare-function org-export-backend-name "ox" (backend))
452 (defcustom org-export-backends '(ascii html icalendar latex)
453 "List of export back-ends that should be always available.
455 If a description starts with <C>, the file is not part of Emacs
456 and loading it will require that you have downloaded and properly
457 installed the Org mode distribution.
459 Unlike to `org-modules', libraries in this list will not be
460 loaded along with Org, but only once the export framework is
461 needed.
463 This variable needs to be set before org.el is loaded. If you
464 need to make a change while Emacs is running, use the customize
465 interface or run the following code, where VAL stands for the new
466 value of the variable, after updating it:
468 \(progn
469 \(setq org-export--registered-backends
470 \(org-remove-if-not
471 \(lambda (backend)
472 \(let ((name (org-export-backend-name backend)))
473 \(or (memq name val)
474 \(catch 'parentp
475 \(dolist (b val)
476 \(and (org-export-derived-backend-p b name)
477 \(throw 'parentp t)))))))
478 org-export--registered-backends))
479 \(let ((new-list (mapcar 'org-export-backend-name
480 org-export--registered-backends)))
481 \(dolist (backend val)
482 \(cond
483 \((not (load (format \"ox-%s\" backend) t t))
484 \(message \"Problems while trying to load export back-end `%s'\"
485 backend))
486 \((not (memq backend new-list)) (push backend new-list))))
487 \(set-default 'org-export-backends new-list)))
489 Adding a back-end to this list will also pull the back-end it
490 depends on, if any."
491 :group 'org
492 :group 'org-export
493 :version "24.4"
494 :package-version '(Org . "8.0")
495 :initialize 'custom-initialize-set
496 :set (lambda (var val)
497 (if (not (featurep 'ox)) (set-default var val)
498 ;; Any back-end not required anymore (not present in VAL and not
499 ;; a parent of any back-end in the new value) is removed from the
500 ;; list of registered back-ends.
501 (setq org-export--registered-backends
502 (org-remove-if-not
503 (lambda (backend)
504 (let ((name (org-export-backend-name backend)))
505 (or (memq name val)
506 (catch 'parentp
507 (dolist (b val)
508 (and (org-export-derived-backend-p b name)
509 (throw 'parentp t)))))))
510 org-export--registered-backends))
511 ;; Now build NEW-LIST of both new back-ends and required
512 ;; parents.
513 (let ((new-list (mapcar 'org-export-backend-name
514 org-export--registered-backends)))
515 (dolist (backend val)
516 (cond
517 ((not (load (format "ox-%s" backend) t t))
518 (message "Problems while trying to load export back-end `%s'"
519 backend))
520 ((not (memq backend new-list)) (push backend new-list))))
521 ;; Set VAR to that list with fixed dependencies.
522 (set-default var new-list))))
523 :type '(set :greedy t
524 (const :tag " ascii Export buffer to ASCII format" ascii)
525 (const :tag " beamer Export buffer to Beamer presentation" beamer)
526 (const :tag " html Export buffer to HTML format" html)
527 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
528 (const :tag " latex Export buffer to LaTeX format" latex)
529 (const :tag " man Export buffer to MAN format" man)
530 (const :tag " md Export buffer to Markdown format" md)
531 (const :tag " odt Export buffer to ODT format" odt)
532 (const :tag " org Export buffer to Org format" org)
533 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
534 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
535 (const :tag "C deck Export buffer to deck.js presentations" deck)
536 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
537 (const :tag "C groff Export buffer to Groff format" groff)
538 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
539 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
540 (const :tag "C s5 Export buffer to s5 presentations" s5)
541 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
543 (eval-after-load 'ox
544 '(mapc
545 (lambda (backend)
546 (condition-case nil (require (intern (format "ox-%s" backend)))
547 (error (message "Problems while trying to load export back-end `%s'"
548 backend))))
549 org-export-backends))
551 (defcustom org-support-shift-select nil
552 "Non-nil means make shift-cursor commands select text when possible.
554 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
555 start selecting a region, or enlarge regions started in this way.
556 In Org-mode, in special contexts, these same keys are used for
557 other purposes, important enough to compete with shift selection.
558 Org tries to balance these needs by supporting `shift-select-mode'
559 outside these special contexts, under control of this variable.
561 The default of this variable is nil, to avoid confusing behavior. Shifted
562 cursor keys will then execute Org commands in the following contexts:
563 - on a headline, changing TODO state (left/right) and priority (up/down)
564 - on a time stamp, changing the time
565 - in a plain list item, changing the bullet type
566 - in a property definition line, switching between allowed values
567 - in the BEGIN line of a clock table (changing the time block).
568 Outside these contexts, the commands will throw an error.
570 When this variable is t and the cursor is not in a special
571 context, Org-mode will support shift-selection for making and
572 enlarging regions. To make this more effective, the bullet
573 cycling will no longer happen anywhere in an item line, but only
574 if the cursor is exactly on the bullet.
576 If you set this variable to the symbol `always', then the keys
577 will not be special in headlines, property lines, and item lines,
578 to make shift selection work there as well. If this is what you
579 want, you can use the following alternative commands: `C-c C-t'
580 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
581 can be used to switch TODO sets, `C-c -' to cycle item bullet
582 types, and properties can be edited by hand or in column view.
584 However, when the cursor is on a timestamp, shift-cursor commands
585 will still edit the time stamp - this is just too good to give up.
587 XEmacs user should have this variable set to nil, because
588 `shift-select-mode' is in Emacs 23 or later only."
589 :group 'org
590 :type '(choice
591 (const :tag "Never" nil)
592 (const :tag "When outside special context" t)
593 (const :tag "Everywhere except timestamps" always)))
595 (defcustom org-loop-over-headlines-in-active-region nil
596 "Shall some commands act upon headlines in the active region?
598 When set to `t', some commands will be performed in all headlines
599 within the active region.
601 When set to `start-level', some commands will be performed in all
602 headlines within the active region, provided that these headlines
603 are of the same level than the first one.
605 When set to a string, those commands will be performed on the
606 matching headlines within the active region. Such string must be
607 a tags/property/todo match as it is used in the agenda tags view.
609 The list of commands is: `org-schedule', `org-deadline',
610 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
611 `org-archive-to-archive-sibling'. The archiving commands skip
612 already archived entries."
613 :type '(choice (const :tag "Don't loop" nil)
614 (const :tag "All headlines in active region" t)
615 (const :tag "In active region, headlines at the same level than the first one" start-level)
616 (string :tag "Tags/Property/Todo matcher"))
617 :version "24.1"
618 :group 'org-todo
619 :group 'org-archive)
621 (defgroup org-startup nil
622 "Options concerning startup of Org-mode."
623 :tag "Org Startup"
624 :group 'org)
626 (defcustom org-startup-folded t
627 "Non-nil means entering Org-mode will switch to OVERVIEW.
628 This can also be configured on a per-file basis by adding one of
629 the following lines anywhere in the buffer:
631 #+STARTUP: fold (or `overview', this is equivalent)
632 #+STARTUP: nofold (or `showall', this is equivalent)
633 #+STARTUP: content
634 #+STARTUP: showeverything
636 By default, this option is ignored when Org opens agenda files
637 for the first time. If you want the agenda to honor the startup
638 option, set `org-agenda-inhibit-startup' to nil."
639 :group 'org-startup
640 :type '(choice
641 (const :tag "nofold: show all" nil)
642 (const :tag "fold: overview" t)
643 (const :tag "content: all headlines" content)
644 (const :tag "show everything, even drawers" showeverything)))
646 (defcustom org-startup-truncated t
647 "Non-nil means entering Org-mode will set `truncate-lines'.
648 This is useful since some lines containing links can be very long and
649 uninteresting. Also tables look terrible when wrapped."
650 :group 'org-startup
651 :type 'boolean)
653 (defcustom org-startup-indented nil
654 "Non-nil means turn on `org-indent-mode' on startup.
655 This can also be configured on a per-file basis by adding one of
656 the following lines anywhere in the buffer:
658 #+STARTUP: indent
659 #+STARTUP: noindent"
660 :group 'org-structure
661 :type '(choice
662 (const :tag "Not" nil)
663 (const :tag "Globally (slow on startup in large files)" t)))
665 (defcustom org-use-sub-superscripts t
666 "Non-nil means interpret \"_\" and \"^\" for display.
668 If you want to control how Org exports those characters, see
669 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
670 used to be an alias for `org-export-with-sub-superscripts' in
671 Org <8.0, it is not anymore.
673 When this option is turned on, you can use TeX-like syntax for
674 sub- and superscripts within the buffer. Several characters after
675 \"_\" or \"^\" will be considered as a single item - so grouping
676 with {} is normally not needed. For example, the following things
677 will be parsed as single sub- or superscripts:
679 10^24 or 10^tau several digits will be considered 1 item.
680 10^-12 or 10^-tau a leading sign with digits or a word
681 x^2-y^3 will be read as x^2 - y^3, because items are
682 terminated by almost any nonword/nondigit char.
683 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
685 Still, ambiguity is possible. So when in doubt, use {} to enclose
686 the sub/superscript. If you set this variable to the symbol `{}',
687 the braces are *required* in order to trigger interpretations as
688 sub/superscript. This can be helpful in documents that need \"_\"
689 frequently in plain text."
690 :group 'org-startup
691 :version "24.4"
692 :package-version '(Org . "8.0")
693 :type '(choice
694 (const :tag "Always interpret" t)
695 (const :tag "Only with braces" {})
696 (const :tag "Never interpret" nil)))
698 (defcustom org-startup-with-beamer-mode nil
699 "Non-nil means turn on `org-beamer-mode' on startup.
700 This can also be configured on a per-file basis by adding one of
701 the following lines anywhere in the buffer:
703 #+STARTUP: beamer"
704 :group 'org-startup
705 :version "24.1"
706 :type 'boolean)
708 (defcustom org-startup-align-all-tables nil
709 "Non-nil means align all tables when visiting a file.
710 This is useful when the column width in tables is forced with <N> cookies
711 in table fields. Such tables will look correct only after the first re-align.
712 This can also be configured on a per-file basis by adding one of
713 the following lines anywhere in the buffer:
714 #+STARTUP: align
715 #+STARTUP: noalign"
716 :group 'org-startup
717 :type 'boolean)
719 (defcustom org-startup-with-inline-images nil
720 "Non-nil means show inline images when loading a new Org file.
721 This can also be configured on a per-file basis by adding one of
722 the following lines anywhere in the buffer:
723 #+STARTUP: inlineimages
724 #+STARTUP: noinlineimages"
725 :group 'org-startup
726 :version "24.1"
727 :type 'boolean)
729 (defcustom org-startup-with-latex-preview nil
730 "Non-nil means preview LaTeX fragments when loading a new Org file.
732 This can also be configured on a per-file basis by adding one of
733 the following lines anywhere in the buffer:
734 #+STARTUP: latexpreview
735 #+STARTUP: nolatexpreview"
736 :group 'org-startup
737 :version "24.4"
738 :package-version '(Org . "8.0")
739 :type 'boolean)
741 (defcustom org-insert-mode-line-in-empty-file nil
742 "Non-nil means insert the first line setting Org-mode in empty files.
743 When the function `org-mode' is called interactively in an empty file, this
744 normally means that the file name does not automatically trigger Org-mode.
745 To ensure that the file will always be in Org-mode in the future, a
746 line enforcing Org-mode will be inserted into the buffer, if this option
747 has been set."
748 :group 'org-startup
749 :type 'boolean)
751 (defcustom org-replace-disputed-keys nil
752 "Non-nil means use alternative key bindings for some keys.
753 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
754 These keys are also used by other packages like shift-selection-mode'
755 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
756 If you want to use Org-mode together with one of these other modes,
757 or more generally if you would like to move some Org-mode commands to
758 other keys, set this variable and configure the keys with the variable
759 `org-disputed-keys'.
761 This option is only relevant at load-time of Org-mode, and must be set
762 *before* org.el is loaded. Changing it requires a restart of Emacs to
763 become effective."
764 :group 'org-startup
765 :type 'boolean)
767 (defcustom org-use-extra-keys nil
768 "Non-nil means use extra key sequence definitions for certain commands.
769 This happens automatically if you run XEmacs or if `window-system'
770 is nil. This variable lets you do the same manually. You must
771 set it before loading org.
773 Example: on Carbon Emacs 22 running graphically, with an external
774 keyboard on a Powerbook, the default way of setting M-left might
775 not work for either Alt or ESC. Setting this variable will make
776 it work for ESC."
777 :group 'org-startup
778 :type 'boolean)
780 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
782 (defcustom org-disputed-keys
783 '(([(shift up)] . [(meta p)])
784 ([(shift down)] . [(meta n)])
785 ([(shift left)] . [(meta -)])
786 ([(shift right)] . [(meta +)])
787 ([(control shift right)] . [(meta shift +)])
788 ([(control shift left)] . [(meta shift -)]))
789 "Keys for which Org-mode and other modes compete.
790 This is an alist, cars are the default keys, second element specifies
791 the alternative to use when `org-replace-disputed-keys' is t.
793 Keys can be specified in any syntax supported by `define-key'.
794 The value of this option takes effect only at Org-mode's startup,
795 therefore you'll have to restart Emacs to apply it after changing."
796 :group 'org-startup
797 :type 'alist)
799 (defun org-key (key)
800 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
801 Or return the original if not disputed.
802 Also apply the translations defined in `org-xemacs-key-equivalents'."
803 (when org-replace-disputed-keys
804 (let* ((nkey (key-description key))
805 (x (org-find-if (lambda (x)
806 (equal (key-description (car x)) nkey))
807 org-disputed-keys)))
808 (setq key (if x (cdr x) key))))
809 (when (featurep 'xemacs)
810 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
811 key)
813 (defun org-find-if (predicate seq)
814 (catch 'exit
815 (while seq
816 (if (funcall predicate (car seq))
817 (throw 'exit (car seq))
818 (pop seq)))))
820 (defun org-defkey (keymap key def)
821 "Define a key, possibly translated, as returned by `org-key'."
822 (define-key keymap (org-key key) def))
824 (defcustom org-ellipsis nil
825 "The ellipsis to use in the Org-mode outline.
826 When nil, just use the standard three dots.
827 When a string, use that string instead.
828 When a face, use the standard 3 dots, but with the specified face.
829 The change affects only Org-mode (which will then use its own display table).
830 Changing this requires executing `M-x org-mode RET' in a buffer to become
831 effective."
832 :group 'org-startup
833 :type '(choice (const :tag "Default" nil)
834 (face :tag "Face" :value org-warning)
835 (string :tag "String" :value "...#")))
837 (defvar org-display-table nil
838 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
840 (defgroup org-keywords nil
841 "Keywords in Org-mode."
842 :tag "Org Keywords"
843 :group 'org)
845 (defcustom org-deadline-string "DEADLINE:"
846 "String to mark deadline entries.
847 A deadline is this string, followed by a time stamp. Should be a word,
848 terminated by a colon. You can insert a schedule keyword and
849 a timestamp with \\[org-deadline].
850 Changes become only effective after restarting Emacs."
851 :group 'org-keywords
852 :type 'string)
854 (defcustom org-scheduled-string "SCHEDULED:"
855 "String to mark scheduled TODO entries.
856 A schedule is this string, followed by a time stamp. Should be a word,
857 terminated by a colon. You can insert a schedule keyword and
858 a timestamp with \\[org-schedule].
859 Changes become only effective after restarting Emacs."
860 :group 'org-keywords
861 :type 'string)
863 (defcustom org-closed-string "CLOSED:"
864 "String used as the prefix for timestamps logging closing a TODO entry."
865 :group 'org-keywords
866 :type 'string)
868 (defcustom org-clock-string "CLOCK:"
869 "String used as prefix for timestamps clocking work hours on an item."
870 :group 'org-keywords
871 :type 'string)
873 (defcustom org-closed-keep-when-no-todo nil
874 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
875 :group 'org-todo
876 :group 'org-keywords
877 :version "24.4"
878 :package-version '(Org . "8.0")
879 :type 'boolean)
881 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
882 org-scheduled-string "\\|"
883 org-deadline-string "\\|"
884 org-closed-string "\\|"
885 org-clock-string "\\)")
886 "Matches a line with planning or clock info.")
888 (defcustom org-comment-string "COMMENT"
889 "Entries starting with this keyword will never be exported.
890 An entry can be toggled between COMMENT and normal with
891 \\[org-toggle-comment].
892 Changes become only effective after restarting Emacs."
893 :group 'org-keywords
894 :type 'string)
896 (defcustom org-quote-string "QUOTE"
897 "Entries starting with this keyword will be exported in fixed-width font.
898 Quoting applies only to the text in the entry following the headline, and does
899 not extend beyond the next headline, even if that is lower level.
900 An entry can be toggled between QUOTE and normal with
901 \\[org-toggle-fixed-width-section]."
902 :group 'org-keywords
903 :type 'string)
905 (defconst org-repeat-re
906 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
907 "Regular expression for specifying repeated events.
908 After a match, group 1 contains the repeat expression.")
910 (defgroup org-structure nil
911 "Options concerning the general structure of Org-mode files."
912 :tag "Org Structure"
913 :group 'org)
915 (defgroup org-reveal-location nil
916 "Options about how to make context of a location visible."
917 :tag "Org Reveal Location"
918 :group 'org-structure)
920 (defconst org-context-choice
921 '(choice
922 (const :tag "Always" t)
923 (const :tag "Never" nil)
924 (repeat :greedy t :tag "Individual contexts"
925 (cons
926 (choice :tag "Context"
927 (const agenda)
928 (const org-goto)
929 (const occur-tree)
930 (const tags-tree)
931 (const link-search)
932 (const mark-goto)
933 (const bookmark-jump)
934 (const isearch)
935 (const default))
936 (boolean))))
937 "Contexts for the reveal options.")
939 (defcustom org-show-hierarchy-above '((default . t))
940 "Non-nil means show full hierarchy when revealing a location.
941 Org-mode often shows locations in an org-mode file which might have
942 been invisible before. When this is set, the hierarchy of headings
943 above the exposed location is shown.
944 Turning this off for example for sparse trees makes them very compact.
945 Instead of t, this can also be an alist specifying this option for different
946 contexts. Valid contexts are
947 agenda when exposing an entry from the agenda
948 org-goto when using the command `org-goto' on key C-c C-j
949 occur-tree when using the command `org-occur' on key C-c /
950 tags-tree when constructing a sparse tree based on tags matches
951 link-search when exposing search matches associated with a link
952 mark-goto when exposing the jump goal of a mark
953 bookmark-jump when exposing a bookmark location
954 isearch when exiting from an incremental search
955 default default for all contexts not set explicitly"
956 :group 'org-reveal-location
957 :type org-context-choice)
959 (defcustom org-show-following-heading '((default . nil))
960 "Non-nil means show following heading when revealing a location.
961 Org-mode often shows locations in an org-mode file which might have
962 been invisible before. When this is set, the heading following the
963 match is shown.
964 Turning this off for example for sparse trees makes them very compact,
965 but makes it harder to edit the location of the match. In such a case,
966 use the command \\[org-reveal] to show more context.
967 Instead of t, this can also be an alist specifying this option for different
968 contexts. See `org-show-hierarchy-above' for valid contexts."
969 :group 'org-reveal-location
970 :type org-context-choice)
972 (defcustom org-show-siblings '((default . nil) (isearch t) (bookmark-jump t))
973 "Non-nil means show all sibling heading when revealing a location.
974 Org-mode often shows locations in an org-mode file which might have
975 been invisible before. When this is set, the sibling of the current entry
976 heading are all made visible. If `org-show-hierarchy-above' is t,
977 the same happens on each level of the hierarchy above the current entry.
979 By default this is on for the isearch context, off for all other contexts.
980 Turning this off for example for sparse trees makes them very compact,
981 but makes it harder to edit the location of the match. In such a case,
982 use the command \\[org-reveal] to show more context.
983 Instead of t, this can also be an alist specifying this option for different
984 contexts. See `org-show-hierarchy-above' for valid contexts."
985 :group 'org-reveal-location
986 :type org-context-choice
987 :version "24.4"
988 :package-version '(Org . "8.0"))
990 (defcustom org-show-entry-below '((default . nil))
991 "Non-nil means show the entry below a headline when revealing a location.
992 Org-mode often shows locations in an org-mode file which might have
993 been invisible before. When this is set, the text below the headline that is
994 exposed is also shown.
996 By default this is off for all contexts.
997 Instead of t, this can also be an alist specifying this option for different
998 contexts. See `org-show-hierarchy-above' for valid contexts."
999 :group 'org-reveal-location
1000 :type org-context-choice)
1002 (defcustom org-indirect-buffer-display 'other-window
1003 "How should indirect tree buffers be displayed?
1004 This applies to indirect buffers created with the commands
1005 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
1006 Valid values are:
1007 current-window Display in the current window
1008 other-window Just display in another window.
1009 dedicated-frame Create one new frame, and re-use it each time.
1010 new-frame Make a new frame each time. Note that in this case
1011 previously-made indirect buffers are kept, and you need to
1012 kill these buffers yourself."
1013 :group 'org-structure
1014 :group 'org-agenda-windows
1015 :type '(choice
1016 (const :tag "In current window" current-window)
1017 (const :tag "In current frame, other window" other-window)
1018 (const :tag "Each time a new frame" new-frame)
1019 (const :tag "One dedicated frame" dedicated-frame)))
1021 (defcustom org-use-speed-commands nil
1022 "Non-nil means activate single letter commands at beginning of a headline.
1023 This may also be a function to test for appropriate locations where speed
1024 commands should be active."
1025 :group 'org-structure
1026 :type '(choice
1027 (const :tag "Never" nil)
1028 (const :tag "At beginning of headline stars" t)
1029 (function)))
1031 (defcustom org-speed-commands-user nil
1032 "Alist of additional speed commands.
1033 This list will be checked before `org-speed-commands-default'
1034 when the variable `org-use-speed-commands' is non-nil
1035 and when the cursor is at the beginning of a headline.
1036 The car if each entry is a string with a single letter, which must
1037 be assigned to `self-insert-command' in the global map.
1038 The cdr is either a command to be called interactively, a function
1039 to be called, or a form to be evaluated.
1040 An entry that is just a list with a single string will be interpreted
1041 as a descriptive headline that will be added when listing the speed
1042 commands in the Help buffer using the `?' speed command."
1043 :group 'org-structure
1044 :type '(repeat :value ("k" . ignore)
1045 (choice :value ("k" . ignore)
1046 (list :tag "Descriptive Headline" (string :tag "Headline"))
1047 (cons :tag "Letter and Command"
1048 (string :tag "Command letter")
1049 (choice
1050 (function)
1051 (sexp))))))
1053 (defcustom org-bookmark-names-plist
1054 '(:last-capture "org-capture-last-stored"
1055 :last-refile "org-refile-last-stored"
1056 :last-capture-marker "org-capture-last-stored-marker")
1057 "Names for bookmarks automatically set by some Org commands.
1058 This can provide strings as names for a number of bookmarks Org sets
1059 automatically. The following keys are currently implemented:
1060 :last-capture
1061 :last-capture-marker
1062 :last-refile
1063 When a key does not show up in the property list, the corresponding bookmark
1064 is not set."
1065 :group 'org-structure
1066 :type 'plist)
1068 (defgroup org-cycle nil
1069 "Options concerning visibility cycling in Org-mode."
1070 :tag "Org Cycle"
1071 :group 'org-structure)
1073 (defcustom org-cycle-skip-children-state-if-no-children t
1074 "Non-nil means skip CHILDREN state in entries that don't have any."
1075 :group 'org-cycle
1076 :type 'boolean)
1078 (defcustom org-cycle-max-level nil
1079 "Maximum level which should still be subject to visibility cycling.
1080 Levels higher than this will, for cycling, be treated as text, not a headline.
1081 When `org-odd-levels-only' is set, a value of N in this variable actually
1082 means 2N-1 stars as the limiting headline.
1083 When nil, cycle all levels.
1084 Note that the limiting level of cycling is also influenced by
1085 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1086 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1087 than its value."
1088 :group 'org-cycle
1089 :type '(choice
1090 (const :tag "No limit" nil)
1091 (integer :tag "Maximum level")))
1093 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
1094 "Names of drawers. Drawers are not opened by cycling on the headline above.
1095 Drawers only open with a TAB on the drawer line itself. A drawer looks like
1096 this:
1097 :DRAWERNAME:
1098 .....
1099 :END:
1100 The drawer \"PROPERTIES\" is special for capturing properties through
1101 the property API.
1103 Drawers can be defined on the per-file basis with a line like:
1105 #+DRAWERS: HIDDEN STATE PROPERTIES"
1106 :group 'org-structure
1107 :group 'org-cycle
1108 :type '(repeat (string :tag "Drawer Name")))
1110 (defcustom org-hide-block-startup nil
1111 "Non-nil means entering Org-mode will fold all blocks.
1112 This can also be set in on a per-file basis with
1114 #+STARTUP: hideblocks
1115 #+STARTUP: showblocks"
1116 :group 'org-startup
1117 :group 'org-cycle
1118 :type 'boolean)
1120 (defcustom org-cycle-global-at-bob nil
1121 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1122 This makes it possible to do global cycling without having to use S-TAB or
1123 \\[universal-argument] TAB. For this special case to work, the first line
1124 of the buffer must not be a headline -- it may be empty or some other text.
1125 When used in this way, `org-cycle-hook' is disabled temporarily to make
1126 sure the cursor stays at the beginning of the buffer. When this option is
1127 nil, don't do anything special at the beginning of the buffer."
1128 :group 'org-cycle
1129 :type 'boolean)
1131 (defcustom org-cycle-level-after-item/entry-creation t
1132 "Non-nil means cycle entry level or item indentation in new empty entries.
1134 When the cursor is at the end of an empty headline, i.e., with only stars
1135 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1136 and then all possible ancestor states, before returning to the original state.
1137 This makes data entry extremely fast: M-RET to create a new headline,
1138 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1140 When the cursor is at the end of an empty plain list item, one TAB will
1141 make it a subitem, two or more tabs will back up to make this an item
1142 higher up in the item hierarchy."
1143 :group 'org-cycle
1144 :type 'boolean)
1146 (defcustom org-cycle-emulate-tab t
1147 "Where should `org-cycle' emulate TAB.
1148 nil Never
1149 white Only in completely white lines
1150 whitestart Only at the beginning of lines, before the first non-white char
1151 t Everywhere except in headlines
1152 exc-hl-bol Everywhere except at the start of a headline
1153 If TAB is used in a place where it does not emulate TAB, the current subtree
1154 visibility is cycled."
1155 :group 'org-cycle
1156 :type '(choice (const :tag "Never" nil)
1157 (const :tag "Only in completely white lines" white)
1158 (const :tag "Before first char in a line" whitestart)
1159 (const :tag "Everywhere except in headlines" t)
1160 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1162 (defcustom org-cycle-separator-lines 2
1163 "Number of empty lines needed to keep an empty line between collapsed trees.
1164 If you leave an empty line between the end of a subtree and the following
1165 headline, this empty line is hidden when the subtree is folded.
1166 Org-mode will leave (exactly) one empty line visible if the number of
1167 empty lines is equal or larger to the number given in this variable.
1168 So the default 2 means at least 2 empty lines after the end of a subtree
1169 are needed to produce free space between a collapsed subtree and the
1170 following headline.
1172 If the number is negative, and the number of empty lines is at least -N,
1173 all empty lines are shown.
1175 Special case: when 0, never leave empty lines in collapsed view."
1176 :group 'org-cycle
1177 :type 'integer)
1178 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1180 (defcustom org-pre-cycle-hook nil
1181 "Hook that is run before visibility cycling is happening.
1182 The function(s) in this hook must accept a single argument which indicates
1183 the new state that will be set right after running this hook. The
1184 argument is a symbol. Before a global state change, it can have the values
1185 `overview', `content', or `all'. Before a local state change, it can have
1186 the values `folded', `children', or `subtree'."
1187 :group 'org-cycle
1188 :type 'hook)
1190 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1191 org-cycle-hide-drawers
1192 org-cycle-hide-inline-tasks
1193 org-cycle-show-empty-lines
1194 org-optimize-window-after-visibility-change)
1195 "Hook that is run after `org-cycle' has changed the buffer visibility.
1196 The function(s) in this hook must accept a single argument which indicates
1197 the new state that was set by the most recent `org-cycle' command. The
1198 argument is a symbol. After a global state change, it can have the values
1199 `overview', `contents', or `all'. After a local state change, it can have
1200 the values `folded', `children', or `subtree'."
1201 :group 'org-cycle
1202 :type 'hook)
1204 (defgroup org-edit-structure nil
1205 "Options concerning structure editing in Org-mode."
1206 :tag "Org Edit Structure"
1207 :group 'org-structure)
1209 (defcustom org-odd-levels-only nil
1210 "Non-nil means skip even levels and only use odd levels for the outline.
1211 This has the effect that two stars are being added/taken away in
1212 promotion/demotion commands. It also influences how levels are
1213 handled by the exporters.
1214 Changing it requires restart of `font-lock-mode' to become effective
1215 for fontification also in regions already fontified.
1216 You may also set this on a per-file basis by adding one of the following
1217 lines to the buffer:
1219 #+STARTUP: odd
1220 #+STARTUP: oddeven"
1221 :group 'org-edit-structure
1222 :group 'org-appearance
1223 :type 'boolean)
1225 (defcustom org-adapt-indentation t
1226 "Non-nil means adapt indentation to outline node level.
1228 When this variable is set, Org assumes that you write outlines by
1229 indenting text in each node to align with the headline (after the stars).
1230 The following issues are influenced by this variable:
1232 - When this is set and the *entire* text in an entry is indented, the
1233 indentation is increased by one space in a demotion command, and
1234 decreased by one in a promotion command. If any line in the entry
1235 body starts with text at column 0, indentation is not changed at all.
1237 - Property drawers and planning information is inserted indented when
1238 this variable s set. When nil, they will not be indented.
1240 - TAB indents a line relative to context. The lines below a headline
1241 will be indented when this variable is set.
1243 Note that this is all about true indentation, by adding and removing
1244 space characters. See also `org-indent.el' which does level-dependent
1245 indentation in a virtual way, i.e. at display time in Emacs."
1246 :group 'org-edit-structure
1247 :type 'boolean)
1249 (defcustom org-special-ctrl-a/e nil
1250 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1252 When t, `C-a' will bring back the cursor to the beginning of the
1253 headline text, i.e. after the stars and after a possible TODO
1254 keyword. In an item, this will be the position after bullet and
1255 check-box, if any. When the cursor is already at that position,
1256 another `C-a' will bring it to the beginning of the line.
1258 `C-e' will jump to the end of the headline, ignoring the presence
1259 of tags in the headline. A second `C-e' will then jump to the
1260 true end of the line, after any tags. This also means that, when
1261 this variable is non-nil, `C-e' also will never jump beyond the
1262 end of the heading of a folded section, i.e. not after the
1263 ellipses.
1265 When set to the symbol `reversed', the first `C-a' or `C-e' works
1266 normally, going to the true line boundary first. Only a directly
1267 following, identical keypress will bring the cursor to the
1268 special positions.
1270 This may also be a cons cell where the behavior for `C-a' and
1271 `C-e' is set separately."
1272 :group 'org-edit-structure
1273 :type '(choice
1274 (const :tag "off" nil)
1275 (const :tag "on: after stars/bullet and before tags first" t)
1276 (const :tag "reversed: true line boundary first" reversed)
1277 (cons :tag "Set C-a and C-e separately"
1278 (choice :tag "Special C-a"
1279 (const :tag "off" nil)
1280 (const :tag "on: after stars/bullet first" t)
1281 (const :tag "reversed: before stars/bullet first" reversed))
1282 (choice :tag "Special C-e"
1283 (const :tag "off" nil)
1284 (const :tag "on: before tags first" t)
1285 (const :tag "reversed: after tags first" reversed)))))
1286 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1288 (defcustom org-special-ctrl-k nil
1289 "Non-nil means `C-k' will behave specially in headlines.
1290 When nil, `C-k' will call the default `kill-line' command.
1291 When t, the following will happen while the cursor is in the headline:
1293 - When the cursor is at the beginning of a headline, kill the entire
1294 line and possible the folded subtree below the line.
1295 - When in the middle of the headline text, kill the headline up to the tags.
1296 - When after the headline text, kill the tags."
1297 :group 'org-edit-structure
1298 :type 'boolean)
1300 (defcustom org-ctrl-k-protect-subtree nil
1301 "Non-nil means, do not delete a hidden subtree with C-k.
1302 When set to the symbol `error', simply throw an error when C-k is
1303 used to kill (part-of) a headline that has hidden text behind it.
1304 Any other non-nil value will result in a query to the user, if it is
1305 OK to kill that hidden subtree. When nil, kill without remorse."
1306 :group 'org-edit-structure
1307 :version "24.1"
1308 :type '(choice
1309 (const :tag "Do not protect hidden subtrees" nil)
1310 (const :tag "Protect hidden subtrees with a security query" t)
1311 (const :tag "Never kill a hidden subtree with C-k" error)))
1313 (defcustom org-special-ctrl-o t
1314 "Non-nil means, make `C-o' insert a row in tables."
1315 :group 'org-edit-structure
1316 :type 'boolean)
1318 (defcustom org-catch-invisible-edits nil
1319 "Check if in invisible region before inserting or deleting a character.
1320 Valid values are:
1322 nil Do not check, so just do invisible edits.
1323 error Throw an error and do nothing.
1324 show Make point visible, and do the requested edit.
1325 show-and-error Make point visible, then throw an error and abort the edit.
1326 smart Make point visible, and do insertion/deletion if it is
1327 adjacent to visible text and the change feels predictable.
1328 Never delete a previously invisible character or add in the
1329 middle or right after an invisible region. Basically, this
1330 allows insertion and backward-delete right before ellipses.
1331 FIXME: maybe in this case we should not even show?"
1332 :group 'org-edit-structure
1333 :version "24.1"
1334 :type '(choice
1335 (const :tag "Do not check" nil)
1336 (const :tag "Throw error when trying to edit" error)
1337 (const :tag "Unhide, but do not do the edit" show-and-error)
1338 (const :tag "Show invisible part and do the edit" show)
1339 (const :tag "Be smart and do the right thing" smart)))
1341 (defcustom org-yank-folded-subtrees t
1342 "Non-nil means when yanking subtrees, fold them.
1343 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1344 it starts with a heading and all other headings in it are either children
1345 or siblings, then fold all the subtrees. However, do this only if no
1346 text after the yank would be swallowed into a folded tree by this action."
1347 :group 'org-edit-structure
1348 :type 'boolean)
1350 (defcustom org-yank-adjusted-subtrees nil
1351 "Non-nil means when yanking subtrees, adjust the level.
1352 With this setting, `org-paste-subtree' is used to insert the subtree, see
1353 this function for details."
1354 :group 'org-edit-structure
1355 :type 'boolean)
1357 (defcustom org-M-RET-may-split-line '((default . t))
1358 "Non-nil means M-RET will split the line at the cursor position.
1359 When nil, it will go to the end of the line before making a
1360 new line.
1361 You may also set this option in a different way for different
1362 contexts. Valid contexts are:
1364 headline when creating a new headline
1365 item when creating a new item
1366 table in a table field
1367 default the value to be used for all contexts not explicitly
1368 customized"
1369 :group 'org-structure
1370 :group 'org-table
1371 :type '(choice
1372 (const :tag "Always" t)
1373 (const :tag "Never" nil)
1374 (repeat :greedy t :tag "Individual contexts"
1375 (cons
1376 (choice :tag "Context"
1377 (const headline)
1378 (const item)
1379 (const table)
1380 (const default))
1381 (boolean)))))
1384 (defcustom org-insert-heading-respect-content nil
1385 "Non-nil means insert new headings after the current subtree.
1386 When nil, the new heading is created directly after the current line.
1387 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1388 this variable on for the duration of the command."
1389 :group 'org-structure
1390 :type 'boolean)
1392 (defcustom org-blank-before-new-entry '((heading . auto)
1393 (plain-list-item . auto))
1394 "Should `org-insert-heading' leave a blank line before new heading/item?
1395 The value is an alist, with `heading' and `plain-list-item' as CAR,
1396 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1397 which case Org will look at the surrounding headings/items and try to
1398 make an intelligent decision whether to insert a blank line or not.
1400 For plain lists, if `org-list-empty-line-terminates-plain-lists' is set,
1401 the setting here is ignored and no empty line is inserted to avoid breaking
1402 the list structure."
1403 :group 'org-edit-structure
1404 :type '(list
1405 (cons (const heading)
1406 (choice (const :tag "Never" nil)
1407 (const :tag "Always" t)
1408 (const :tag "Auto" auto)))
1409 (cons (const plain-list-item)
1410 (choice (const :tag "Never" nil)
1411 (const :tag "Always" t)
1412 (const :tag "Auto" auto)))))
1414 (defcustom org-insert-heading-hook nil
1415 "Hook being run after inserting a new heading."
1416 :group 'org-edit-structure
1417 :type 'hook)
1419 (defcustom org-enable-fixed-width-editor t
1420 "Non-nil means lines starting with \":\" are treated as fixed-width.
1421 This currently only means they are never auto-wrapped.
1422 When nil, such lines will be treated like ordinary lines.
1423 See also the QUOTE keyword."
1424 :group 'org-edit-structure
1425 :type 'boolean)
1427 (defcustom org-goto-auto-isearch t
1428 "Non-nil means typing characters in `org-goto' starts incremental search.
1429 When nil, you can use these keybindings to navigate the buffer:
1431 q Quit the org-goto interface
1432 n Go to the next visible heading
1433 p Go to the previous visible heading
1434 f Go one heading forward on same level
1435 b Go one heading backward on same level
1436 u Go one heading up"
1437 :group 'org-edit-structure
1438 :type 'boolean)
1440 (defgroup org-sparse-trees nil
1441 "Options concerning sparse trees in Org-mode."
1442 :tag "Org Sparse Trees"
1443 :group 'org-structure)
1445 (defcustom org-highlight-sparse-tree-matches t
1446 "Non-nil means highlight all matches that define a sparse tree.
1447 The highlights will automatically disappear the next time the buffer is
1448 changed by an edit command."
1449 :group 'org-sparse-trees
1450 :type 'boolean)
1452 (defcustom org-remove-highlights-with-change t
1453 "Non-nil means any change to the buffer will remove temporary highlights.
1454 Such highlights are created by `org-occur' and `org-clock-display'.
1455 When nil, `C-c C-c needs to be used to get rid of the highlights.
1456 The highlights created by `org-preview-latex-fragment' always need
1457 `C-c C-c' to be removed."
1458 :group 'org-sparse-trees
1459 :group 'org-time
1460 :type 'boolean)
1463 (defcustom org-occur-hook '(org-first-headline-recenter)
1464 "Hook that is run after `org-occur' has constructed a sparse tree.
1465 This can be used to recenter the window to show as much of the structure
1466 as possible."
1467 :group 'org-sparse-trees
1468 :type 'hook)
1470 (defgroup org-imenu-and-speedbar nil
1471 "Options concerning imenu and speedbar in Org-mode."
1472 :tag "Org Imenu and Speedbar"
1473 :group 'org-structure)
1475 (defcustom org-imenu-depth 2
1476 "The maximum level for Imenu access to Org-mode headlines.
1477 This also applied for speedbar access."
1478 :group 'org-imenu-and-speedbar
1479 :type 'integer)
1481 (defgroup org-table nil
1482 "Options concerning tables in Org-mode."
1483 :tag "Org Table"
1484 :group 'org)
1486 (defcustom org-enable-table-editor 'optimized
1487 "Non-nil means lines starting with \"|\" are handled by the table editor.
1488 When nil, such lines will be treated like ordinary lines.
1490 When equal to the symbol `optimized', the table editor will be optimized to
1491 do the following:
1492 - Automatic overwrite mode in front of whitespace in table fields.
1493 This makes the structure of the table stay in tact as long as the edited
1494 field does not exceed the column width.
1495 - Minimize the number of realigns. Normally, the table is aligned each time
1496 TAB or RET are pressed to move to another field. With optimization this
1497 happens only if changes to a field might have changed the column width.
1498 Optimization requires replacing the functions `self-insert-command',
1499 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1500 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1501 very good at guessing when a re-align will be necessary, but you can always
1502 force one with \\[org-ctrl-c-ctrl-c].
1504 If you would like to use the optimized version in Org-mode, but the
1505 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1507 This variable can be used to turn on and off the table editor during a session,
1508 but in order to toggle optimization, a restart is required.
1510 See also the variable `org-table-auto-blank-field'."
1511 :group 'org-table
1512 :type '(choice
1513 (const :tag "off" nil)
1514 (const :tag "on" t)
1515 (const :tag "on, optimized" optimized)))
1517 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1518 (version<= emacs-version "24.1"))
1519 "Non-nil means cluster self-insert commands for undo when possible.
1520 If this is set, then, like in the Emacs command loop, 20 consecutive
1521 characters will be undone together.
1522 This is configurable, because there is some impact on typing performance."
1523 :group 'org-table
1524 :type 'boolean)
1526 (defcustom org-table-tab-recognizes-table.el t
1527 "Non-nil means TAB will automatically notice a table.el table.
1528 When it sees such a table, it moves point into it and - if necessary -
1529 calls `table-recognize-table'."
1530 :group 'org-table-editing
1531 :type 'boolean)
1533 (defgroup org-link nil
1534 "Options concerning links in Org-mode."
1535 :tag "Org Link"
1536 :group 'org)
1538 (defvar org-link-abbrev-alist-local nil
1539 "Buffer-local version of `org-link-abbrev-alist', which see.
1540 The value of this is taken from the #+LINK lines.")
1541 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1543 (defcustom org-link-abbrev-alist nil
1544 "Alist of link abbreviations.
1545 The car of each element is a string, to be replaced at the start of a link.
1546 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1547 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1549 [[linkkey:tag][description]]
1551 The 'linkkey' must be a word word, starting with a letter, followed
1552 by letters, numbers, '-' or '_'.
1554 If REPLACE is a string, the tag will simply be appended to create the link.
1555 If the string contains \"%s\", the tag will be inserted there. If the string
1556 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1557 at that point (see the function `url-hexify-string'). If the string contains
1558 the specifier \"%(my-function)\", then the custom function `my-function' will
1559 be invoked: this function takes the tag as its only argument and must return
1560 a string.
1562 REPLACE may also be a function that will be called with the tag as the
1563 only argument to create the link, which should be returned as a string.
1565 See the manual for examples."
1566 :group 'org-link
1567 :type '(repeat
1568 (cons
1569 (string :tag "Protocol")
1570 (choice
1571 (string :tag "Format")
1572 (function)))))
1574 (defcustom org-descriptive-links t
1575 "Non-nil means Org will display descriptive links.
1576 E.g. [[http://orgmode.org][Org website]] will be displayed as
1577 \"Org Website\", hiding the link itself and just displaying its
1578 description. When set to `nil', Org will display the full links
1579 literally.
1581 You can interactively set the value of this variable by calling
1582 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1583 :group 'org-link
1584 :type 'boolean)
1586 (defcustom org-link-file-path-type 'adaptive
1587 "How the path name in file links should be stored.
1588 Valid values are:
1590 relative Relative to the current directory, i.e. the directory of the file
1591 into which the link is being inserted.
1592 absolute Absolute path, if possible with ~ for home directory.
1593 noabbrev Absolute path, no abbreviation of home directory.
1594 adaptive Use relative path for files in the current directory and sub-
1595 directories of it. For other files, use an absolute path."
1596 :group 'org-link
1597 :type '(choice
1598 (const relative)
1599 (const absolute)
1600 (const noabbrev)
1601 (const adaptive)))
1603 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1604 "Types of links that should be activated in Org-mode files.
1605 This is a list of symbols, each leading to the activation of a certain link
1606 type. In principle, it does not hurt to turn on most link types - there may
1607 be a small gain when turning off unused link types. The types are:
1609 bracket The recommended [[link][description]] or [[link]] links with hiding.
1610 angle Links in angular brackets that may contain whitespace like
1611 <bbdb:Carsten Dominik>.
1612 plain Plain links in normal text, no whitespace, like http://google.com.
1613 radio Text that is matched by a radio target, see manual for details.
1614 tag Tag settings in a headline (link to tag search).
1615 date Time stamps (link to calendar).
1616 footnote Footnote labels.
1618 Changing this variable requires a restart of Emacs to become effective."
1619 :group 'org-link
1620 :type '(set :greedy t
1621 (const :tag "Double bracket links" bracket)
1622 (const :tag "Angular bracket links" angle)
1623 (const :tag "Plain text links" plain)
1624 (const :tag "Radio target matches" radio)
1625 (const :tag "Tags" tag)
1626 (const :tag "Timestamps" date)
1627 (const :tag "Footnotes" footnote)))
1629 (defcustom org-make-link-description-function nil
1630 "Function to use for generating link descriptions from links.
1631 When nil, the link location will be used. This function must take
1632 two parameters: the first one is the link, the second one is the
1633 description generated by `org-insert-link'. The function should
1634 return the description to use."
1635 :group 'org-link
1636 :type '(choice (const nil) (function)))
1638 (defgroup org-link-store nil
1639 "Options concerning storing links in Org-mode."
1640 :tag "Org Store Link"
1641 :group 'org-link)
1643 (defcustom org-url-hexify-p t
1644 "When non-nil, hexify URL when creating a link."
1645 :type 'boolean
1646 :version "24.3"
1647 :group 'org-link-store)
1649 (defcustom org-email-link-description-format "Email %c: %.30s"
1650 "Format of the description part of a link to an email or usenet message.
1651 The following %-escapes will be replaced by corresponding information:
1653 %F full \"From\" field
1654 %f name, taken from \"From\" field, address if no name
1655 %T full \"To\" field
1656 %t first name in \"To\" field, address if no name
1657 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1658 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1659 %s subject
1660 %d date
1661 %m message-id.
1663 You may use normal field width specification between the % and the letter.
1664 This is for example useful to limit the length of the subject.
1666 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1667 :group 'org-link-store
1668 :type 'string)
1670 (defcustom org-from-is-user-regexp
1671 (let (r1 r2)
1672 (when (and user-mail-address (not (string= user-mail-address "")))
1673 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1674 (when (and user-full-name (not (string= user-full-name "")))
1675 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1676 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1677 "Regexp matched against the \"From:\" header of an email or usenet message.
1678 It should match if the message is from the user him/herself."
1679 :group 'org-link-store
1680 :type 'regexp)
1682 (defcustom org-context-in-file-links t
1683 "Non-nil means file links from `org-store-link' contain context.
1684 A search string will be added to the file name with :: as separator and
1685 used to find the context when the link is activated by the command
1686 `org-open-at-point'. When this option is t, the entire active region
1687 will be placed in the search string of the file link. If set to a
1688 positive integer, only the first n lines of context will be stored.
1690 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1691 negates this setting for the duration of the command."
1692 :group 'org-link-store
1693 :type '(choice boolean integer))
1695 (defcustom org-keep-stored-link-after-insertion nil
1696 "Non-nil means keep link in list for entire session.
1698 The command `org-store-link' adds a link pointing to the current
1699 location to an internal list. These links accumulate during a session.
1700 The command `org-insert-link' can be used to insert links into any
1701 Org-mode file (offering completion for all stored links). When this
1702 option is nil, every link which has been inserted once using \\[org-insert-link]
1703 will be removed from the list, to make completing the unused links
1704 more efficient."
1705 :group 'org-link-store
1706 :type 'boolean)
1708 (defgroup org-link-follow nil
1709 "Options concerning following links in Org-mode."
1710 :tag "Org Follow Link"
1711 :group 'org-link)
1713 (defcustom org-link-translation-function nil
1714 "Function to translate links with different syntax to Org syntax.
1715 This can be used to translate links created for example by the Planner
1716 or emacs-wiki packages to Org syntax.
1717 The function must accept two parameters, a TYPE containing the link
1718 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1719 which is everything after the link protocol. It should return a cons
1720 with possibly modified values of type and path.
1721 Org contains a function for this, so if you set this variable to
1722 `org-translate-link-from-planner', you should be able follow many
1723 links created by planner."
1724 :group 'org-link-follow
1725 :type '(choice (const nil) (function)))
1727 (defcustom org-follow-link-hook nil
1728 "Hook that is run after a link has been followed."
1729 :group 'org-link-follow
1730 :type 'hook)
1732 (defcustom org-tab-follows-link nil
1733 "Non-nil means on links TAB will follow the link.
1734 Needs to be set before org.el is loaded.
1735 This really should not be used, it does not make sense, and the
1736 implementation is bad."
1737 :group 'org-link-follow
1738 :type 'boolean)
1740 (defcustom org-return-follows-link nil
1741 "Non-nil means on links RET will follow the link.
1742 In tables, the special behavior of RET has precedence."
1743 :group 'org-link-follow
1744 :type 'boolean)
1746 (defcustom org-mouse-1-follows-link
1747 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1748 "Non-nil means mouse-1 on a link will follow the link.
1749 A longer mouse click will still set point. Does not work on XEmacs.
1750 Needs to be set before org.el is loaded."
1751 :group 'org-link-follow
1752 :version "24.4"
1753 :package-version '(Org . "8.3")
1754 :type '(choice
1755 (const :tag "A double click follows the link" double)
1756 (const :tag "Unconditionally follow the link with mouse-1" t)
1757 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
1759 (defcustom org-mark-ring-length 4
1760 "Number of different positions to be recorded in the ring.
1761 Changing this requires a restart of Emacs to work correctly."
1762 :group 'org-link-follow
1763 :type 'integer)
1765 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1766 "Non-nil means internal links in Org files must exactly match a headline.
1767 When nil, the link search tries to match a phrase with all words
1768 in the search text."
1769 :group 'org-link-follow
1770 :version "24.1"
1771 :type '(choice
1772 (const :tag "Use fuzzy text search" nil)
1773 (const :tag "Match only exact headline" t)
1774 (const :tag "Match exact headline or query to create it"
1775 query-to-create)))
1777 (defcustom org-link-frame-setup
1778 '((vm . vm-visit-folder-other-frame)
1779 (vm-imap . vm-visit-imap-folder-other-frame)
1780 (gnus . org-gnus-no-new-news)
1781 (file . find-file-other-window)
1782 (wl . wl-other-frame))
1783 "Setup the frame configuration for following links.
1784 When following a link with Emacs, it may often be useful to display
1785 this link in another window or frame. This variable can be used to
1786 set this up for the different types of links.
1787 For VM, use any of
1788 `vm-visit-folder'
1789 `vm-visit-folder-other-window'
1790 `vm-visit-folder-other-frame'
1791 For Gnus, use any of
1792 `gnus'
1793 `gnus-other-frame'
1794 `org-gnus-no-new-news'
1795 For FILE, use any of
1796 `find-file'
1797 `find-file-other-window'
1798 `find-file-other-frame'
1799 For Wanderlust use any of
1800 `wl'
1801 `wl-other-frame'
1802 For the calendar, use the variable `calendar-setup'.
1803 For BBDB, it is currently only possible to display the matches in
1804 another window."
1805 :group 'org-link-follow
1806 :type '(list
1807 (cons (const vm)
1808 (choice
1809 (const vm-visit-folder)
1810 (const vm-visit-folder-other-window)
1811 (const vm-visit-folder-other-frame)))
1812 (cons (const vm-imap)
1813 (choice
1814 (const vm-visit-imap-folder)
1815 (const vm-visit-imap-folder-other-window)
1816 (const vm-visit-imap-folder-other-frame)))
1817 (cons (const gnus)
1818 (choice
1819 (const gnus)
1820 (const gnus-other-frame)
1821 (const org-gnus-no-new-news)))
1822 (cons (const file)
1823 (choice
1824 (const find-file)
1825 (const find-file-other-window)
1826 (const find-file-other-frame)))
1827 (cons (const wl)
1828 (choice
1829 (const wl)
1830 (const wl-other-frame)))))
1832 (defcustom org-display-internal-link-with-indirect-buffer nil
1833 "Non-nil means use indirect buffer to display infile links.
1834 Activating internal links (from one location in a file to another location
1835 in the same file) normally just jumps to the location. When the link is
1836 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1837 is displayed in
1838 another window. When this option is set, the other window actually displays
1839 an indirect buffer clone of the current buffer, to avoid any visibility
1840 changes to the current buffer."
1841 :group 'org-link-follow
1842 :type 'boolean)
1844 (defcustom org-open-non-existing-files nil
1845 "Non-nil means `org-open-file' will open non-existing files.
1846 When nil, an error will be generated.
1847 This variable applies only to external applications because they
1848 might choke on non-existing files. If the link is to a file that
1849 will be opened in Emacs, the variable is ignored."
1850 :group 'org-link-follow
1851 :type 'boolean)
1853 (defcustom org-open-directory-means-index-dot-org nil
1854 "Non-nil means a link to a directory really means to index.org.
1855 When nil, following a directory link will run dired or open a finder/explorer
1856 window on that directory."
1857 :group 'org-link-follow
1858 :type 'boolean)
1860 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1861 "Function and arguments to call for following mailto links.
1862 This is a list with the first element being a Lisp function, and the
1863 remaining elements being arguments to the function. In string arguments,
1864 %a will be replaced by the address, and %s will be replaced by the subject
1865 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1866 :group 'org-link-follow
1867 :type '(choice
1868 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1869 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1870 (const :tag "message-mail" (message-mail "%a" "%s"))
1871 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1873 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1874 "Non-nil means ask for confirmation before executing shell links.
1875 Shell links can be dangerous: just think about a link
1877 [[shell:rm -rf ~/*][Google Search]]
1879 This link would show up in your Org-mode document as \"Google Search\",
1880 but really it would remove your entire home directory.
1881 Therefore we advise against setting this variable to nil.
1882 Just change it to `y-or-n-p' if you want to confirm with a
1883 single keystroke rather than having to type \"yes\"."
1884 :group 'org-link-follow
1885 :type '(choice
1886 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1887 (const :tag "with y-or-n (faster)" y-or-n-p)
1888 (const :tag "no confirmation (dangerous)" nil)))
1889 (put 'org-confirm-shell-link-function
1890 'safe-local-variable
1891 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1893 (defcustom org-confirm-shell-link-not-regexp ""
1894 "A regexp to skip confirmation for shell links."
1895 :group 'org-link-follow
1896 :version "24.1"
1897 :type 'regexp)
1899 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1900 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1901 Elisp links can be dangerous: just think about a link
1903 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1905 This link would show up in your Org-mode document as \"Google Search\",
1906 but really it would remove your entire home directory.
1907 Therefore we advise against setting this variable to nil.
1908 Just change it to `y-or-n-p' if you want to confirm with a
1909 single keystroke rather than having to type \"yes\"."
1910 :group 'org-link-follow
1911 :type '(choice
1912 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1913 (const :tag "with y-or-n (faster)" y-or-n-p)
1914 (const :tag "no confirmation (dangerous)" nil)))
1915 (put 'org-confirm-shell-link-function
1916 'safe-local-variable
1917 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1919 (defcustom org-confirm-elisp-link-not-regexp ""
1920 "A regexp to skip confirmation for Elisp links."
1921 :group 'org-link-follow
1922 :version "24.1"
1923 :type 'regexp)
1925 (defconst org-file-apps-defaults-gnu
1926 '((remote . emacs)
1927 (system . mailcap)
1928 (t . mailcap))
1929 "Default file applications on a UNIX or GNU/Linux system.
1930 See `org-file-apps'.")
1932 (defconst org-file-apps-defaults-macosx
1933 '((remote . emacs)
1934 (t . "open %s")
1935 (system . "open %s")
1936 ("ps.gz" . "gv %s")
1937 ("eps.gz" . "gv %s")
1938 ("dvi" . "xdvi %s")
1939 ("fig" . "xfig %s"))
1940 "Default file applications on a MacOS X system.
1941 The system \"open\" is known as a default, but we use X11 applications
1942 for some files for which the OS does not have a good default.
1943 See `org-file-apps'.")
1945 (defconst org-file-apps-defaults-windowsnt
1946 (list
1947 '(remote . emacs)
1948 (cons t
1949 (list (if (featurep 'xemacs)
1950 'mswindows-shell-execute
1951 'w32-shell-execute)
1952 "open" 'file))
1953 (cons 'system
1954 (list (if (featurep 'xemacs)
1955 'mswindows-shell-execute
1956 'w32-shell-execute)
1957 "open" 'file)))
1958 "Default file applications on a Windows NT system.
1959 The system \"open\" is used for most files.
1960 See `org-file-apps'.")
1962 (defcustom org-file-apps
1963 '((auto-mode . emacs)
1964 ("\\.mm\\'" . default)
1965 ("\\.x?html?\\'" . default)
1966 ("\\.pdf\\'" . default))
1967 "External applications for opening `file:path' items in a document.
1968 Org-mode uses system defaults for different file types, but
1969 you can use this variable to set the application for a given file
1970 extension. The entries in this list are cons cells where the car identifies
1971 files and the cdr the corresponding command. Possible values for the
1972 file identifier are
1973 \"string\" A string as a file identifier can be interpreted in different
1974 ways, depending on its contents:
1976 - Alphanumeric characters only:
1977 Match links with this file extension.
1978 Example: (\"pdf\" . \"evince %s\")
1979 to open PDFs with evince.
1981 - Regular expression: Match links where the
1982 filename matches the regexp. If you want to
1983 use groups here, use shy groups.
1985 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1986 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1987 to open *.html and *.xhtml with firefox.
1989 - Regular expression which contains (non-shy) groups:
1990 Match links where the whole link, including \"::\", and
1991 anything after that, matches the regexp.
1992 In a custom command string, %1, %2, etc. are replaced with
1993 the parts of the link that were matched by the groups.
1994 For backwards compatibility, if a command string is given
1995 that does not use any of the group matches, this case is
1996 handled identically to the second one (i.e. match against
1997 file name only).
1998 In a custom lisp form, you can access the group matches with
1999 (match-string n link).
2001 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
2002 to open [[file:document.pdf::5]] with evince at page 5.
2004 `directory' Matches a directory
2005 `remote' Matches a remote file, accessible through tramp or efs.
2006 Remote files most likely should be visited through Emacs
2007 because external applications cannot handle such paths.
2008 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2009 so all files Emacs knows how to handle. Using this with
2010 command `emacs' will open most files in Emacs. Beware that this
2011 will also open html files inside Emacs, unless you add
2012 (\"html\" . default) to the list as well.
2013 t Default for files not matched by any of the other options.
2014 `system' The system command to open files, like `open' on Windows
2015 and Mac OS X, and mailcap under GNU/Linux. This is the command
2016 that will be selected if you call `C-c C-o' with a double
2017 \\[universal-argument] \\[universal-argument] prefix.
2019 Possible values for the command are:
2020 `emacs' The file will be visited by the current Emacs process.
2021 `default' Use the default application for this file type, which is the
2022 association for t in the list, most likely in the system-specific
2023 part.
2024 This can be used to overrule an unwanted setting in the
2025 system-specific variable.
2026 `system' Use the system command for opening files, like \"open\".
2027 This command is specified by the entry whose car is `system'.
2028 Most likely, the system-specific version of this variable
2029 does define this command, but you can overrule/replace it
2030 here.
2031 string A command to be executed by a shell; %s will be replaced
2032 by the path to the file.
2033 sexp A Lisp form which will be evaluated. The file path will
2034 be available in the Lisp variable `file'.
2035 For more examples, see the system specific constants
2036 `org-file-apps-defaults-macosx'
2037 `org-file-apps-defaults-windowsnt'
2038 `org-file-apps-defaults-gnu'."
2039 :group 'org-link-follow
2040 :type '(repeat
2041 (cons (choice :value ""
2042 (string :tag "Extension")
2043 (const :tag "System command to open files" system)
2044 (const :tag "Default for unrecognized files" t)
2045 (const :tag "Remote file" remote)
2046 (const :tag "Links to a directory" directory)
2047 (const :tag "Any files that have Emacs modes"
2048 auto-mode))
2049 (choice :value ""
2050 (const :tag "Visit with Emacs" emacs)
2051 (const :tag "Use default" default)
2052 (const :tag "Use the system command" system)
2053 (string :tag "Command")
2054 (sexp :tag "Lisp form")))))
2056 (defcustom org-doi-server-url "http://dx.doi.org/"
2057 "The URL of the DOI server."
2058 :type 'string
2059 :version "24.3"
2060 :group 'org-link-follow)
2062 (defgroup org-refile nil
2063 "Options concerning refiling entries in Org-mode."
2064 :tag "Org Refile"
2065 :group 'org)
2067 (defcustom org-directory "~/org"
2068 "Directory with org files.
2069 This is just a default location to look for Org files. There is no need
2070 at all to put your files into this directory. It is only used in the
2071 following situations:
2073 1. When a capture template specifies a target file that is not an
2074 absolute path. The path will then be interpreted relative to
2075 `org-directory'
2076 2. When a capture note is filed away in an interactive way (when exiting the
2077 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2078 with `org-directory' as the default path."
2079 :group 'org-refile
2080 :group 'org-capture
2081 :type 'directory)
2083 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2084 "Default target for storing notes.
2085 Used as a fall back file for org-capture.el, for templates that
2086 do not specify a target file."
2087 :group 'org-refile
2088 :group 'org-capture
2089 :type '(choice
2090 (const :tag "Default from remember-data-file" nil)
2091 file))
2093 (defcustom org-goto-interface 'outline
2094 "The default interface to be used for `org-goto'.
2095 Allowed values are:
2096 outline The interface shows an outline of the relevant file
2097 and the correct heading is found by moving through
2098 the outline or by searching with incremental search.
2099 outline-path-completion Headlines in the current buffer are offered via
2100 completion. This is the interface also used by
2101 the refile command."
2102 :group 'org-refile
2103 :type '(choice
2104 (const :tag "Outline" outline)
2105 (const :tag "Outline-path-completion" outline-path-completion)))
2107 (defcustom org-goto-max-level 5
2108 "Maximum target level when running `org-goto' with refile interface."
2109 :group 'org-refile
2110 :type 'integer)
2112 (defcustom org-reverse-note-order nil
2113 "Non-nil means store new notes at the beginning of a file or entry.
2114 When nil, new notes will be filed to the end of a file or entry.
2115 This can also be a list with cons cells of regular expressions that
2116 are matched against file names, and values."
2117 :group 'org-capture
2118 :group 'org-refile
2119 :type '(choice
2120 (const :tag "Reverse always" t)
2121 (const :tag "Reverse never" nil)
2122 (repeat :tag "By file name regexp"
2123 (cons regexp boolean))))
2125 (defcustom org-log-refile nil
2126 "Information to record when a task is refiled.
2128 Possible values are:
2130 nil Don't add anything
2131 time Add a time stamp to the task
2132 note Prompt for a note and add it with template `org-log-note-headings'
2134 This option can also be set with on a per-file-basis with
2136 #+STARTUP: nologrefile
2137 #+STARTUP: logrefile
2138 #+STARTUP: lognoterefile
2140 You can have local logging settings for a subtree by setting the LOGGING
2141 property to one or more of these keywords.
2143 When bulk-refiling from the agenda, the value `note' is forbidden and
2144 will temporarily be changed to `time'."
2145 :group 'org-refile
2146 :group 'org-progress
2147 :version "24.1"
2148 :type '(choice
2149 (const :tag "No logging" nil)
2150 (const :tag "Record timestamp" time)
2151 (const :tag "Record timestamp with note." note)))
2153 (defcustom org-refile-targets nil
2154 "Targets for refiling entries with \\[org-refile].
2155 This is a list of cons cells. Each cell contains:
2156 - a specification of the files to be considered, either a list of files,
2157 or a symbol whose function or variable value will be used to retrieve
2158 a file name or a list of file names. If you use `org-agenda-files' for
2159 that, all agenda files will be scanned for targets. Nil means consider
2160 headings in the current buffer.
2161 - A specification of how to find candidate refile targets. This may be
2162 any of:
2163 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2164 This tag has to be present in all target headlines, inheritance will
2165 not be considered.
2166 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2167 todo keyword.
2168 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2169 headlines that are refiling targets.
2170 - a cons cell (:level . N). Any headline of level N is considered a target.
2171 Note that, when `org-odd-levels-only' is set, level corresponds to
2172 order in hierarchy, not to the number of stars.
2173 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2174 Note that, when `org-odd-levels-only' is set, level corresponds to
2175 order in hierarchy, not to the number of stars.
2177 Each element of this list generates a set of possible targets.
2178 The union of these sets is presented (with completion) to
2179 the user by `org-refile'.
2181 You can set the variable `org-refile-target-verify-function' to a function
2182 to verify each headline found by the simple criteria above.
2184 When this variable is nil, all top-level headlines in the current buffer
2185 are used, equivalent to the value `((nil . (:level . 1))'."
2186 :group 'org-refile
2187 :type '(repeat
2188 (cons
2189 (choice :value org-agenda-files
2190 (const :tag "All agenda files" org-agenda-files)
2191 (const :tag "Current buffer" nil)
2192 (function) (variable) (file))
2193 (choice :tag "Identify target headline by"
2194 (cons :tag "Specific tag" (const :value :tag) (string))
2195 (cons :tag "TODO keyword" (const :value :todo) (string))
2196 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2197 (cons :tag "Level number" (const :value :level) (integer))
2198 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2200 (defcustom org-refile-target-verify-function nil
2201 "Function to verify if the headline at point should be a refile target.
2202 The function will be called without arguments, with point at the
2203 beginning of the headline. It should return t and leave point
2204 where it is if the headline is a valid target for refiling.
2206 If the target should not be selected, the function must return nil.
2207 In addition to this, it may move point to a place from where the search
2208 should be continued. For example, the function may decide that the entire
2209 subtree of the current entry should be excluded and move point to the end
2210 of the subtree."
2211 :group 'org-refile
2212 :type '(choice
2213 (const nil)
2214 (function)))
2216 (defcustom org-refile-use-cache nil
2217 "Non-nil means cache refile targets to speed up the process.
2218 The cache for a particular file will be updated automatically when
2219 the buffer has been killed, or when any of the marker used for flagging
2220 refile targets no longer points at a live buffer.
2221 If you have added new entries to a buffer that might themselves be targets,
2222 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2223 find that easier, `C-u C-u C-u C-c C-w'."
2224 :group 'org-refile
2225 :version "24.1"
2226 :type 'boolean)
2228 (defcustom org-refile-use-outline-path nil
2229 "Non-nil means provide refile targets as paths.
2230 So a level 3 headline will be available as level1/level2/level3.
2232 When the value is `file', also include the file name (without directory)
2233 into the path. In this case, you can also stop the completion after
2234 the file name, to get entries inserted as top level in the file.
2236 When `full-file-path', include the full file path."
2237 :group 'org-refile
2238 :type '(choice
2239 (const :tag "Not" nil)
2240 (const :tag "Yes" t)
2241 (const :tag "Start with file name" file)
2242 (const :tag "Start with full file path" full-file-path)))
2244 (defcustom org-outline-path-complete-in-steps t
2245 "Non-nil means complete the outline path in hierarchical steps.
2246 When Org-mode uses the refile interface to select an outline path
2247 \(see variable `org-refile-use-outline-path'), the completion of
2248 the path can be done is a single go, or if can be done in steps down
2249 the headline hierarchy. Going in steps is probably the best if you
2250 do not use a special completion package like `ido' or `icicles'.
2251 However, when using these packages, going in one step can be very
2252 fast, while still showing the whole path to the entry."
2253 :group 'org-refile
2254 :type 'boolean)
2256 (defcustom org-refile-allow-creating-parent-nodes nil
2257 "Non-nil means allow to create new nodes as refile targets.
2258 New nodes are then created by adding \"/new node name\" to the completion
2259 of an existing node. When the value of this variable is `confirm',
2260 new node creation must be confirmed by the user (recommended).
2261 When nil, the completion must match an existing entry.
2263 Note that, if the new heading is not seen by the criteria
2264 listed in `org-refile-targets', multiple instances of the same
2265 heading would be created by trying again to file under the new
2266 heading."
2267 :group 'org-refile
2268 :type '(choice
2269 (const :tag "Never" nil)
2270 (const :tag "Always" t)
2271 (const :tag "Prompt for confirmation" confirm)))
2273 (defcustom org-refile-active-region-within-subtree nil
2274 "Non-nil means also refile active region within a subtree.
2276 By default `org-refile' doesn't allow refiling regions if they
2277 don't contain a set of subtrees, but it might be convenient to
2278 do so sometimes: in that case, the first line of the region is
2279 converted to a headline before refiling."
2280 :group 'org-refile
2281 :version "24.1"
2282 :type 'boolean)
2284 (defgroup org-todo nil
2285 "Options concerning TODO items in Org-mode."
2286 :tag "Org TODO"
2287 :group 'org)
2289 (defgroup org-progress nil
2290 "Options concerning Progress logging in Org-mode."
2291 :tag "Org Progress"
2292 :group 'org-time)
2294 (defvar org-todo-interpretation-widgets
2295 '((:tag "Sequence (cycling hits every state)" sequence)
2296 (:tag "Type (cycling directly to DONE)" type))
2297 "The available interpretation symbols for customizing `org-todo-keywords'.
2298 Interested libraries should add to this list.")
2300 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2301 "List of TODO entry keyword sequences and their interpretation.
2302 \\<org-mode-map>This is a list of sequences.
2304 Each sequence starts with a symbol, either `sequence' or `type',
2305 indicating if the keywords should be interpreted as a sequence of
2306 action steps, or as different types of TODO items. The first
2307 keywords are states requiring action - these states will select a headline
2308 for inclusion into the global TODO list Org-mode produces. If one of
2309 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2310 signify that no further action is necessary. If \"|\" is not found,
2311 the last keyword is treated as the only DONE state of the sequence.
2313 The command \\[org-todo] cycles an entry through these states, and one
2314 additional state where no keyword is present. For details about this
2315 cycling, see the manual.
2317 TODO keywords and interpretation can also be set on a per-file basis with
2318 the special #+SEQ_TODO and #+TYP_TODO lines.
2320 Each keyword can optionally specify a character for fast state selection
2321 \(in combination with the variable `org-use-fast-todo-selection')
2322 and specifiers for state change logging, using the same syntax that
2323 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2324 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2325 indicates to record a time stamp each time this state is selected.
2327 Each keyword may also specify if a timestamp or a note should be
2328 recorded when entering or leaving the state, by adding additional
2329 characters in the parenthesis after the keyword. This looks like this:
2330 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2331 record only the time of the state change. With X and Y being either
2332 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2333 Y when leaving the state if and only if the *target* state does not
2334 define X. You may omit any of the fast-selection key or X or /Y,
2335 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2337 For backward compatibility, this variable may also be just a list
2338 of keywords. In this case the interpretation (sequence or type) will be
2339 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2340 :group 'org-todo
2341 :group 'org-keywords
2342 :type '(choice
2343 (repeat :tag "Old syntax, just keywords"
2344 (string :tag "Keyword"))
2345 (repeat :tag "New syntax"
2346 (cons
2347 (choice
2348 :tag "Interpretation"
2349 ;;Quick and dirty way to see
2350 ;;`org-todo-interpretations'. This takes the
2351 ;;place of item arguments
2352 :convert-widget
2353 (lambda (widget)
2354 (widget-put widget
2355 :args (mapcar
2356 #'(lambda (x)
2357 (widget-convert
2358 (cons 'const x)))
2359 org-todo-interpretation-widgets))
2360 widget))
2361 (repeat
2362 (string :tag "Keyword"))))))
2364 (defvar org-todo-keywords-1 nil
2365 "All TODO and DONE keywords active in a buffer.")
2366 (make-variable-buffer-local 'org-todo-keywords-1)
2367 (defvar org-todo-keywords-for-agenda nil)
2368 (defvar org-done-keywords-for-agenda nil)
2369 (defvar org-drawers-for-agenda nil)
2370 (defvar org-todo-keyword-alist-for-agenda nil)
2371 (defvar org-tag-alist-for-agenda nil
2372 "Alist of all tags from all agenda files.")
2373 (defvar org-tag-groups-alist-for-agenda nil
2374 "Alist of all groups tags from all current agenda files.")
2375 (defvar org-tag-groups-alist nil)
2376 (make-variable-buffer-local 'org-tag-groups-alist)
2377 (defvar org-agenda-contributing-files nil)
2378 (defvar org-not-done-keywords nil)
2379 (make-variable-buffer-local 'org-not-done-keywords)
2380 (defvar org-done-keywords nil)
2381 (make-variable-buffer-local 'org-done-keywords)
2382 (defvar org-todo-heads nil)
2383 (make-variable-buffer-local 'org-todo-heads)
2384 (defvar org-todo-sets nil)
2385 (make-variable-buffer-local 'org-todo-sets)
2386 (defvar org-todo-log-states nil)
2387 (make-variable-buffer-local 'org-todo-log-states)
2388 (defvar org-todo-kwd-alist nil)
2389 (make-variable-buffer-local 'org-todo-kwd-alist)
2390 (defvar org-todo-key-alist nil)
2391 (make-variable-buffer-local 'org-todo-key-alist)
2392 (defvar org-todo-key-trigger nil)
2393 (make-variable-buffer-local 'org-todo-key-trigger)
2395 (defcustom org-todo-interpretation 'sequence
2396 "Controls how TODO keywords are interpreted.
2397 This variable is in principle obsolete and is only used for
2398 backward compatibility, if the interpretation of todo keywords is
2399 not given already in `org-todo-keywords'. See that variable for
2400 more information."
2401 :group 'org-todo
2402 :group 'org-keywords
2403 :type '(choice (const sequence)
2404 (const type)))
2406 (defcustom org-use-fast-todo-selection t
2407 "Non-nil means use the fast todo selection scheme with C-c C-t.
2408 This variable describes if and under what circumstances the cycling
2409 mechanism for TODO keywords will be replaced by a single-key, direct
2410 selection scheme.
2412 When nil, fast selection is never used.
2414 When the symbol `prefix', it will be used when `org-todo' is called
2415 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2416 `C-u t' in an agenda buffer.
2418 When t, fast selection is used by default. In this case, the prefix
2419 argument forces cycling instead.
2421 In all cases, the special interface is only used if access keys have
2422 actually been assigned by the user, i.e. if keywords in the configuration
2423 are followed by a letter in parenthesis, like TODO(t)."
2424 :group 'org-todo
2425 :type '(choice
2426 (const :tag "Never" nil)
2427 (const :tag "By default" t)
2428 (const :tag "Only with C-u C-c C-t" prefix)))
2430 (defcustom org-provide-todo-statistics t
2431 "Non-nil means update todo statistics after insert and toggle.
2432 ALL-HEADLINES means update todo statistics by including headlines
2433 with no TODO keyword as well, counting them as not done.
2434 A list of TODO keywords means the same, but skip keywords that are
2435 not in this list.
2437 When this is set, todo statistics is updated in the parent of the
2438 current entry each time a todo state is changed."
2439 :group 'org-todo
2440 :type '(choice
2441 (const :tag "Yes, only for TODO entries" t)
2442 (const :tag "Yes, including all entries" all-headlines)
2443 (repeat :tag "Yes, for TODOs in this list"
2444 (string :tag "TODO keyword"))
2445 (other :tag "No TODO statistics" nil)))
2447 (defcustom org-hierarchical-todo-statistics t
2448 "Non-nil means TODO statistics covers just direct children.
2449 When nil, all entries in the subtree are considered.
2450 This has only an effect if `org-provide-todo-statistics' is set.
2451 To set this to nil for only a single subtree, use a COOKIE_DATA
2452 property and include the word \"recursive\" into the value."
2453 :group 'org-todo
2454 :type 'boolean)
2456 (defcustom org-after-todo-state-change-hook nil
2457 "Hook which is run after the state of a TODO item was changed.
2458 The new state (a string with a TODO keyword, or nil) is available in the
2459 Lisp variable `org-state'."
2460 :group 'org-todo
2461 :type 'hook)
2463 (defvar org-blocker-hook nil
2464 "Hook for functions that are allowed to block a state change.
2466 Functions in this hook should not modify the buffer.
2467 Each function gets as its single argument a property list,
2468 see `org-trigger-hook' for more information about this list.
2470 If any of the functions in this hook returns nil, the state change
2471 is blocked.")
2473 (defvar org-trigger-hook nil
2474 "Hook for functions that are triggered by a state change.
2476 Each function gets as its single argument a property list with at
2477 least the following elements:
2479 (:type type-of-change :position pos-at-entry-start
2480 :from old-state :to new-state)
2482 Depending on the type, more properties may be present.
2484 This mechanism is currently implemented for:
2486 TODO state changes
2487 ------------------
2488 :type todo-state-change
2489 :from previous state (keyword as a string), or nil, or a symbol
2490 'todo' or 'done', to indicate the general type of state.
2491 :to new state, like in :from")
2493 (defcustom org-enforce-todo-dependencies nil
2494 "Non-nil means undone TODO entries will block switching the parent to DONE.
2495 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2496 be blocked if any prior sibling is not yet done.
2497 Finally, if the parent is blocked because of ordered siblings of its own,
2498 the child will also be blocked."
2499 :set (lambda (var val)
2500 (set var val)
2501 (if val
2502 (add-hook 'org-blocker-hook
2503 'org-block-todo-from-children-or-siblings-or-parent)
2504 (remove-hook 'org-blocker-hook
2505 'org-block-todo-from-children-or-siblings-or-parent)))
2506 :group 'org-todo
2507 :type 'boolean)
2509 (defcustom org-enforce-todo-checkbox-dependencies nil
2510 "Non-nil means unchecked boxes will block switching the parent to DONE.
2511 When this is nil, checkboxes have no influence on switching TODO states.
2512 When non-nil, you first need to check off all check boxes before the TODO
2513 entry can be switched to DONE.
2514 This variable needs to be set before org.el is loaded, and you need to
2515 restart Emacs after a change to make the change effective. The only way
2516 to change is while Emacs is running is through the customize interface."
2517 :set (lambda (var val)
2518 (set var val)
2519 (if val
2520 (add-hook 'org-blocker-hook
2521 'org-block-todo-from-checkboxes)
2522 (remove-hook 'org-blocker-hook
2523 'org-block-todo-from-checkboxes)))
2524 :group 'org-todo
2525 :type 'boolean)
2527 (defcustom org-treat-insert-todo-heading-as-state-change nil
2528 "Non-nil means inserting a TODO heading is treated as state change.
2529 So when the command \\[org-insert-todo-heading] is used, state change
2530 logging will apply if appropriate. When nil, the new TODO item will
2531 be inserted directly, and no logging will take place."
2532 :group 'org-todo
2533 :type 'boolean)
2535 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2536 "Non-nil means switching TODO states with S-cursor counts as state change.
2537 This is the default behavior. However, setting this to nil allows a
2538 convenient way to select a TODO state and bypass any logging associated
2539 with that."
2540 :group 'org-todo
2541 :type 'boolean)
2543 (defcustom org-todo-state-tags-triggers nil
2544 "Tag changes that should be triggered by TODO state changes.
2545 This is a list. Each entry is
2547 (state-change (tag . flag) .......)
2549 State-change can be a string with a state, and empty string to indicate the
2550 state that has no TODO keyword, or it can be one of the symbols `todo'
2551 or `done', meaning any not-done or done state, respectively."
2552 :group 'org-todo
2553 :group 'org-tags
2554 :type '(repeat
2555 (cons (choice :tag "When changing to"
2556 (const :tag "Not-done state" todo)
2557 (const :tag "Done state" done)
2558 (string :tag "State"))
2559 (repeat
2560 (cons :tag "Tag action"
2561 (string :tag "Tag")
2562 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2564 (defcustom org-log-done nil
2565 "Information to record when a task moves to the DONE state.
2567 Possible values are:
2569 nil Don't add anything, just change the keyword
2570 time Add a time stamp to the task
2571 note Prompt for a note and add it with template `org-log-note-headings'
2573 This option can also be set with on a per-file-basis with
2575 #+STARTUP: nologdone
2576 #+STARTUP: logdone
2577 #+STARTUP: lognotedone
2579 You can have local logging settings for a subtree by setting the LOGGING
2580 property to one or more of these keywords."
2581 :group 'org-todo
2582 :group 'org-progress
2583 :type '(choice
2584 (const :tag "No logging" nil)
2585 (const :tag "Record CLOSED timestamp" time)
2586 (const :tag "Record CLOSED timestamp with note." note)))
2588 ;; Normalize old uses of org-log-done.
2589 (cond
2590 ((eq org-log-done t) (setq org-log-done 'time))
2591 ((and (listp org-log-done) (memq 'done org-log-done))
2592 (setq org-log-done 'note)))
2594 (defcustom org-log-reschedule nil
2595 "Information to record when the scheduling date of a tasks is modified.
2597 Possible values are:
2599 nil Don't add anything, just change the date
2600 time Add a time stamp to the task
2601 note Prompt for a note and add it with template `org-log-note-headings'
2603 This option can also be set with on a per-file-basis with
2605 #+STARTUP: nologreschedule
2606 #+STARTUP: logreschedule
2607 #+STARTUP: lognotereschedule"
2608 :group 'org-todo
2609 :group 'org-progress
2610 :type '(choice
2611 (const :tag "No logging" nil)
2612 (const :tag "Record timestamp" time)
2613 (const :tag "Record timestamp with note." note)))
2615 (defcustom org-log-redeadline nil
2616 "Information to record when the deadline date of a tasks is modified.
2618 Possible values are:
2620 nil Don't add anything, just change the date
2621 time Add a time stamp to the task
2622 note Prompt for a note and add it with template `org-log-note-headings'
2624 This option can also be set with on a per-file-basis with
2626 #+STARTUP: nologredeadline
2627 #+STARTUP: logredeadline
2628 #+STARTUP: lognoteredeadline
2630 You can have local logging settings for a subtree by setting the LOGGING
2631 property to one or more of these keywords."
2632 :group 'org-todo
2633 :group 'org-progress
2634 :type '(choice
2635 (const :tag "No logging" nil)
2636 (const :tag "Record timestamp" time)
2637 (const :tag "Record timestamp with note." note)))
2639 (defcustom org-log-note-clock-out nil
2640 "Non-nil means record a note when clocking out of an item.
2641 This can also be configured on a per-file basis by adding one of
2642 the following lines anywhere in the buffer:
2644 #+STARTUP: lognoteclock-out
2645 #+STARTUP: nolognoteclock-out"
2646 :group 'org-todo
2647 :group 'org-progress
2648 :type 'boolean)
2650 (defcustom org-log-done-with-time t
2651 "Non-nil means the CLOSED time stamp will contain date and time.
2652 When nil, only the date will be recorded."
2653 :group 'org-progress
2654 :type 'boolean)
2656 (defcustom org-log-note-headings
2657 '((done . "CLOSING NOTE %t")
2658 (state . "State %-12s from %-12S %t")
2659 (note . "Note taken on %t")
2660 (reschedule . "Rescheduled from %S on %t")
2661 (delschedule . "Not scheduled, was %S on %t")
2662 (redeadline . "New deadline from %S on %t")
2663 (deldeadline . "Removed deadline, was %S on %t")
2664 (refile . "Refiled on %t")
2665 (clock-out . ""))
2666 "Headings for notes added to entries.
2667 The value is an alist, with the car being a symbol indicating the note
2668 context, and the cdr is the heading to be used. The heading may also be the
2669 empty string.
2670 %t in the heading will be replaced by a time stamp.
2671 %T will be an active time stamp instead the default inactive one
2672 %d will be replaced by a short-format time stamp.
2673 %D will be replaced by an active short-format time stamp.
2674 %s will be replaced by the new TODO state, in double quotes.
2675 %S will be replaced by the old TODO state, in double quotes.
2676 %u will be replaced by the user name.
2677 %U will be replaced by the full user name.
2679 In fact, it is not a good idea to change the `state' entry, because
2680 agenda log mode depends on the format of these entries."
2681 :group 'org-todo
2682 :group 'org-progress
2683 :type '(list :greedy t
2684 (cons (const :tag "Heading when closing an item" done) string)
2685 (cons (const :tag
2686 "Heading when changing todo state (todo sequence only)"
2687 state) string)
2688 (cons (const :tag "Heading when just taking a note" note) string)
2689 (cons (const :tag "Heading when rescheduling" reschedule) string)
2690 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2691 (cons (const :tag "Heading when changing deadline" redeadline) string)
2692 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2693 (cons (const :tag "Heading when refiling" refile) string)
2694 (cons (const :tag "Heading when clocking out" clock-out) string)))
2696 (unless (assq 'note org-log-note-headings)
2697 (push '(note . "%t") org-log-note-headings))
2699 (defcustom org-log-into-drawer nil
2700 "Non-nil means insert state change notes and time stamps into a drawer.
2701 When nil, state changes notes will be inserted after the headline and
2702 any scheduling and clock lines, but not inside a drawer.
2704 The value of this variable should be the name of the drawer to use.
2705 LOGBOOK is proposed as the default drawer for this purpose, you can
2706 also set this to a string to define the drawer of your choice.
2708 A value of t is also allowed, representing \"LOGBOOK\".
2710 A value of t or nil can also be set with on a per-file-basis with
2712 #+STARTUP: logdrawer
2713 #+STARTUP: nologdrawer
2715 If this variable is set, `org-log-state-notes-insert-after-drawers'
2716 will be ignored.
2718 You can set the property LOG_INTO_DRAWER to overrule this setting for
2719 a subtree."
2720 :group 'org-todo
2721 :group 'org-progress
2722 :type '(choice
2723 (const :tag "Not into a drawer" nil)
2724 (const :tag "LOGBOOK" t)
2725 (string :tag "Other")))
2727 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2729 (defun org-log-into-drawer ()
2730 "Return the value of `org-log-into-drawer', but let properties overrule.
2731 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2732 used instead of the default value."
2733 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2734 (cond
2735 ((not p) org-log-into-drawer)
2736 ((equal p "nil") nil)
2737 ((equal p "t") "LOGBOOK")
2738 (t p))))
2740 (defcustom org-log-state-notes-insert-after-drawers nil
2741 "Non-nil means insert state change notes after any drawers in entry.
2742 Only the drawers that *immediately* follow the headline and the
2743 deadline/scheduled line are skipped.
2744 When nil, insert notes right after the heading and perhaps the line
2745 with deadline/scheduling if present.
2747 This variable will have no effect if `org-log-into-drawer' is
2748 set."
2749 :group 'org-todo
2750 :group 'org-progress
2751 :type 'boolean)
2753 (defcustom org-log-states-order-reversed t
2754 "Non-nil means the latest state note will be directly after heading.
2755 When nil, the state change notes will be ordered according to time.
2757 This option can also be set with on a per-file-basis with
2759 #+STARTUP: logstatesreversed
2760 #+STARTUP: nologstatesreversed"
2761 :group 'org-todo
2762 :group 'org-progress
2763 :type 'boolean)
2765 (defcustom org-todo-repeat-to-state nil
2766 "The TODO state to which a repeater should return the repeating task.
2767 By default this is the first task in a TODO sequence, or the previous state
2768 in a TODO_TYP set. But you can specify another task here.
2769 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2770 :group 'org-todo
2771 :version "24.1"
2772 :type '(choice (const :tag "Head of sequence" nil)
2773 (string :tag "Specific state")))
2775 (defcustom org-log-repeat 'time
2776 "Non-nil means record moving through the DONE state when triggering repeat.
2777 An auto-repeating task is immediately switched back to TODO when
2778 marked DONE. If you are not logging state changes (by adding \"@\"
2779 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2780 record a closing note, there will be no record of the task moving
2781 through DONE. This variable forces taking a note anyway.
2783 nil Don't force a record
2784 time Record a time stamp
2785 note Prompt for a note and add it with template `org-log-note-headings'
2787 This option can also be set with on a per-file-basis with
2789 #+STARTUP: nologrepeat
2790 #+STARTUP: logrepeat
2791 #+STARTUP: lognoterepeat
2793 You can have local logging settings for a subtree by setting the LOGGING
2794 property to one or more of these keywords."
2795 :group 'org-todo
2796 :group 'org-progress
2797 :type '(choice
2798 (const :tag "Don't force a record" nil)
2799 (const :tag "Force recording the DONE state" time)
2800 (const :tag "Force recording a note with the DONE state" note)))
2803 (defgroup org-priorities nil
2804 "Priorities in Org-mode."
2805 :tag "Org Priorities"
2806 :group 'org-todo)
2808 (defcustom org-enable-priority-commands t
2809 "Non-nil means priority commands are active.
2810 When nil, these commands will be disabled, so that you never accidentally
2811 set a priority."
2812 :group 'org-priorities
2813 :type 'boolean)
2815 (defcustom org-highest-priority ?A
2816 "The highest priority of TODO items. A character like ?A, ?B etc.
2817 Must have a smaller ASCII number than `org-lowest-priority'."
2818 :group 'org-priorities
2819 :type 'character)
2821 (defcustom org-lowest-priority ?C
2822 "The lowest priority of TODO items. A character like ?A, ?B etc.
2823 Must have a larger ASCII number than `org-highest-priority'."
2824 :group 'org-priorities
2825 :type 'character)
2827 (defcustom org-default-priority ?B
2828 "The default priority of TODO items.
2829 This is the priority an item gets if no explicit priority is given.
2830 When starting to cycle on an empty priority the first step in the cycle
2831 depends on `org-priority-start-cycle-with-default'. The resulting first
2832 step priority must not exceed the range from `org-highest-priority' to
2833 `org-lowest-priority' which means that `org-default-priority' has to be
2834 in this range exclusive or inclusive the range boundaries. Else the
2835 first step refuses to set the default and the second will fall back
2836 to (depending on the command used) the highest or lowest priority."
2837 :group 'org-priorities
2838 :type 'character)
2840 (defcustom org-priority-start-cycle-with-default t
2841 "Non-nil means start with default priority when starting to cycle.
2842 When this is nil, the first step in the cycle will be (depending on the
2843 command used) one higher or lower than the default priority.
2844 See also `org-default-priority'."
2845 :group 'org-priorities
2846 :type 'boolean)
2848 (defcustom org-get-priority-function nil
2849 "Function to extract the priority from a string.
2850 The string is normally the headline. If this is nil Org computes the
2851 priority from the priority cookie like [#A] in the headline. It returns
2852 an integer, increasing by 1000 for each priority level.
2853 The user can set a different function here, which should take a string
2854 as an argument and return the numeric priority."
2855 :group 'org-priorities
2856 :version "24.1"
2857 :type '(choice
2858 (const nil)
2859 (function)))
2861 (defgroup org-time nil
2862 "Options concerning time stamps and deadlines in Org-mode."
2863 :tag "Org Time"
2864 :group 'org)
2866 (defcustom org-insert-labeled-timestamps-at-point nil
2867 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2868 When nil, these labeled time stamps are forces into the second line of an
2869 entry, just after the headline. When scheduling from the global TODO list,
2870 the time stamp will always be forced into the second line."
2871 :group 'org-time
2872 :type 'boolean)
2874 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2875 "Formats for `format-time-string' which are used for time stamps.
2876 It is not recommended to change this constant.")
2878 (defcustom org-time-stamp-rounding-minutes '(0 5)
2879 "Number of minutes to round time stamps to.
2880 These are two values, the first applies when first creating a time stamp.
2881 The second applies when changing it with the commands `S-up' and `S-down'.
2882 When changing the time stamp, this means that it will change in steps
2883 of N minutes, as given by the second value.
2885 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2886 numbers should be factors of 60, so for example 5, 10, 15.
2888 When this is larger than 1, you can still force an exact time stamp by using
2889 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2890 and by using a prefix arg to `S-up/down' to specify the exact number
2891 of minutes to shift."
2892 :group 'org-time
2893 :get #'(lambda (var) ; Make sure both elements are there
2894 (if (integerp (default-value var))
2895 (list (default-value var) 5)
2896 (default-value var)))
2897 :type '(list
2898 (integer :tag "when inserting times")
2899 (integer :tag "when modifying times")))
2901 ;; Normalize old customizations of this variable.
2902 (when (integerp org-time-stamp-rounding-minutes)
2903 (setq org-time-stamp-rounding-minutes
2904 (list org-time-stamp-rounding-minutes
2905 org-time-stamp-rounding-minutes)))
2907 (defcustom org-display-custom-times nil
2908 "Non-nil means overlay custom formats over all time stamps.
2909 The formats are defined through the variable `org-time-stamp-custom-formats'.
2910 To turn this on on a per-file basis, insert anywhere in the file:
2911 #+STARTUP: customtime"
2912 :group 'org-time
2913 :set 'set-default
2914 :type 'sexp)
2915 (make-variable-buffer-local 'org-display-custom-times)
2917 (defcustom org-time-stamp-custom-formats
2918 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2919 "Custom formats for time stamps. See `format-time-string' for the syntax.
2920 These are overlaid over the default ISO format if the variable
2921 `org-display-custom-times' is set. Time like %H:%M should be at the
2922 end of the second format. The custom formats are also honored by export
2923 commands, if custom time display is turned on at the time of export."
2924 :group 'org-time
2925 :type 'sexp)
2927 (defun org-time-stamp-format (&optional long inactive)
2928 "Get the right format for a time string."
2929 (let ((f (if long (cdr org-time-stamp-formats)
2930 (car org-time-stamp-formats))))
2931 (if inactive
2932 (concat "[" (substring f 1 -1) "]")
2933 f)))
2935 (defcustom org-time-clocksum-format
2936 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2937 "The format string used when creating CLOCKSUM lines.
2938 This is also used when Org mode generates a time duration.
2940 The value can be a single format string containing two
2941 %-sequences, which will be filled with the number of hours and
2942 minutes in that order.
2944 Alternatively, the value can be a plist associating any of the
2945 keys :years, :months, :weeks, :days, :hours or :minutes with
2946 format strings. The time duration is formatted using only the
2947 time components that are needed and concatenating the results.
2948 If a time unit in absent, it falls back to the next smallest
2949 unit.
2951 The keys :require-years, :require-months, :require-days,
2952 :require-weeks, :require-hours, :require-minutes are also
2953 meaningful. A non-nil value for these keys indicates that the
2954 corresponding time component should always be included, even if
2955 its value is 0.
2958 For example,
2960 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2961 :require-minutes t)
2963 means durations longer than a day will be expressed in days,
2964 hours and minutes, and durations less than a day will always be
2965 expressed in hours and minutes (even for durations less than an
2966 hour).
2968 The value
2970 \(:days \"%dd\" :minutes \"%dm\")
2972 means durations longer than a day will be expressed in days and
2973 minutes, and durations less than a day will be expressed entirely
2974 in minutes (even for durations longer than an hour)."
2975 :group 'org-time
2976 :group 'org-clock
2977 :version "24.4"
2978 :package-version '(Org . "8.0")
2979 :type '(choice (string :tag "Format string")
2980 (set :tag "Plist"
2981 (group :inline t (const :tag "Years" :years)
2982 (string :tag "Format string"))
2983 (group :inline t
2984 (const :tag "Always show years" :require-years)
2985 (const t))
2986 (group :inline t (const :tag "Months" :months)
2987 (string :tag "Format string"))
2988 (group :inline t
2989 (const :tag "Always show months" :require-months)
2990 (const t))
2991 (group :inline t (const :tag "Weeks" :weeks)
2992 (string :tag "Format string"))
2993 (group :inline t
2994 (const :tag "Always show weeks" :require-weeks)
2995 (const t))
2996 (group :inline t (const :tag "Days" :days)
2997 (string :tag "Format string"))
2998 (group :inline t
2999 (const :tag "Always show days" :require-days)
3000 (const t))
3001 (group :inline t (const :tag "Hours" :hours)
3002 (string :tag "Format string"))
3003 (group :inline t
3004 (const :tag "Always show hours" :require-hours)
3005 (const t))
3006 (group :inline t (const :tag "Minutes" :minutes)
3007 (string :tag "Format string"))
3008 (group :inline t
3009 (const :tag "Always show minutes" :require-minutes)
3010 (const t)))))
3012 (defcustom org-time-clocksum-use-fractional nil
3013 "When non-nil, \\[org-clock-display] uses fractional times.
3014 See `org-time-clocksum-format' for more on time clock formats."
3015 :group 'org-time
3016 :group 'org-clock
3017 :version "24.3"
3018 :type 'boolean)
3020 (defcustom org-time-clocksum-use-effort-durations nil
3021 "When non-nil, \\[org-clock-display] uses effort durations.
3022 E.g. by default, one day is considered to be a 8 hours effort,
3023 so a task that has been clocked for 16 hours will be displayed
3024 as during 2 days in the clock display or in the clocktable.
3026 See `org-effort-durations' on how to set effort durations
3027 and `org-time-clocksum-format' for more on time clock formats."
3028 :group 'org-time
3029 :group 'org-clock
3030 :version "24.4"
3031 :package-version '(Org . "8.0")
3032 :type 'boolean)
3034 (defcustom org-time-clocksum-fractional-format "%.2f"
3035 "The format string used when creating CLOCKSUM lines,
3036 or when Org mode generates a time duration, if
3037 `org-time-clocksum-use-fractional' is enabled.
3039 The value can be a single format string containing one
3040 %-sequence, which will be filled with the number of hours as
3041 a float.
3043 Alternatively, the value can be a plist associating any of the
3044 keys :years, :months, :weeks, :days, :hours or :minutes with
3045 a format string. The time duration is formatted using the
3046 largest time unit which gives a non-zero integer part. If all
3047 specified formats have zero integer part, the smallest time unit
3048 is used."
3049 :group 'org-time
3050 :type '(choice (string :tag "Format string")
3051 (set (group :inline t (const :tag "Years" :years)
3052 (string :tag "Format string"))
3053 (group :inline t (const :tag "Months" :months)
3054 (string :tag "Format string"))
3055 (group :inline t (const :tag "Weeks" :weeks)
3056 (string :tag "Format string"))
3057 (group :inline t (const :tag "Days" :days)
3058 (string :tag "Format string"))
3059 (group :inline t (const :tag "Hours" :hours)
3060 (string :tag "Format string"))
3061 (group :inline t (const :tag "Minutes" :minutes)
3062 (string :tag "Format string")))))
3064 (defcustom org-deadline-warning-days 14
3065 "Number of days before expiration during which a deadline becomes active.
3066 This variable governs the display in sparse trees and in the agenda.
3067 When 0 or negative, it means use this number (the absolute value of it)
3068 even if a deadline has a different individual lead time specified.
3070 Custom commands can set this variable in the options section."
3071 :group 'org-time
3072 :group 'org-agenda-daily/weekly
3073 :type 'integer)
3075 (defcustom org-scheduled-delay-days 0
3076 "Number of days before a scheduled item becomes active.
3077 This variable governs the display in sparse trees and in the agenda.
3078 The default value (i.e. 0) means: don't delay scheduled item.
3079 When negative, it means use this number (the absolute value of it)
3080 even if a scheduled item has a different individual delay time
3081 specified.
3083 Custom commands can set this variable in the options section."
3084 :group 'org-time
3085 :group 'org-agenda-daily/weekly
3086 :version "24.4"
3087 :package-version '(Org . "8.0")
3088 :type 'integer)
3090 (defcustom org-read-date-prefer-future t
3091 "Non-nil means assume future for incomplete date input from user.
3092 This affects the following situations:
3093 1. The user gives a month but not a year.
3094 For example, if it is April and you enter \"feb 2\", this will be read
3095 as Feb 2, *next* year. \"May 5\", however, will be this year.
3096 2. The user gives a day, but no month.
3097 For example, if today is the 15th, and you enter \"3\", Org-mode will
3098 read this as the third of *next* month. However, if you enter \"17\",
3099 it will be considered as *this* month.
3101 If you set this variable to the symbol `time', then also the following
3102 will work:
3104 3. If the user gives a time.
3105 If the time is before now, it will be interpreted as tomorrow.
3107 Currently none of this works for ISO week specifications.
3109 When this option is nil, the current day, month and year will always be
3110 used as defaults.
3112 See also `org-agenda-jump-prefer-future'."
3113 :group 'org-time
3114 :type '(choice
3115 (const :tag "Never" nil)
3116 (const :tag "Check month and day" t)
3117 (const :tag "Check month, day, and time" time)))
3119 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3120 "Should the agenda jump command prefer the future for incomplete dates?
3121 The default is to do the same as configured in `org-read-date-prefer-future'.
3122 But you can also set a deviating value here.
3123 This may t or nil, or the symbol `org-read-date-prefer-future'."
3124 :group 'org-agenda
3125 :group 'org-time
3126 :version "24.1"
3127 :type '(choice
3128 (const :tag "Use org-read-date-prefer-future"
3129 org-read-date-prefer-future)
3130 (const :tag "Never" nil)
3131 (const :tag "Always" t)))
3133 (defcustom org-read-date-force-compatible-dates t
3134 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3136 Depending on the system Emacs is running on, certain dates cannot
3137 be represented with the type used internally to represent time.
3138 Dates between 1970-1-1 and 2038-1-1 can always be represented
3139 correctly. Some systems allow for earlier dates, some for later,
3140 some for both. One way to find out it to insert any date into an
3141 Org buffer, putting the cursor on the year and hitting S-up and
3142 S-down to test the range.
3144 When this variable is set to t, the date/time prompt will not let
3145 you specify dates outside the 1970-2037 range, so it is certain that
3146 these dates will work in whatever version of Emacs you are
3147 running, and also that you can move a file from one Emacs implementation
3148 to another. WHenever Org is forcing the year for you, it will display
3149 a message and beep.
3151 When this variable is nil, Org will check if the date is
3152 representable in the specific Emacs implementation you are using.
3153 If not, it will force a year, usually the current year, and beep
3154 to remind you. Currently this setting is not recommended because
3155 the likelihood that you will open your Org files in an Emacs that
3156 has limited date range is not negligible.
3158 A workaround for this problem is to use diary sexp dates for time
3159 stamps outside of this range."
3160 :group 'org-time
3161 :version "24.1"
3162 :type 'boolean)
3164 (defcustom org-read-date-display-live t
3165 "Non-nil means display current interpretation of date prompt live.
3166 This display will be in an overlay, in the minibuffer."
3167 :group 'org-time
3168 :type 'boolean)
3170 (defcustom org-read-date-popup-calendar t
3171 "Non-nil means pop up a calendar when prompting for a date.
3172 In the calendar, the date can be selected with mouse-1. However, the
3173 minibuffer will also be active, and you can simply enter the date as well.
3174 When nil, only the minibuffer will be available."
3175 :group 'org-time
3176 :type 'boolean)
3177 (org-defvaralias 'org-popup-calendar-for-date-prompt
3178 'org-read-date-popup-calendar)
3180 (make-obsolete-variable
3181 'org-read-date-minibuffer-setup-hook
3182 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3183 (defcustom org-read-date-minibuffer-setup-hook nil
3184 "Hook to be used to set up keys for the date/time interface.
3185 Add key definitions to `minibuffer-local-map', which will be a
3186 temporary copy.
3188 WARNING: This option is obsolete, you should use
3189 `org-read-date-minibuffer-local-map' to set up keys."
3190 :group 'org-time
3191 :type 'hook)
3193 (defcustom org-extend-today-until 0
3194 "The hour when your day really ends. Must be an integer.
3195 This has influence for the following applications:
3196 - When switching the agenda to \"today\". It it is still earlier than
3197 the time given here, the day recognized as TODAY is actually yesterday.
3198 - When a date is read from the user and it is still before the time given
3199 here, the current date and time will be assumed to be yesterday, 23:59.
3200 Also, timestamps inserted in capture templates follow this rule.
3202 IMPORTANT: This is a feature whose implementation is and likely will
3203 remain incomplete. Really, it is only here because past midnight seems to
3204 be the favorite working time of John Wiegley :-)"
3205 :group 'org-time
3206 :type 'integer)
3208 (defcustom org-use-effective-time nil
3209 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3210 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3211 \"effective time\" of any timestamps between midnight and 8am will be
3212 23:59 of the previous day."
3213 :group 'org-time
3214 :version "24.1"
3215 :type 'boolean)
3217 (defcustom org-use-last-clock-out-time-as-effective-time nil
3218 "When non-nil, use the last clock out time for `org-todo'.
3219 Note that this option has precedence over the combined use of
3220 `org-use-effective-time' and `org-extend-today-until'."
3221 :group 'org-time
3222 :version "24.4"
3223 :package-version '(Org . "8.0")
3224 :type 'boolean)
3226 (defcustom org-edit-timestamp-down-means-later nil
3227 "Non-nil means S-down will increase the time in a time stamp.
3228 When nil, S-up will increase."
3229 :group 'org-time
3230 :type 'boolean)
3232 (defcustom org-calendar-follow-timestamp-change t
3233 "Non-nil means make the calendar window follow timestamp changes.
3234 When a timestamp is modified and the calendar window is visible, it will be
3235 moved to the new date."
3236 :group 'org-time
3237 :type 'boolean)
3239 (defgroup org-tags nil
3240 "Options concerning tags in Org-mode."
3241 :tag "Org Tags"
3242 :group 'org)
3244 (defcustom org-tag-alist nil
3245 "List of tags allowed in Org-mode files.
3246 When this list is nil, Org-mode will base TAG input on what is already in the
3247 buffer.
3248 The value of this variable is an alist, the car of each entry must be a
3249 keyword as a string, the cdr may be a character that is used to select
3250 that tag through the fast-tag-selection interface.
3251 See the manual for details."
3252 :group 'org-tags
3253 :type '(repeat
3254 (choice
3255 (cons (string :tag "Tag name")
3256 (character :tag "Access char"))
3257 (list :tag "Start radio group"
3258 (const :startgroup)
3259 (option (string :tag "Group description")))
3260 (list :tag "Group tags delimiter"
3261 (const :grouptags))
3262 (list :tag "End radio group"
3263 (const :endgroup)
3264 (option (string :tag "Group description")))
3265 (const :tag "New line" (:newline)))))
3267 (defcustom org-tag-persistent-alist nil
3268 "List of tags that will always appear in all Org-mode files.
3269 This is in addition to any in buffer settings or customizations
3270 of `org-tag-alist'.
3271 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3272 The value of this variable is an alist, the car of each entry must be a
3273 keyword as a string, the cdr may be a character that is used to select
3274 that tag through the fast-tag-selection interface.
3275 See the manual for details.
3276 To disable these tags on a per-file basis, insert anywhere in the file:
3277 #+STARTUP: noptag"
3278 :group 'org-tags
3279 :type '(repeat
3280 (choice
3281 (cons (string :tag "Tag name")
3282 (character :tag "Access char"))
3283 (const :tag "Start radio group" (:startgroup))
3284 (const :tag "Group tags delimiter" (:grouptags))
3285 (const :tag "End radio group" (:endgroup))
3286 (const :tag "New line" (:newline)))))
3288 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3289 "If non-nil, always offer completion for all tags of all agenda files.
3290 Instead of customizing this variable directly, you might want to
3291 set it locally for capture buffers, because there no list of
3292 tags in that file can be created dynamically (there are none).
3294 (add-hook 'org-capture-mode-hook
3295 (lambda ()
3296 (set (make-local-variable
3297 'org-complete-tags-always-offer-all-agenda-tags)
3298 t)))"
3299 :group 'org-tags
3300 :version "24.1"
3301 :type 'boolean)
3303 (defvar org-file-tags nil
3304 "List of tags that can be inherited by all entries in the file.
3305 The tags will be inherited if the variable `org-use-tag-inheritance'
3306 says they should be.
3307 This variable is populated from #+FILETAGS lines.")
3309 (defcustom org-use-fast-tag-selection 'auto
3310 "Non-nil means use fast tag selection scheme.
3311 This is a special interface to select and deselect tags with single keys.
3312 When nil, fast selection is never used.
3313 When the symbol `auto', fast selection is used if and only if selection
3314 characters for tags have been configured, either through the variable
3315 `org-tag-alist' or through a #+TAGS line in the buffer.
3316 When t, fast selection is always used and selection keys are assigned
3317 automatically if necessary."
3318 :group 'org-tags
3319 :type '(choice
3320 (const :tag "Always" t)
3321 (const :tag "Never" nil)
3322 (const :tag "When selection characters are configured" auto)))
3324 (defcustom org-fast-tag-selection-single-key nil
3325 "Non-nil means fast tag selection exits after first change.
3326 When nil, you have to press RET to exit it.
3327 During fast tag selection, you can toggle this flag with `C-c'.
3328 This variable can also have the value `expert'. In this case, the window
3329 displaying the tags menu is not even shown, until you press C-c again."
3330 :group 'org-tags
3331 :type '(choice
3332 (const :tag "No" nil)
3333 (const :tag "Yes" t)
3334 (const :tag "Expert" expert)))
3336 (defvar org-fast-tag-selection-include-todo nil
3337 "Non-nil means fast tags selection interface will also offer TODO states.
3338 This is an undocumented feature, you should not rely on it.")
3340 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3341 "The column to which tags should be indented in a headline.
3342 If this number is positive, it specifies the column. If it is negative,
3343 it means that the tags should be flushright to that column. For example,
3344 -80 works well for a normal 80 character screen.
3345 When 0, place tags directly after headline text, with only one space in
3346 between."
3347 :group 'org-tags
3348 :type 'integer)
3350 (defcustom org-auto-align-tags t
3351 "Non-nil keeps tags aligned when modifying headlines.
3352 Some operations (i.e. demoting) change the length of a headline and
3353 therefore shift the tags around. With this option turned on, after
3354 each such operation the tags are again aligned to `org-tags-column'."
3355 :group 'org-tags
3356 :type 'boolean)
3358 (defcustom org-use-tag-inheritance t
3359 "Non-nil means tags in levels apply also for sublevels.
3360 When nil, only the tags directly given in a specific line apply there.
3361 This may also be a list of tags that should be inherited, or a regexp that
3362 matches tags that should be inherited. Additional control is possible
3363 with the variable `org-tags-exclude-from-inheritance' which gives an
3364 explicit list of tags to be excluded from inheritance, even if the value of
3365 `org-use-tag-inheritance' would select it for inheritance.
3367 If this option is t, a match early-on in a tree can lead to a large
3368 number of matches in the subtree when constructing the agenda or creating
3369 a sparse tree. If you only want to see the first match in a tree during
3370 a search, check out the variable `org-tags-match-list-sublevels'."
3371 :group 'org-tags
3372 :type '(choice
3373 (const :tag "Not" nil)
3374 (const :tag "Always" t)
3375 (repeat :tag "Specific tags" (string :tag "Tag"))
3376 (regexp :tag "Tags matched by regexp")))
3378 (defcustom org-tags-exclude-from-inheritance nil
3379 "List of tags that should never be inherited.
3380 This is a way to exclude a few tags from inheritance. For way to do
3381 the opposite, to actively allow inheritance for selected tags,
3382 see the variable `org-use-tag-inheritance'."
3383 :group 'org-tags
3384 :type '(repeat (string :tag "Tag")))
3386 (defun org-tag-inherit-p (tag)
3387 "Check if TAG is one that should be inherited."
3388 (cond
3389 ((member tag org-tags-exclude-from-inheritance) nil)
3390 ((eq org-use-tag-inheritance t) t)
3391 ((not org-use-tag-inheritance) nil)
3392 ((stringp org-use-tag-inheritance)
3393 (string-match org-use-tag-inheritance tag))
3394 ((listp org-use-tag-inheritance)
3395 (member tag org-use-tag-inheritance))
3396 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3398 (defcustom org-tags-match-list-sublevels t
3399 "Non-nil means list also sublevels of headlines matching a search.
3400 This variable applies to tags/property searches, and also to stuck
3401 projects because this search is based on a tags match as well.
3403 When set to the symbol `indented', sublevels are indented with
3404 leading dots.
3406 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3407 the sublevels of a headline matching a tag search often also match
3408 the same search. Listing all of them can create very long lists.
3409 Setting this variable to nil causes subtrees of a match to be skipped.
3411 This variable is semi-obsolete and probably should always be true. It
3412 is better to limit inheritance to certain tags using the variables
3413 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3414 :group 'org-tags
3415 :type '(choice
3416 (const :tag "No, don't list them" nil)
3417 (const :tag "Yes, do list them" t)
3418 (const :tag "List them, indented with leading dots" indented)))
3420 (defcustom org-tags-sort-function nil
3421 "When set, tags are sorted using this function as a comparator."
3422 :group 'org-tags
3423 :type '(choice
3424 (const :tag "No sorting" nil)
3425 (const :tag "Alphabetical" string<)
3426 (const :tag "Reverse alphabetical" string>)
3427 (function :tag "Custom function" nil)))
3429 (defvar org-tags-history nil
3430 "History of minibuffer reads for tags.")
3431 (defvar org-last-tags-completion-table nil
3432 "The last used completion table for tags.")
3433 (defvar org-after-tags-change-hook nil
3434 "Hook that is run after the tags in a line have changed.")
3436 (defgroup org-properties nil
3437 "Options concerning properties in Org-mode."
3438 :tag "Org Properties"
3439 :group 'org)
3441 (defcustom org-property-format "%-10s %s"
3442 "How property key/value pairs should be formatted by `indent-line'.
3443 When `indent-line' hits a property definition, it will format the line
3444 according to this format, mainly to make sure that the values are
3445 lined-up with respect to each other."
3446 :group 'org-properties
3447 :type 'string)
3449 (defcustom org-properties-postprocess-alist nil
3450 "Alist of properties and functions to adjust inserted values.
3451 Elements of this alist must be of the form
3453 ([string] [function])
3455 where [string] must be a property name and [function] must be a
3456 lambda expression: this lambda expression must take one argument,
3457 the value to adjust, and return the new value as a string.
3459 For example, this element will allow the property \"Remaining\"
3460 to be updated wrt the relation between the \"Effort\" property
3461 and the clock summary:
3463 ((\"Remaining\" (lambda(value)
3464 (let ((clocksum (org-clock-sum-current-item))
3465 (effort (org-duration-string-to-minutes
3466 (org-entry-get (point) \"Effort\"))))
3467 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3468 :group 'org-properties
3469 :version "24.1"
3470 :type '(alist :key-type (string :tag "Property")
3471 :value-type (function :tag "Function")))
3473 (defcustom org-use-property-inheritance nil
3474 "Non-nil means properties apply also for sublevels.
3476 This setting is chiefly used during property searches. Turning it on can
3477 cause significant overhead when doing a search, which is why it is not
3478 on by default.
3480 When nil, only the properties directly given in the current entry count.
3481 When t, every property is inherited. The value may also be a list of
3482 properties that should have inheritance, or a regular expression matching
3483 properties that should be inherited.
3485 However, note that some special properties use inheritance under special
3486 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3487 and the properties ending in \"_ALL\" when they are used as descriptor
3488 for valid values of a property.
3490 Note for programmers:
3491 When querying an entry with `org-entry-get', you can control if inheritance
3492 should be used. By default, `org-entry-get' looks only at the local
3493 properties. You can request inheritance by setting the inherit argument
3494 to t (to force inheritance) or to `selective' (to respect the setting
3495 in this variable)."
3496 :group 'org-properties
3497 :type '(choice
3498 (const :tag "Not" nil)
3499 (const :tag "Always" t)
3500 (repeat :tag "Specific properties" (string :tag "Property"))
3501 (regexp :tag "Properties matched by regexp")))
3503 (defun org-property-inherit-p (property)
3504 "Check if PROPERTY is one that should be inherited."
3505 (cond
3506 ((eq org-use-property-inheritance t) t)
3507 ((not org-use-property-inheritance) nil)
3508 ((stringp org-use-property-inheritance)
3509 (string-match org-use-property-inheritance property))
3510 ((listp org-use-property-inheritance)
3511 (member property org-use-property-inheritance))
3512 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3514 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3515 "The default column format, if no other format has been defined.
3516 This variable can be set on the per-file basis by inserting a line
3518 #+COLUMNS: %25ITEM ....."
3519 :group 'org-properties
3520 :type 'string)
3522 (defcustom org-columns-ellipses ".."
3523 "The ellipses to be used when a field in column view is truncated.
3524 When this is the empty string, as many characters as possible are shown,
3525 but then there will be no visual indication that the field has been truncated.
3526 When this is a string of length N, the last N characters of a truncated
3527 field are replaced by this string. If the column is narrower than the
3528 ellipses string, only part of the ellipses string will be shown."
3529 :group 'org-properties
3530 :type 'string)
3532 (defcustom org-columns-modify-value-for-display-function nil
3533 "Function that modifies values for display in column view.
3534 For example, it can be used to cut out a certain part from a time stamp.
3535 The function must take 2 arguments:
3537 column-title The title of the column (*not* the property name)
3538 value The value that should be modified.
3540 The function should return the value that should be displayed,
3541 or nil if the normal value should be used."
3542 :group 'org-properties
3543 :type '(choice (const nil) (function)))
3545 (defcustom org-effort-property "Effort"
3546 "The property that is being used to keep track of effort estimates.
3547 Effort estimates given in this property need to have the format H:MM."
3548 :group 'org-properties
3549 :group 'org-progress
3550 :type '(string :tag "Property"))
3552 (defconst org-global-properties-fixed
3553 '(("VISIBILITY_ALL" . "folded children content all")
3554 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3555 "List of property/value pairs that can be inherited by any entry.
3557 These are fixed values, for the preset properties. The user variable
3558 that can be used to add to this list is `org-global-properties'.
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. If the value represents
3562 multiple items like an \"_ALL\" property, separate the items by
3563 spaces.")
3565 (defcustom org-global-properties nil
3566 "List of property/value pairs that can be inherited by any entry.
3568 This list will be combined with the constant `org-global-properties-fixed'.
3570 The entries in this list are cons cells where the car is a property
3571 name and cdr is a string with the value.
3573 You can set buffer-local values for the same purpose in the variable
3574 `org-file-properties' this by adding lines like
3576 #+PROPERTY: NAME VALUE"
3577 :group 'org-properties
3578 :type '(repeat
3579 (cons (string :tag "Property")
3580 (string :tag "Value"))))
3582 (defvar org-file-properties nil
3583 "List of property/value pairs that can be inherited by any entry.
3584 Valid for the current buffer.
3585 This variable is populated from #+PROPERTY lines.")
3586 (make-variable-buffer-local 'org-file-properties)
3588 (defgroup org-agenda nil
3589 "Options concerning agenda views in Org-mode."
3590 :tag "Org Agenda"
3591 :group 'org)
3593 (defvar org-category nil
3594 "Variable used by org files to set a category for agenda display.
3595 Such files should use a file variable to set it, for example
3597 # -*- mode: org; org-category: \"ELisp\"
3599 or contain a special line
3601 #+CATEGORY: ELisp
3603 If the file does not specify a category, then file's base name
3604 is used instead.")
3605 (make-variable-buffer-local 'org-category)
3606 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3608 (defcustom org-agenda-files nil
3609 "The files to be used for agenda display.
3610 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3611 \\[org-remove-file]. You can also use customize to edit the list.
3613 If an entry is a directory, all files in that directory that are matched by
3614 `org-agenda-file-regexp' will be part of the file list.
3616 If the value of the variable is not a list but a single file name, then
3617 the list of agenda files is actually stored and maintained in that file, one
3618 agenda file per line. In this file paths can be given relative to
3619 `org-directory'. Tilde expansion and environment variable substitution
3620 are also made."
3621 :group 'org-agenda
3622 :type '(choice
3623 (repeat :tag "List of files and directories" file)
3624 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3626 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3627 "Regular expression to match files for `org-agenda-files'.
3628 If any element in the list in that variable contains a directory instead
3629 of a normal file, all files in that directory that are matched by this
3630 regular expression will be included."
3631 :group 'org-agenda
3632 :type 'regexp)
3634 (defcustom org-agenda-text-search-extra-files nil
3635 "List of extra files to be searched by text search commands.
3636 These files will be searched in addition to the agenda files by the
3637 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3638 Note that these files will only be searched for text search commands,
3639 not for the other agenda views like todo lists, tag searches or the weekly
3640 agenda. This variable is intended to list notes and possibly archive files
3641 that should also be searched by these two commands.
3642 In fact, if the first element in the list is the symbol `agenda-archives',
3643 then all archive files of all agenda files will be added to the search
3644 scope."
3645 :group 'org-agenda
3646 :type '(set :greedy t
3647 (const :tag "Agenda Archives" agenda-archives)
3648 (repeat :inline t (file))))
3650 (org-defvaralias 'org-agenda-multi-occur-extra-files
3651 'org-agenda-text-search-extra-files)
3653 (defcustom org-agenda-skip-unavailable-files nil
3654 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3655 A nil value means to remove them, after a query, from the list."
3656 :group 'org-agenda
3657 :type 'boolean)
3659 (defcustom org-calendar-to-agenda-key [?c]
3660 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3661 The command `org-calendar-goto-agenda' will be bound to this key. The
3662 default is the character `c' because then `c' can be used to switch back and
3663 forth between agenda and calendar."
3664 :group 'org-agenda
3665 :type 'sexp)
3667 (defcustom org-calendar-insert-diary-entry-key [?i]
3668 "The key to be installed in `calendar-mode-map' for adding diary entries.
3669 This option is irrelevant until `org-agenda-diary-file' has been configured
3670 to point to an Org-mode file. When that is the case, the command
3671 `org-agenda-diary-entry' will be bound to the key given here, by default
3672 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3673 if you want to continue doing this, you need to change this to a different
3674 key."
3675 :group 'org-agenda
3676 :type 'sexp)
3678 (defcustom org-agenda-diary-file 'diary-file
3679 "File to which to add new entries with the `i' key in agenda and calendar.
3680 When this is the symbol `diary-file', the functionality in the Emacs
3681 calendar will be used to add entries to the `diary-file'. But when this
3682 points to a file, `org-agenda-diary-entry' will be used instead."
3683 :group 'org-agenda
3684 :type '(choice
3685 (const :tag "The standard Emacs diary file" diary-file)
3686 (file :tag "Special Org file diary entries")))
3688 (eval-after-load "calendar"
3689 '(progn
3690 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3691 'org-calendar-goto-agenda)
3692 (add-hook 'calendar-mode-hook
3693 (lambda ()
3694 (unless (eq org-agenda-diary-file 'diary-file)
3695 (define-key calendar-mode-map
3696 org-calendar-insert-diary-entry-key
3697 'org-agenda-diary-entry))))))
3699 (defgroup org-latex nil
3700 "Options for embedding LaTeX code into Org-mode."
3701 :tag "Org LaTeX"
3702 :group 'org)
3704 (defcustom org-format-latex-options
3705 '(:foreground default :background default :scale 1.0
3706 :html-foreground "Black" :html-background "Transparent"
3707 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3708 "Options for creating images from LaTeX fragments.
3709 This is a property list with the following properties:
3710 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3711 `default' means use the foreground of the default face.
3712 `auto' means use the foreground from the text face.
3713 :background the background color, or \"Transparent\".
3714 `default' means use the background of the default face.
3715 `auto' means use the background from the text face.
3716 :scale a scaling factor for the size of the images, to get more pixels
3717 :html-foreground, :html-background, :html-scale
3718 the same numbers for HTML export.
3719 :matchers a list indicating which matchers should be used to
3720 find LaTeX fragments. Valid members of this list are:
3721 \"begin\" find environments
3722 \"$1\" find single characters surrounded by $.$
3723 \"$\" find math expressions surrounded by $...$
3724 \"$$\" find math expressions surrounded by $$....$$
3725 \"\\(\" find math expressions surrounded by \\(...\\)
3726 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3727 :group 'org-latex
3728 :type 'plist)
3730 (defcustom org-format-latex-signal-error t
3731 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3732 When nil, just push out a message."
3733 :group 'org-latex
3734 :version "24.1"
3735 :type 'boolean)
3737 (defcustom org-latex-to-mathml-jar-file nil
3738 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3739 Use this to specify additional executable file say a jar file.
3741 When using MathToWeb as the converter, specify the full-path to
3742 your mathtoweb.jar file."
3743 :group 'org-latex
3744 :version "24.1"
3745 :type '(choice
3746 (const :tag "None" nil)
3747 (file :tag "JAR file" :must-match t)))
3749 (defcustom org-latex-to-mathml-convert-command nil
3750 "Command to convert LaTeX fragments to MathML.
3751 Replace format-specifiers in the command as noted below and use
3752 `shell-command' to convert LaTeX to MathML.
3753 %j: Executable file in fully expanded form as specified by
3754 `org-latex-to-mathml-jar-file'.
3755 %I: Input LaTeX file in fully expanded form
3756 %o: Output MathML file
3757 This command is used by `org-create-math-formula'.
3759 When using MathToWeb as the converter, set this to
3760 \"java -jar %j -unicode -force -df %o %I\"."
3761 :group 'org-latex
3762 :version "24.1"
3763 :type '(choice
3764 (const :tag "None" nil)
3765 (string :tag "\nShell command")))
3767 (defcustom org-latex-create-formula-image-program 'dvipng
3768 "Program to convert LaTeX fragments with.
3770 dvipng Process the LaTeX fragments to dvi file, then convert
3771 dvi files to png files using dvipng.
3772 This will also include processing of non-math environments.
3773 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3774 to convert pdf files to png files"
3775 :group 'org-latex
3776 :version "24.1"
3777 :type '(choice
3778 (const :tag "dvipng" dvipng)
3779 (const :tag "imagemagick" imagemagick)))
3781 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3782 "Path to store latex preview images.
3783 A relative path here creates many directories relative to the
3784 processed org files paths. An absolute path puts all preview
3785 images at the same place."
3786 :group 'org-latex
3787 :version "24.3"
3788 :type 'string)
3790 (defun org-format-latex-mathml-available-p ()
3791 "Return t if `org-latex-to-mathml-convert-command' is usable."
3792 (save-match-data
3793 (when (and (boundp 'org-latex-to-mathml-convert-command)
3794 org-latex-to-mathml-convert-command)
3795 (let ((executable (car (split-string
3796 org-latex-to-mathml-convert-command))))
3797 (when (executable-find executable)
3798 (if (string-match
3799 "%j" org-latex-to-mathml-convert-command)
3800 (file-readable-p org-latex-to-mathml-jar-file)
3801 t))))))
3803 (defcustom org-format-latex-header "\\documentclass{article}
3804 \\usepackage[usenames]{color}
3805 \[PACKAGES]
3806 \[DEFAULT-PACKAGES]
3807 \\pagestyle{empty} % do not remove
3808 % The settings below are copied from fullpage.sty
3809 \\setlength{\\textwidth}{\\paperwidth}
3810 \\addtolength{\\textwidth}{-3cm}
3811 \\setlength{\\oddsidemargin}{1.5cm}
3812 \\addtolength{\\oddsidemargin}{-2.54cm}
3813 \\setlength{\\evensidemargin}{\\oddsidemargin}
3814 \\setlength{\\textheight}{\\paperheight}
3815 \\addtolength{\\textheight}{-\\headheight}
3816 \\addtolength{\\textheight}{-\\headsep}
3817 \\addtolength{\\textheight}{-\\footskip}
3818 \\addtolength{\\textheight}{-3cm}
3819 \\setlength{\\topmargin}{1.5cm}
3820 \\addtolength{\\topmargin}{-2.54cm}"
3821 "The document header used for processing LaTeX fragments.
3822 It is imperative that this header make sure that no page number
3823 appears on the page. The package defined in the variables
3824 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3825 will either replace the placeholder \"[PACKAGES]\" in this
3826 header, or they will be appended."
3827 :group 'org-latex
3828 :type 'string)
3830 (defun org-set-packages-alist (var val)
3831 "Set the packages alist and make sure it has 3 elements per entry."
3832 (set var (mapcar (lambda (x)
3833 (if (and (consp x) (= (length x) 2))
3834 (list (car x) (nth 1 x) t)
3836 val)))
3838 (defun org-get-packages-alist (var)
3839 "Get the packages alist and make sure it has 3 elements per entry."
3840 (mapcar (lambda (x)
3841 (if (and (consp x) (= (length x) 2))
3842 (list (car x) (nth 1 x) t)
3844 (default-value var)))
3846 (defcustom org-latex-default-packages-alist
3847 '(("AUTO" "inputenc" t)
3848 ("T1" "fontenc" t)
3849 ("" "fixltx2e" nil)
3850 ("" "graphicx" t)
3851 ("" "longtable" nil)
3852 ("" "float" nil)
3853 ("" "wrapfig" nil)
3854 ("" "rotating" nil)
3855 ("normalem" "ulem" t)
3856 ("" "amsmath" t)
3857 ("" "textcomp" t)
3858 ("" "marvosym" t)
3859 ("" "wasysym" t)
3860 ("" "amssymb" t)
3861 ("" "hyperref" nil)
3862 "\\tolerance=1000")
3863 "Alist of default packages to be inserted in the header.
3865 Change this only if one of the packages here causes an
3866 incompatibility with another package you are using.
3868 The packages in this list are needed by one part or another of
3869 Org mode to function properly:
3871 - inputenc, fontenc: for basic font and character selection
3872 - fixltx2e: Important patches of LaTeX itself
3873 - graphicx: for including images
3874 - longtable: For multipage tables
3875 - float, wrapfig: for figure placement
3876 - rotating: for sideways figures and tables
3877 - ulem: for underline and strike-through
3878 - amsmath: for subscript and superscript and math environments
3879 - textcomp, marvosymb, wasysym, amssymb: for various symbols used
3880 for interpreting the entities in `org-entities'. You can skip
3881 some of these packages if you don't use any of their symbols.
3882 - hyperref: for cross references
3884 Therefore you should not modify this variable unless you know
3885 what you are doing. The one reason to change it anyway is that
3886 you might be loading some other package that conflicts with one
3887 of the default packages. Each element is either a cell or
3888 a string.
3890 A cell is of the format:
3892 \( \"options\" \"package\" SNIPPET-FLAG).
3894 If SNIPPET-FLAG is non-nil, the package also needs to be included
3895 when compiling LaTeX snippets into images for inclusion into
3896 non-LaTeX output.
3898 A string will be inserted as-is in the header of the document."
3899 :group 'org-latex
3900 :group 'org-export-latex
3901 :set 'org-set-packages-alist
3902 :get 'org-get-packages-alist
3903 :version "24.1"
3904 :type '(repeat
3905 (choice
3906 (list :tag "options/package pair"
3907 (string :tag "options")
3908 (string :tag "package")
3909 (boolean :tag "Snippet"))
3910 (string :tag "A line of LaTeX"))))
3912 (defcustom org-latex-packages-alist nil
3913 "Alist of packages to be inserted in every LaTeX header.
3915 These will be inserted after `org-latex-default-packages-alist'.
3916 Each element is either a cell or a string.
3918 A cell is of the format:
3920 \(\"options\" \"package\" SNIPPET-FLAG)
3922 SNIPPET-FLAG, when non-nil, indicates that this package is also
3923 needed when turning LaTeX snippets into images for inclusion into
3924 non-LaTeX output.
3926 A string will be inserted as-is in the header of the document.
3928 Make sure that you only list packages here which:
3930 - you want in every file;
3931 - do not conflict with the setup in `org-format-latex-header';
3932 - do not conflict with the default packages in
3933 `org-latex-default-packages-alist'."
3934 :group 'org-latex
3935 :group 'org-export-latex
3936 :set 'org-set-packages-alist
3937 :get 'org-get-packages-alist
3938 :type '(repeat
3939 (choice
3940 (list :tag "options/package pair"
3941 (string :tag "options")
3942 (string :tag "package")
3943 (boolean :tag "Snippet"))
3944 (string :tag "A line of LaTeX"))))
3946 (defgroup org-appearance nil
3947 "Settings for Org-mode appearance."
3948 :tag "Org Appearance"
3949 :group 'org)
3951 (defcustom org-level-color-stars-only nil
3952 "Non-nil means fontify only the stars in each headline.
3953 When nil, the entire headline is fontified.
3954 Changing it requires restart of `font-lock-mode' to become effective
3955 also in regions already fontified."
3956 :group 'org-appearance
3957 :type 'boolean)
3959 (defcustom org-hide-leading-stars nil
3960 "Non-nil means hide the first N-1 stars in a headline.
3961 This works by using the face `org-hide' for these stars. This
3962 face is white for a light background, and black for a dark
3963 background. You may have to customize the face `org-hide' to
3964 make this work.
3965 Changing it requires restart of `font-lock-mode' to become effective
3966 also in regions already fontified.
3967 You may also set this on a per-file basis by adding one of the following
3968 lines to the buffer:
3970 #+STARTUP: hidestars
3971 #+STARTUP: showstars"
3972 :group 'org-appearance
3973 :type 'boolean)
3975 (defcustom org-hidden-keywords nil
3976 "List of symbols corresponding to keywords to be hidden the org buffer.
3977 For example, a value '(title) for this list will make the document's title
3978 appear in the buffer without the initial #+TITLE: keyword."
3979 :group 'org-appearance
3980 :version "24.1"
3981 :type '(set (const :tag "#+AUTHOR" author)
3982 (const :tag "#+DATE" date)
3983 (const :tag "#+EMAIL" email)
3984 (const :tag "#+TITLE" title)))
3986 (defcustom org-custom-properties nil
3987 "List of properties (as strings) with a special meaning.
3988 The default use of these custom properties is to let the user
3989 hide them with `org-toggle-custom-properties-visibility'."
3990 :group 'org-properties
3991 :group 'org-appearance
3992 :version "24.3"
3993 :type '(repeat (string :tag "Property Name")))
3995 (defcustom org-fontify-done-headline nil
3996 "Non-nil means change the face of a headline if it is marked DONE.
3997 Normally, only the TODO/DONE keyword indicates the state of a headline.
3998 When this is non-nil, the headline after the keyword is set to the
3999 `org-headline-done' as an additional indication."
4000 :group 'org-appearance
4001 :type 'boolean)
4003 (defcustom org-fontify-emphasized-text t
4004 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4005 Changing this variable requires a restart of Emacs to take effect."
4006 :group 'org-appearance
4007 :type 'boolean)
4009 (defcustom org-fontify-whole-heading-line nil
4010 "Non-nil means fontify the whole line for headings.
4011 This is useful when setting a background color for the
4012 org-level-* faces."
4013 :group 'org-appearance
4014 :type 'boolean)
4016 (defcustom org-highlight-latex-and-related nil
4017 "Non-nil means highlight LaTeX related syntax in the buffer.
4018 When non nil, the value should be a list containing any of the
4019 following symbols:
4020 `latex' Highlight LaTeX snippets and environments.
4021 `script' Highlight subscript and superscript.
4022 `entities' Highlight entities."
4023 :group 'org-appearance
4024 :version "24.4"
4025 :package-version '(Org . "8.0")
4026 :type '(choice
4027 (const :tag "No highlighting" nil)
4028 (set :greedy t :tag "Highlight"
4029 (const :tag "LaTeX snippets and environments" latex)
4030 (const :tag "Subscript and superscript" script)
4031 (const :tag "Entities" entities))))
4033 (defcustom org-hide-emphasis-markers nil
4034 "Non-nil mean font-lock should hide the emphasis marker characters."
4035 :group 'org-appearance
4036 :type 'boolean)
4038 (defcustom org-pretty-entities nil
4039 "Non-nil means show entities as UTF8 characters.
4040 When nil, the \\name form remains in the buffer."
4041 :group 'org-appearance
4042 :version "24.1"
4043 :type 'boolean)
4045 (defcustom org-pretty-entities-include-sub-superscripts t
4046 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4047 :group 'org-appearance
4048 :version "24.1"
4049 :type 'boolean)
4051 (defvar org-emph-re nil
4052 "Regular expression for matching emphasis.
4053 After a match, the match groups contain these elements:
4054 0 The match of the full regular expression, including the characters
4055 before and after the proper match
4056 1 The character before the proper match, or empty at beginning of line
4057 2 The proper match, including the leading and trailing markers
4058 3 The leading marker like * or /, indicating the type of highlighting
4059 4 The text between the emphasis markers, not including the markers
4060 5 The character after the match, empty at the end of a line")
4061 (defvar org-verbatim-re nil
4062 "Regular expression for matching verbatim text.")
4063 (defvar org-emphasis-regexp-components) ; defined just below
4064 (defvar org-emphasis-alist) ; defined just below
4065 (defun org-set-emph-re (var val)
4066 "Set variable and compute the emphasis regular expression."
4067 (set var val)
4068 (when (and (boundp 'org-emphasis-alist)
4069 (boundp 'org-emphasis-regexp-components)
4070 org-emphasis-alist org-emphasis-regexp-components)
4071 (let* ((e org-emphasis-regexp-components)
4072 (pre (car e))
4073 (post (nth 1 e))
4074 (border (nth 2 e))
4075 (body (nth 3 e))
4076 (nl (nth 4 e))
4077 (body1 (concat body "*?"))
4078 (markers (mapconcat 'car org-emphasis-alist ""))
4079 (vmarkers (mapconcat
4080 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4081 org-emphasis-alist "")))
4082 ;; make sure special characters appear at the right position in the class
4083 (if (string-match "\\^" markers)
4084 (setq markers (concat (replace-match "" t t markers) "^")))
4085 (if (string-match "-" markers)
4086 (setq markers (concat (replace-match "" t t markers) "-")))
4087 (if (string-match "\\^" vmarkers)
4088 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4089 (if (string-match "-" vmarkers)
4090 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4091 (if (> nl 0)
4092 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4093 (int-to-string nl) "\\}")))
4094 ;; Make the regexp
4095 (setq org-emph-re
4096 (concat "\\([" pre "]\\|^\\)"
4097 "\\("
4098 "\\([" markers "]\\)"
4099 "\\("
4100 "[^" border "]\\|"
4101 "[^" border "]"
4102 body1
4103 "[^" border "]"
4104 "\\)"
4105 "\\3\\)"
4106 "\\([" post "]\\|$\\)"))
4107 (setq org-verbatim-re
4108 (concat "\\([" pre "]\\|^\\)"
4109 "\\("
4110 "\\([" vmarkers "]\\)"
4111 "\\("
4112 "[^" border "]\\|"
4113 "[^" border "]"
4114 body1
4115 "[^" border "]"
4116 "\\)"
4117 "\\3\\)"
4118 "\\([" post "]\\|$\\)")))))
4120 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4121 ;; set this option proved cumbersome. See this message/thread:
4122 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4123 (defvar org-emphasis-regexp-components
4124 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4125 "Components used to build the regular expression for emphasis.
4126 This is a list with five entries. Terminology: In an emphasis string
4127 like \" *strong word* \", we call the initial space PREMATCH, the final
4128 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4129 and \"trong wor\" is the body. The different components in this variable
4130 specify what is allowed/forbidden in each part:
4132 pre Chars allowed as prematch. Beginning of line will be allowed too.
4133 post Chars allowed as postmatch. End of line will be allowed too.
4134 border The chars *forbidden* as border characters.
4135 body-regexp A regexp like \".\" to match a body character. Don't use
4136 non-shy groups here, and don't allow newline here.
4137 newline The maximum number of newlines allowed in an emphasis exp.
4139 You need to reload Org or to restart Emacs after customizing this.")
4141 (defcustom org-emphasis-alist
4142 `(("*" bold)
4143 ("/" italic)
4144 ("_" underline)
4145 ("=" org-verbatim verbatim)
4146 ("~" org-code verbatim)
4147 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4148 "Alist of characters and faces to emphasize text.
4149 Text starting and ending with a special character will be emphasized,
4150 for example *bold*, _underlined_ and /italic/. This variable sets the
4151 marker characters and the face to be used by font-lock for highlighting
4152 in Org-mode Emacs buffers.
4154 You need to reload Org or to restart Emacs after customizing this."
4155 :group 'org-appearance
4156 :set 'org-set-emph-re
4157 :version "24.4"
4158 :package-version '(Org . "8.0")
4159 :type '(repeat
4160 (list
4161 (string :tag "Marker character")
4162 (choice
4163 (face :tag "Font-lock-face")
4164 (plist :tag "Face property list"))
4165 (option (const verbatim)))))
4167 (defvar org-protecting-blocks
4168 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4169 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4170 This is needed for font-lock setup.")
4172 ;;; Miscellaneous options
4174 (defgroup org-completion nil
4175 "Completion in Org-mode."
4176 :tag "Org Completion"
4177 :group 'org)
4179 (defcustom org-completion-use-ido nil
4180 "Non-nil means use ido completion wherever possible.
4181 Note that `ido-mode' must be active for this variable to be relevant.
4182 If you decide to turn this variable on, you might well want to turn off
4183 `org-outline-path-complete-in-steps'.
4184 See also `org-completion-use-iswitchb'."
4185 :group 'org-completion
4186 :type 'boolean)
4188 (defcustom org-completion-use-iswitchb nil
4189 "Non-nil means use iswitchb completion wherever possible.
4190 Note that `iswitchb-mode' must be active for this variable to be relevant.
4191 If you decide to turn this variable on, you might well want to turn off
4192 `org-outline-path-complete-in-steps'.
4193 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4194 :group 'org-completion
4195 :type 'boolean)
4197 (defcustom org-completion-fallback-command 'hippie-expand
4198 "The expansion command called by \\[pcomplete] in normal context.
4199 Normal means, no org-mode-specific context."
4200 :group 'org-completion
4201 :type 'function)
4203 ;;; Functions and variables from their packages
4204 ;; Declared here to avoid compiler warnings
4206 ;; XEmacs only
4207 (defvar outline-mode-menu-heading)
4208 (defvar outline-mode-menu-show)
4209 (defvar outline-mode-menu-hide)
4210 (defvar zmacs-regions) ; XEmacs regions
4212 ;; Emacs only
4213 (defvar mark-active)
4215 ;; Various packages
4216 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4217 (declare-function calendar-forward-day "cal-move" (arg))
4218 (declare-function calendar-goto-date "cal-move" (date))
4219 (declare-function calendar-goto-today "cal-move" ())
4220 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4221 (defvar calc-embedded-close-formula)
4222 (defvar calc-embedded-open-formula)
4223 (declare-function cdlatex-tab "ext:cdlatex" ())
4224 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4225 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4226 (defvar font-lock-unfontify-region-function)
4227 (declare-function iswitchb-read-buffer "iswitchb"
4228 (prompt &optional default require-match start matches-set))
4229 (defvar iswitchb-temp-buflist)
4230 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4231 (defvar org-agenda-tags-todo-honor-ignore-options)
4232 (declare-function org-agenda-skip "org-agenda" ())
4233 (declare-function
4234 org-agenda-format-item "org-agenda"
4235 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4236 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4237 (declare-function org-agenda-change-all-lines "org-agenda"
4238 (newhead hdmarker &optional fixface just-this))
4239 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4240 (declare-function org-agenda-maybe-redo "org-agenda" ())
4241 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4242 (beg end))
4243 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4244 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4245 "org-agenda" (&optional end))
4246 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4247 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4248 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4249 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4250 (declare-function org-indent-mode "org-indent" (&optional arg))
4251 (declare-function parse-time-string "parse-time" (string))
4252 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4253 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4254 (defvar remember-data-file)
4255 (defvar texmathp-why)
4256 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4257 (declare-function table--at-cell-p "table" (position &optional object at-column))
4259 (defvar org-latex-regexps)
4261 ;;; Autoload and prepare some org modules
4263 ;; Some table stuff that needs to be defined here, because it is used
4264 ;; by the functions setting up org-mode or checking for table context.
4266 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4267 "Detect an org-type or table-type table.")
4268 (defconst org-table-line-regexp "^[ \t]*|"
4269 "Detect an org-type table line.")
4270 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4271 "Detect an org-type table line.")
4272 (defconst org-table-hline-regexp "^[ \t]*|-"
4273 "Detect an org-type table hline.")
4274 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4275 "Detect a table-type table hline.")
4276 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4277 "Detect the first line outside a table when searching from within it.
4278 This works for both table types.")
4280 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
4281 "Detect a #+TBLFM line.")
4283 ;;;###autoload
4284 (defun turn-on-orgtbl ()
4285 "Unconditionally turn on `orgtbl-mode'."
4286 (require 'org-table)
4287 (orgtbl-mode 1))
4289 (defun org-at-table-p (&optional table-type)
4290 "Return t if the cursor is inside an org-type table.
4291 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4292 (if org-enable-table-editor
4293 (save-excursion
4294 (beginning-of-line 1)
4295 (looking-at (if table-type org-table-any-line-regexp
4296 org-table-line-regexp)))
4297 nil))
4298 (defsubst org-table-p () (org-at-table-p))
4300 (defun org-at-table.el-p ()
4301 "Return t if and only if we are at a table.el table."
4302 (and (org-at-table-p 'any)
4303 (save-excursion
4304 (goto-char (org-table-begin 'any))
4305 (looking-at org-table1-hline-regexp))))
4307 (defun org-table-recognize-table.el ()
4308 "If there is a table.el table nearby, recognize it and move into it."
4309 (if org-table-tab-recognizes-table.el
4310 (if (org-at-table.el-p)
4311 (progn
4312 (beginning-of-line 1)
4313 (if (looking-at org-table-dataline-regexp)
4315 (if (looking-at org-table1-hline-regexp)
4316 (progn
4317 (beginning-of-line 2)
4318 (if (looking-at org-table-any-border-regexp)
4319 (beginning-of-line -1)))))
4320 (if (re-search-forward "|" (org-table-end t) t)
4321 (progn
4322 (require 'table)
4323 (if (table--at-cell-p (point))
4325 (message "recognizing table.el table...")
4326 (table-recognize-table)
4327 (message "recognizing table.el table...done")))
4328 (error "This should not happen"))
4330 nil)
4331 nil))
4333 (defun org-at-table-hline-p ()
4334 "Return t if the cursor is inside a hline in a table."
4335 (if org-enable-table-editor
4336 (save-excursion
4337 (beginning-of-line 1)
4338 (looking-at org-table-hline-regexp))
4339 nil))
4341 (defun org-table-map-tables (function &optional quietly)
4342 "Apply FUNCTION to the start of all tables in the buffer."
4343 (save-excursion
4344 (save-restriction
4345 (widen)
4346 (goto-char (point-min))
4347 (while (re-search-forward org-table-any-line-regexp nil t)
4348 (unless quietly
4349 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4350 (beginning-of-line 1)
4351 (when (and (looking-at org-table-line-regexp)
4352 ;; Exclude tables in src/example/verbatim/clocktable blocks
4353 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4354 (save-excursion (funcall function))
4355 (or (looking-at org-table-line-regexp)
4356 (forward-char 1)))
4357 (re-search-forward org-table-any-border-regexp nil 1))))
4358 (unless quietly (message "Mapping tables: done")))
4360 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4361 (declare-function org-clock-update-mode-line "org-clock" ())
4362 (declare-function org-resolve-clocks "org-clock"
4363 (&optional also-non-dangling-p prompt last-valid))
4365 (defun org-at-TBLFM-p (&optional pos)
4366 "Return t when point (or POS) is in #+TBLFM line."
4367 (save-excursion
4368 (let ((pos pos)))
4369 (goto-char (or pos (point)))
4370 (beginning-of-line 1)
4371 (looking-at org-TBLFM-regexp)))
4373 (defvar org-clock-start-time)
4374 (defvar org-clock-marker (make-marker)
4375 "Marker recording the last clock-in.")
4376 (defvar org-clock-hd-marker (make-marker)
4377 "Marker recording the last clock-in, but the headline position.")
4378 (defvar org-clock-heading ""
4379 "The heading of the current clock entry.")
4380 (defun org-clock-is-active ()
4381 "Return the buffer where the clock is currently running.
4382 Return nil if no clock is running."
4383 (marker-buffer org-clock-marker))
4385 (defun org-check-running-clock ()
4386 "Check if the current buffer contains the running clock.
4387 If yes, offer to stop it and to save the buffer with the changes."
4388 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4389 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4390 (buffer-name))))
4391 (org-clock-out)
4392 (when (y-or-n-p "Save changed buffer?")
4393 (save-buffer))))
4395 (defun org-clocktable-try-shift (dir n)
4396 "Check if this line starts a clock table, if yes, shift the time block."
4397 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4398 (org-clocktable-shift dir n)))
4400 ;;;###autoload
4401 (defun org-clock-persistence-insinuate ()
4402 "Set up hooks for clock persistence."
4403 (require 'org-clock)
4404 (add-hook 'org-mode-hook 'org-clock-load)
4405 (add-hook 'kill-emacs-hook 'org-clock-save))
4407 (defgroup org-archive nil
4408 "Options concerning archiving in Org-mode."
4409 :tag "Org Archive"
4410 :group 'org-structure)
4412 (defcustom org-archive-location "%s_archive::"
4413 "The location where subtrees should be archived.
4415 The value of this variable is a string, consisting of two parts,
4416 separated by a double-colon. The first part is a filename and
4417 the second part is a headline.
4419 When the filename is omitted, archiving happens in the same file.
4420 %s in the filename will be replaced by the current file
4421 name (without the directory part). Archiving to a different file
4422 is useful to keep archived entries from contributing to the
4423 Org-mode Agenda.
4425 The archived entries will be filed as subtrees of the specified
4426 headline. When the headline is omitted, the subtrees are simply
4427 filed away at the end of the file, as top-level entries. Also in
4428 the heading you can use %s to represent the file name, this can be
4429 useful when using the same archive for a number of different files.
4431 Here are a few examples:
4432 \"%s_archive::\"
4433 If the current file is Projects.org, archive in file
4434 Projects.org_archive, as top-level trees. This is the default.
4436 \"::* Archived Tasks\"
4437 Archive in the current file, under the top-level headline
4438 \"* Archived Tasks\".
4440 \"~/org/archive.org::\"
4441 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4443 \"~/org/archive.org::* From %s\"
4444 Archive in file ~/org/archive.org (absolute path), under headlines
4445 \"From FILENAME\" where file name is the current file name.
4447 \"~/org/datetree.org::datetree/* Finished Tasks\"
4448 The \"datetree/\" string is special, signifying to archive
4449 items to the datetree. Items are placed in either the CLOSED
4450 date of the item, or the current date if there is no CLOSED date.
4451 The heading will be a subentry to the current date. There doesn't
4452 need to be a heading, but there always needs to be a slash after
4453 datetree. For example, to store archived items directly in the
4454 datetree, use \"~/org/datetree.org::datetree/\".
4456 \"basement::** Finished Tasks\"
4457 Archive in file ./basement (relative path), as level 3 trees
4458 below the level 2 heading \"** Finished Tasks\".
4460 You may set this option on a per-file basis by adding to the buffer a
4461 line like
4463 #+ARCHIVE: basement::** Finished Tasks
4465 You may also define it locally for a subtree by setting an ARCHIVE property
4466 in the entry. If such a property is found in an entry, or anywhere up
4467 the hierarchy, it will be used."
4468 :group 'org-archive
4469 :type 'string)
4471 (defcustom org-archive-tag "ARCHIVE"
4472 "The tag that marks a subtree as archived.
4473 An archived subtree does not open during visibility cycling, and does
4474 not contribute to the agenda listings.
4475 After changing this, font-lock must be restarted in the relevant buffers to
4476 get the proper fontification."
4477 :group 'org-archive
4478 :group 'org-keywords
4479 :type 'string)
4481 (defcustom org-agenda-skip-archived-trees t
4482 "Non-nil means the agenda will skip any items located in archived trees.
4483 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4484 variable is no longer recommended, you should leave it at the value t.
4485 Instead, use the key `v' to cycle the archives-mode in the agenda."
4486 :group 'org-archive
4487 :group 'org-agenda-skip
4488 :type 'boolean)
4490 (defcustom org-columns-skip-archived-trees t
4491 "Non-nil means ignore archived trees when creating column view."
4492 :group 'org-archive
4493 :group 'org-properties
4494 :type 'boolean)
4496 (defcustom org-cycle-open-archived-trees nil
4497 "Non-nil means `org-cycle' will open archived trees.
4498 An archived tree is a tree marked with the tag ARCHIVE.
4499 When nil, archived trees will stay folded. You can still open them with
4500 normal outline commands like `show-all', but not with the cycling commands."
4501 :group 'org-archive
4502 :group 'org-cycle
4503 :type 'boolean)
4505 (defcustom org-sparse-tree-open-archived-trees nil
4506 "Non-nil means sparse tree construction shows matches in archived trees.
4507 When nil, matches in these trees are highlighted, but the trees are kept in
4508 collapsed state."
4509 :group 'org-archive
4510 :group 'org-sparse-trees
4511 :type 'boolean)
4513 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4514 "The default date type when building a sparse tree.
4515 When this is nil, a date is a scheduled or a deadline timestamp.
4516 Otherwise, these types are allowed:
4518 all: all timestamps
4519 active: only active timestamps (<...>)
4520 inactive: only inactive timestamps (<...)
4521 scheduled: only scheduled timestamps
4522 deadline: only deadline timestamps"
4523 :type '(choice (const :tag "Scheduled or deadline" scheduled-or-deadline)
4524 (const :tag "All timestamps" all)
4525 (const :tag "Only active timestamps" active)
4526 (const :tag "Only inactive timestamps" inactive)
4527 (const :tag "Only scheduled timestamps" scheduled)
4528 (const :tag "Only deadline timestamps" deadline)
4529 (const :tag "Only closed timestamps" closed))
4530 :version "24.3"
4531 :group 'org-sparse-trees)
4533 (defun org-cycle-hide-archived-subtrees (state)
4534 "Re-hide all archived subtrees after a visibility state change."
4535 (when (and (not org-cycle-open-archived-trees)
4536 (not (memq state '(overview folded))))
4537 (save-excursion
4538 (let* ((globalp (memq state '(contents all)))
4539 (beg (if globalp (point-min) (point)))
4540 (end (if globalp (point-max) (org-end-of-subtree t))))
4541 (org-hide-archived-subtrees beg end)
4542 (goto-char beg)
4543 (if (looking-at (concat ".*:" org-archive-tag ":"))
4544 (message "%s" (substitute-command-keys
4545 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4547 (defun org-force-cycle-archived ()
4548 "Cycle subtree even if it is archived."
4549 (interactive)
4550 (setq this-command 'org-cycle)
4551 (let ((org-cycle-open-archived-trees t))
4552 (call-interactively 'org-cycle)))
4554 (defun org-hide-archived-subtrees (beg end)
4555 "Re-hide all archived subtrees after a visibility state change."
4556 (save-excursion
4557 (let* ((re (concat ":" org-archive-tag ":")))
4558 (goto-char beg)
4559 (while (re-search-forward re end t)
4560 (when (org-at-heading-p)
4561 (org-flag-subtree t)
4562 (org-end-of-subtree t))))))
4564 (declare-function outline-end-of-heading "outline" ())
4565 (declare-function outline-flag-region "outline" (from to flag))
4566 (defun org-flag-subtree (flag)
4567 (save-excursion
4568 (org-back-to-heading t)
4569 (outline-end-of-heading)
4570 (outline-flag-region (point)
4571 (progn (org-end-of-subtree t) (point))
4572 flag)))
4574 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4576 ;; Declare Column View Code
4578 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4579 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4580 (declare-function org-columns-compute "org-colview" (property))
4582 ;; Declare ID code
4584 (declare-function org-id-store-link "org-id")
4585 (declare-function org-id-locations-load "org-id")
4586 (declare-function org-id-locations-save "org-id")
4587 (defvar org-id-track-globally)
4589 ;;; Variables for pre-computed regular expressions, all buffer local
4591 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4592 "Matches first line of a hidden block.")
4593 (make-variable-buffer-local 'org-drawer-regexp)
4594 (defvar org-todo-regexp nil
4595 "Matches any of the TODO state keywords.")
4596 (make-variable-buffer-local 'org-todo-regexp)
4597 (defvar org-not-done-regexp nil
4598 "Matches any of the TODO state keywords except the last one.")
4599 (make-variable-buffer-local 'org-not-done-regexp)
4600 (defvar org-not-done-heading-regexp nil
4601 "Matches a TODO headline that is not done.")
4602 (make-variable-buffer-local 'org-not-done-regexp)
4603 (defvar org-todo-line-regexp nil
4604 "Matches a headline and puts TODO state into group 2 if present.")
4605 (make-variable-buffer-local 'org-todo-line-regexp)
4606 (defvar org-complex-heading-regexp nil
4607 "Matches a headline and puts everything into groups:
4608 group 1: the stars
4609 group 2: The todo keyword, maybe
4610 group 3: Priority cookie
4611 group 4: True headline
4612 group 5: Tags")
4613 (make-variable-buffer-local 'org-complex-heading-regexp)
4614 (defvar org-complex-heading-regexp-format nil
4615 "Printf format to make regexp to match an exact headline.
4616 This regexp will match the headline of any node which has the
4617 exact headline text that is put into the format, but may have any
4618 TODO state, priority and tags.")
4619 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4620 (defvar org-todo-line-tags-regexp nil
4621 "Matches a headline and puts TODO state into group 2 if present.
4622 Also put tags into group 4 if tags are present.")
4623 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4624 (defvar org-ds-keyword-length 12
4625 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4626 (make-variable-buffer-local 'org-ds-keyword-length)
4627 (defvar org-deadline-regexp nil
4628 "Matches the DEADLINE keyword.")
4629 (make-variable-buffer-local 'org-deadline-regexp)
4630 (defvar org-deadline-time-regexp nil
4631 "Matches the DEADLINE keyword together with a time stamp.")
4632 (make-variable-buffer-local 'org-deadline-time-regexp)
4633 (defvar org-deadline-time-hour-regexp nil
4634 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4635 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4636 (defvar org-deadline-line-regexp nil
4637 "Matches the DEADLINE keyword and the rest of the line.")
4638 (make-variable-buffer-local 'org-deadline-line-regexp)
4639 (defvar org-scheduled-regexp nil
4640 "Matches the SCHEDULED keyword.")
4641 (make-variable-buffer-local 'org-scheduled-regexp)
4642 (defvar org-scheduled-time-regexp nil
4643 "Matches the SCHEDULED keyword together with a time stamp.")
4644 (make-variable-buffer-local 'org-scheduled-time-regexp)
4645 (defvar org-scheduled-time-hour-regexp nil
4646 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4647 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4648 (defvar org-closed-time-regexp nil
4649 "Matches the CLOSED keyword together with a time stamp.")
4650 (make-variable-buffer-local 'org-closed-time-regexp)
4652 (defvar org-keyword-time-regexp nil
4653 "Matches any of the 4 keywords, together with the time stamp.")
4654 (make-variable-buffer-local 'org-keyword-time-regexp)
4655 (defvar org-keyword-time-not-clock-regexp nil
4656 "Matches any of the 3 keywords, together with the time stamp.")
4657 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4658 (defvar org-maybe-keyword-time-regexp nil
4659 "Matches a timestamp, possibly preceded by a keyword.")
4660 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4661 (defvar org-all-time-keywords nil
4662 "List of time keywords.")
4663 (make-variable-buffer-local 'org-all-time-keywords)
4665 (defconst org-plain-time-of-day-regexp
4666 (concat
4667 "\\(\\<[012]?[0-9]"
4668 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4669 "\\(--?"
4670 "\\(\\<[012]?[0-9]"
4671 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4672 "\\)?")
4673 "Regular expression to match a plain time or time range.
4674 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4675 groups carry important information:
4676 0 the full match
4677 1 the first time, range or not
4678 8 the second time, if it is a range.")
4680 (defconst org-plain-time-extension-regexp
4681 (concat
4682 "\\(\\<[012]?[0-9]"
4683 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4684 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4685 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4686 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4687 groups carry important information:
4688 0 the full match
4689 7 hours of duration
4690 9 minutes of duration")
4692 (defconst org-stamp-time-of-day-regexp
4693 (concat
4694 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4695 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4696 "\\(--?"
4697 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4698 "Regular expression to match a timestamp time or time range.
4699 After a match, the following groups carry important information:
4700 0 the full match
4701 1 date plus weekday, for back referencing to make sure both times are on the same day
4702 2 the first time, range or not
4703 4 the second time, if it is a range.")
4705 (defconst org-startup-options
4706 '(("fold" org-startup-folded t)
4707 ("overview" org-startup-folded t)
4708 ("nofold" org-startup-folded nil)
4709 ("showall" org-startup-folded nil)
4710 ("showeverything" org-startup-folded showeverything)
4711 ("content" org-startup-folded content)
4712 ("indent" org-startup-indented t)
4713 ("noindent" org-startup-indented nil)
4714 ("hidestars" org-hide-leading-stars t)
4715 ("showstars" org-hide-leading-stars nil)
4716 ("odd" org-odd-levels-only t)
4717 ("oddeven" org-odd-levels-only nil)
4718 ("align" org-startup-align-all-tables t)
4719 ("noalign" org-startup-align-all-tables nil)
4720 ("inlineimages" org-startup-with-inline-images t)
4721 ("noinlineimages" org-startup-with-inline-images nil)
4722 ("latexpreview" org-startup-with-latex-preview t)
4723 ("nolatexpreview" org-startup-with-latex-preview nil)
4724 ("customtime" org-display-custom-times t)
4725 ("logdone" org-log-done time)
4726 ("lognotedone" org-log-done note)
4727 ("nologdone" org-log-done nil)
4728 ("lognoteclock-out" org-log-note-clock-out t)
4729 ("nolognoteclock-out" org-log-note-clock-out nil)
4730 ("logrepeat" org-log-repeat state)
4731 ("lognoterepeat" org-log-repeat note)
4732 ("logdrawer" org-log-into-drawer t)
4733 ("nologdrawer" org-log-into-drawer nil)
4734 ("logstatesreversed" org-log-states-order-reversed t)
4735 ("nologstatesreversed" org-log-states-order-reversed nil)
4736 ("nologrepeat" org-log-repeat nil)
4737 ("logreschedule" org-log-reschedule time)
4738 ("lognotereschedule" org-log-reschedule note)
4739 ("nologreschedule" org-log-reschedule nil)
4740 ("logredeadline" org-log-redeadline time)
4741 ("lognoteredeadline" org-log-redeadline note)
4742 ("nologredeadline" org-log-redeadline nil)
4743 ("logrefile" org-log-refile time)
4744 ("lognoterefile" org-log-refile note)
4745 ("nologrefile" org-log-refile nil)
4746 ("fninline" org-footnote-define-inline t)
4747 ("nofninline" org-footnote-define-inline nil)
4748 ("fnlocal" org-footnote-section nil)
4749 ("fnauto" org-footnote-auto-label t)
4750 ("fnprompt" org-footnote-auto-label nil)
4751 ("fnconfirm" org-footnote-auto-label confirm)
4752 ("fnplain" org-footnote-auto-label plain)
4753 ("fnadjust" org-footnote-auto-adjust t)
4754 ("nofnadjust" org-footnote-auto-adjust nil)
4755 ("constcgs" constants-unit-system cgs)
4756 ("constSI" constants-unit-system SI)
4757 ("noptag" org-tag-persistent-alist nil)
4758 ("hideblocks" org-hide-block-startup t)
4759 ("nohideblocks" org-hide-block-startup nil)
4760 ("beamer" org-startup-with-beamer-mode t)
4761 ("entitiespretty" org-pretty-entities t)
4762 ("entitiesplain" org-pretty-entities nil))
4763 "Variable associated with STARTUP options for org-mode.
4764 Each element is a list of three items: the startup options (as written
4765 in the #+STARTUP line), the corresponding variable, and the value to set
4766 this variable to if the option is found. An optional forth element PUSH
4767 means to push this value onto the list in the variable.")
4769 (defun org-update-property-plist (key val props)
4770 "Update PROPS with KEY and VAL."
4771 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4772 (key (if appending (substring key 0 (- (length key) 1)) key))
4773 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4774 (previous (cdr (assoc key props))))
4775 (if appending
4776 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4777 (cons (cons key val) remainder))))
4779 (defconst org-block-regexp
4780 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4781 "Regular expression for hiding blocks.")
4782 (defconst org-heading-keyword-regexp-format
4783 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4784 "Printf format for a regexp matching a headline with some keyword.
4785 This regexp will match the headline of any node which has the
4786 exact keyword that is put into the format. The keyword isn't in
4787 any group by default, but the stars and the body are.")
4788 (defconst org-heading-keyword-maybe-regexp-format
4789 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4790 "Printf format for a regexp matching a headline, possibly with some keyword.
4791 This regexp can match any headline with the specified keyword, or
4792 without a keyword. The keyword isn't in any group by default,
4793 but the stars and the body are.")
4795 (defcustom org-group-tags t
4796 "When non-nil (the default), use group tags.
4797 This can be turned on/off through `org-toggle-tags-groups'."
4798 :group 'org-tags
4799 :group 'org-startup
4800 :type 'boolean)
4802 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4804 (defun org-toggle-tags-groups ()
4805 "Toggle support for group tags.
4806 Support for group tags is controlled by the option
4807 `org-group-tags', which is non-nil by default."
4808 (interactive)
4809 (setq org-group-tags (not org-group-tags))
4810 (cond ((and (derived-mode-p 'org-agenda-mode)
4811 org-group-tags)
4812 (org-agenda-redo))
4813 ((derived-mode-p 'org-mode)
4814 (let ((org-inhibit-startup t)) (org-mode))))
4815 (message "Groups tags support has been turned %s"
4816 (if org-group-tags "on" "off")))
4818 (defun org-set-regexps-and-options-for-tags ()
4819 "Precompute variables used for tags."
4820 (when (derived-mode-p 'org-mode)
4821 (org-set-local 'org-file-tags nil)
4822 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4823 (splitre "[ \t]+")
4824 (start 0)
4825 tags ftags key value)
4826 (save-excursion
4827 (save-restriction
4828 (widen)
4829 (goto-char (point-min))
4830 (while (re-search-forward re nil t)
4831 (setq key (upcase (org-match-string-no-properties 1))
4832 value (org-match-string-no-properties 2))
4833 (if (stringp value) (setq value (org-trim value)))
4834 (cond
4835 ((equal key "TAGS")
4836 (setq tags (append tags (if tags '("\\n") nil)
4837 (org-split-string value splitre))))
4838 ((equal key "FILETAGS")
4839 (when (string-match "\\S-" value)
4840 (setq ftags
4841 (append
4842 ftags
4843 (apply 'append
4844 (mapcar (lambda (x) (org-split-string x ":"))
4845 (org-split-string value)))))))))))
4846 ;; Process the file tags.
4847 (and ftags (org-set-local 'org-file-tags
4848 (mapcar 'org-add-prop-inherited ftags)))
4849 (org-set-local 'org-tag-groups-alist nil)
4850 ;; Process the tags.
4851 (when (and (not tags) org-tag-alist)
4852 (setq tags
4853 (mapcar
4854 (lambda (tg) (cond ((eq (car tg) :startgroup) "{")
4855 ((eq (car tg) :endgroup) "}")
4856 ((eq (car tg) :grouptags) ":")
4857 ((eq (car tg) :newline) "\n")
4858 (t (concat (car tg)
4859 (if (characterp (cdr tg))
4860 (format "(%s)" (char-to-string (cdr tg))) "")))))
4861 org-tag-alist)))
4862 (let (e tgs g)
4863 (while (setq e (pop tags))
4864 (cond
4865 ((equal e "{")
4866 (progn (push '(:startgroup) tgs)
4867 (when (equal (nth 1 tags) ":")
4868 (push (list (replace-regexp-in-string
4869 "(.+)$" "" (nth 0 tags)))
4870 org-tag-groups-alist)
4871 (setq g 0))))
4872 ((equal e ":") (push '(:grouptags) tgs))
4873 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4874 ((equal e "\\n") (push '(:newline) tgs))
4875 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4876 (push (cons (match-string 1 e)
4877 (string-to-char (match-string 2 e))) tgs)
4878 (if (and g (> g 0))
4879 (setcar org-tag-groups-alist
4880 (append (car org-tag-groups-alist)
4881 (list (match-string 1 e)))))
4882 (if g (setq g (1+ g))))
4883 (t (push (list e) tgs)
4884 (if (and g (> g 0))
4885 (setcar org-tag-groups-alist
4886 (append (car org-tag-groups-alist) (list e))))
4887 (if g (setq g (1+ g))))))
4888 (org-set-local 'org-tag-alist nil)
4889 (while (setq e (pop tgs))
4890 (or (and (stringp (car e))
4891 (assoc (car e) org-tag-alist))
4892 (push e org-tag-alist)))
4893 ;; Return a list with tag variables
4894 (list org-file-tags org-tag-alist org-tag-groups-alist)))))
4896 (defvar org-ota nil)
4897 (defun org-set-regexps-and-options ()
4898 "Precompute regular expressions used in the current buffer."
4899 (when (derived-mode-p 'org-mode)
4900 (org-set-local 'org-todo-kwd-alist nil)
4901 (org-set-local 'org-todo-key-alist nil)
4902 (org-set-local 'org-todo-key-trigger nil)
4903 (org-set-local 'org-todo-keywords-1 nil)
4904 (org-set-local 'org-done-keywords nil)
4905 (org-set-local 'org-todo-heads nil)
4906 (org-set-local 'org-todo-sets nil)
4907 (org-set-local 'org-todo-log-states nil)
4908 (org-set-local 'org-file-properties nil)
4909 (let ((re (org-make-options-regexp
4910 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
4911 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4912 "SETUPFILE" "OPTIONS")
4913 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4914 (splitre "[ \t]+")
4915 (scripts org-use-sub-superscripts)
4916 kwds kws0 kwsa key log value cat arch const links hw dws
4917 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
4918 (start 0))
4919 (save-excursion
4920 (save-restriction
4921 (widen)
4922 (goto-char (point-min))
4923 (while
4924 (or (and
4925 ext-setup-or-nil
4926 (not org-ota)
4927 (let (ret)
4928 (with-temp-buffer
4929 (insert ext-setup-or-nil)
4930 (let ((major-mode 'org-mode) org-ota)
4931 (setq ret (save-match-data
4932 (org-set-regexps-and-options-for-tags)))))
4933 ;; Append setupfile tags to existing tags
4934 (setq org-ota t)
4935 (setq org-file-tags
4936 (delq nil (append org-file-tags (nth 0 ret)))
4937 org-tag-alist
4938 (delq nil (append org-tag-alist (nth 1 ret)))
4939 org-tag-groups-alist
4940 (delq nil (append org-tag-groups-alist (nth 2 ret))))))
4941 (and ext-setup-or-nil
4942 (string-match re ext-setup-or-nil start)
4943 (setq start (match-end 0)))
4944 (and (setq ext-setup-or-nil nil start 0)
4945 (re-search-forward re nil t)))
4946 (setq key (upcase (match-string 1 ext-setup-or-nil))
4947 value (org-match-string-no-properties 2 ext-setup-or-nil))
4948 (if (stringp value) (setq value (org-trim value)))
4949 (cond
4950 ((equal key "CATEGORY")
4951 (setq cat value))
4952 ((member key '("SEQ_TODO" "TODO"))
4953 (push (cons 'sequence (org-split-string value splitre)) kwds))
4954 ((equal key "TYP_TODO")
4955 (push (cons 'type (org-split-string value splitre)) kwds))
4956 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4957 ;; general TODO-like setup
4958 (push (cons (intern (downcase (match-string 1 key)))
4959 (org-split-string value splitre)) kwds))
4960 ((equal key "COLUMNS")
4961 (org-set-local 'org-columns-default-format value))
4962 ((equal key "LINK")
4963 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4964 (push (cons (match-string 1 value)
4965 (org-trim (match-string 2 value)))
4966 links)))
4967 ((equal key "PRIORITIES")
4968 (setq prio (org-split-string value " +")))
4969 ((equal key "PROPERTY")
4970 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4971 (setq props (org-update-property-plist (match-string 1 value)
4972 (match-string 2 value)
4973 props))))
4974 ((equal key "DRAWERS")
4975 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4976 ((equal key "CONSTANTS")
4977 (org-table-set-constants))
4978 ((equal key "STARTUP")
4979 (let ((opts (org-split-string value splitre))
4980 l var val)
4981 (while (setq l (pop opts))
4982 (when (setq l (assoc l org-startup-options))
4983 (setq var (nth 1 l) val (nth 2 l))
4984 (if (not (nth 3 l))
4985 (set (make-local-variable var) val)
4986 (if (not (listp (symbol-value var)))
4987 (set (make-local-variable var) nil))
4988 (set (make-local-variable var) (symbol-value var))
4989 (add-to-list var val))))))
4990 ((equal key "ARCHIVE")
4991 (setq arch value)
4992 (remove-text-properties 0 (length arch)
4993 '(face t fontified t) arch))
4994 ((equal key "OPTIONS")
4995 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4996 (setq scripts (read (match-string 2 value)))))
4997 ((and (equal key "SETUPFILE")
4998 ;; Prevent checking in Gnus messages
4999 (not buffer-read-only))
5000 (setq setup-contents (org-file-contents
5001 (expand-file-name
5002 (org-remove-double-quotes value))
5003 'noerror))
5004 (if (not ext-setup-or-nil)
5005 (setq ext-setup-or-nil setup-contents start 0)
5006 (setq ext-setup-or-nil
5007 (concat (substring ext-setup-or-nil 0 start)
5008 "\n" setup-contents "\n"
5009 (substring ext-setup-or-nil start)))))))
5010 ;; search for property blocks
5011 (goto-char (point-min))
5012 (while (re-search-forward org-block-regexp nil t)
5013 (when (equal "PROPERTY" (upcase (match-string 1)))
5014 (setq value (replace-regexp-in-string
5015 "[\n\r]" " " (match-string 4)))
5016 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
5017 (setq props (org-update-property-plist (match-string 1 value)
5018 (match-string 2 value)
5019 props)))))))
5020 (org-set-local 'org-use-sub-superscripts scripts)
5021 (when cat
5022 (org-set-local 'org-category (intern cat))
5023 (push (cons "CATEGORY" cat) props))
5024 (when prio
5025 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
5026 (setq prio (mapcar 'string-to-char prio))
5027 (org-set-local 'org-highest-priority (nth 0 prio))
5028 (org-set-local 'org-lowest-priority (nth 1 prio))
5029 (org-set-local 'org-default-priority (nth 2 prio)))
5030 (and props (org-set-local 'org-file-properties (nreverse props)))
5031 (and drawers (org-set-local 'org-drawers drawers))
5032 (and arch (org-set-local 'org-archive-location arch))
5033 (and links (setq org-link-abbrev-alist-local (nreverse links)))
5034 ;; Process the TODO keywords
5035 (unless kwds
5036 ;; Use the global values as if they had been given locally.
5037 (setq kwds (default-value 'org-todo-keywords))
5038 (if (stringp (car kwds))
5039 (setq kwds (list (cons org-todo-interpretation
5040 (default-value 'org-todo-keywords)))))
5041 (setq kwds (reverse kwds)))
5042 (setq kwds (nreverse kwds))
5043 (let (inter kws kw)
5044 (while (setq kws (pop kwds))
5045 (let ((kws (or
5046 (run-hook-with-args-until-success
5047 'org-todo-setup-filter-hook kws)
5048 kws)))
5049 (setq inter (pop kws) sep (member "|" kws)
5050 kws0 (delete "|" (copy-sequence kws))
5051 kwsa nil
5052 kws1 (mapcar
5053 (lambda (x)
5054 ;; 1 2
5055 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
5056 (progn
5057 (setq kw (match-string 1 x)
5058 key (and (match-end 2) (match-string 2 x))
5059 log (org-extract-log-state-settings x))
5060 (push (cons kw (and key (string-to-char key))) kwsa)
5061 (and log (push log org-todo-log-states))
5063 (error "Invalid TODO keyword %s" x)))
5064 kws0)
5065 kwsa (if kwsa (append '((:startgroup))
5066 (nreverse kwsa)
5067 '((:endgroup))))
5068 hw (car kws1)
5069 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
5070 tail (list inter hw (car dws) (org-last dws))))
5071 (add-to-list 'org-todo-heads hw 'append)
5072 (push kws1 org-todo-sets)
5073 (setq org-done-keywords (append org-done-keywords dws nil))
5074 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
5075 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
5076 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
5077 (setq org-todo-sets (nreverse org-todo-sets)
5078 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5079 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
5080 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
5081 ;; Compute the regular expressions and other local variables.
5082 ;; Using `org-outline-regexp-bol' would complicate them much,
5083 ;; because of the fixed white space at the end of that string.
5084 (if (not org-done-keywords)
5085 (setq org-done-keywords (and org-todo-keywords-1
5086 (list (org-last org-todo-keywords-1)))))
5087 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5088 (length org-scheduled-string)
5089 (length org-clock-string)
5090 (length org-closed-string)))
5091 org-drawer-regexp
5092 (concat "^[ \t]*:\\("
5093 (mapconcat 'regexp-quote org-drawers "\\|")
5094 "\\):[ \t]*$")
5095 org-not-done-keywords
5096 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5097 org-todo-regexp
5098 (concat "\\("
5099 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5100 "\\)")
5101 org-not-done-regexp
5102 (concat "\\("
5103 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5104 "\\)")
5105 org-not-done-heading-regexp
5106 (format org-heading-keyword-regexp-format org-not-done-regexp)
5107 org-todo-line-regexp
5108 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5109 org-complex-heading-regexp
5110 (concat "^\\(\\*+\\)"
5111 "\\(?: +" org-todo-regexp "\\)?"
5112 "\\(?: +\\(\\[#.\\]\\)\\)?"
5113 "\\(?: +\\(.*?\\)\\)??"
5114 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5115 "[ \t]*$")
5116 org-complex-heading-regexp-format
5117 (concat "^\\(\\*+\\)"
5118 "\\(?: +" org-todo-regexp "\\)?"
5119 "\\(?: +\\(\\[#.\\]\\)\\)?"
5120 "\\(?: +"
5121 ;; Stats cookies can be stuck to body.
5122 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5123 "\\(%s\\)"
5124 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5125 "\\)"
5126 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5127 "[ \t]*$")
5128 org-todo-line-tags-regexp
5129 (concat "^\\(\\*+\\)"
5130 "\\(?: +" org-todo-regexp "\\)?"
5131 "\\(?: +\\(.*?\\)\\)??"
5132 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5133 "[ \t]*$")
5134 org-deadline-regexp (concat "\\<" org-deadline-string)
5135 org-deadline-time-regexp
5136 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5137 org-deadline-time-hour-regexp
5138 (concat "\\<" org-deadline-string
5139 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5140 org-deadline-line-regexp
5141 (concat "\\<\\(" org-deadline-string "\\).*")
5142 org-scheduled-regexp
5143 (concat "\\<" org-scheduled-string)
5144 org-scheduled-time-regexp
5145 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5146 org-scheduled-time-hour-regexp
5147 (concat "\\<" org-scheduled-string
5148 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5149 org-closed-time-regexp
5150 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5151 org-keyword-time-regexp
5152 (concat "\\<\\(" org-scheduled-string
5153 "\\|" org-deadline-string
5154 "\\|" org-closed-string
5155 "\\|" org-clock-string "\\)"
5156 " *[[<]\\([^]>]+\\)[]>]")
5157 org-keyword-time-not-clock-regexp
5158 (concat "\\<\\(" org-scheduled-string
5159 "\\|" org-deadline-string
5160 "\\|" org-closed-string
5161 "\\)"
5162 " *[[<]\\([^]>]+\\)[]>]")
5163 org-maybe-keyword-time-regexp
5164 (concat "\\(\\<\\(" org-scheduled-string
5165 "\\|" org-deadline-string
5166 "\\|" org-closed-string
5167 "\\|" org-clock-string "\\)\\)?"
5168 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5169 org-all-time-keywords
5170 (mapcar (lambda (w) (substring w 0 -1))
5171 (list org-scheduled-string org-deadline-string
5172 org-clock-string org-closed-string)))
5173 (setq org-ota nil)
5174 (org-compute-latex-and-related-regexp))))
5176 (defun org-file-contents (file &optional noerror)
5177 "Return the contents of FILE, as a string."
5178 (if (or (not file) (not (file-readable-p file)))
5179 (if (not noerror)
5180 (error "Cannot read file \"%s\"" file)
5181 (message "Cannot read file \"%s\"" file)
5183 (with-temp-buffer
5184 (insert-file-contents file)
5185 (buffer-string))))
5187 (defun org-extract-log-state-settings (x)
5188 "Extract the log state setting from a TODO keyword string.
5189 This will extract info from a string like \"WAIT(w@/!)\"."
5190 (let (kw key log1 log2)
5191 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5192 (setq kw (match-string 1 x)
5193 key (and (match-end 2) (match-string 2 x))
5194 log1 (and (match-end 3) (match-string 3 x))
5195 log2 (and (match-end 4) (match-string 4 x)))
5196 (and (or log1 log2)
5197 (list kw
5198 (and log1 (if (equal log1 "!") 'time 'note))
5199 (and log2 (if (equal log2 "!") 'time 'note)))))))
5201 (defun org-remove-keyword-keys (list)
5202 "Remove a pair of parenthesis at the end of each string in LIST."
5203 (mapcar (lambda (x)
5204 (if (string-match "(.*)$" x)
5205 (substring x 0 (match-beginning 0))
5207 list))
5209 (defun org-assign-fast-keys (alist)
5210 "Assign fast keys to a keyword-key alist.
5211 Respect keys that are already there."
5212 (let (new e (alt ?0))
5213 (while (setq e (pop alist))
5214 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5215 (cdr e)) ;; Key already assigned.
5216 (push e new)
5217 (let ((clist (string-to-list (downcase (car e))))
5218 (used (append new alist)))
5219 (when (= (car clist) ?@)
5220 (pop clist))
5221 (while (and clist (rassoc (car clist) used))
5222 (pop clist))
5223 (unless clist
5224 (while (rassoc alt used)
5225 (incf alt)))
5226 (push (cons (car e) (or (car clist) alt)) new))))
5227 (nreverse new)))
5229 ;;; Some variables used in various places
5231 (defvar org-window-configuration nil
5232 "Used in various places to store a window configuration.")
5233 (defvar org-selected-window nil
5234 "Used in various places to store a window configuration.")
5235 (defvar org-finish-function nil
5236 "Function to be called when `C-c C-c' is used.
5237 This is for getting out of special buffers like capture.")
5240 ;; FIXME: Occasionally check by commenting these, to make sure
5241 ;; no other functions uses these, forgetting to let-bind them.
5242 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5243 (defvar org-last-state)
5244 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5246 ;; Defined somewhere in this file, but used before definition.
5247 (defvar org-entities) ;; defined in org-entities.el
5248 (defvar org-struct-menu)
5249 (defvar org-org-menu)
5250 (defvar org-tbl-menu)
5252 ;;;; Define the Org-mode
5254 ;; We use a before-change function to check if a table might need
5255 ;; an update.
5256 (defvar org-table-may-need-update t
5257 "Indicates that a table might need an update.
5258 This variable is set by `org-before-change-function'.
5259 `org-table-align' sets it back to nil.")
5260 (defun org-before-change-function (beg end)
5261 "Every change indicates that a table might need an update."
5262 (setq org-table-may-need-update t))
5263 (defvar org-mode-map)
5264 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5265 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5266 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5267 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5268 (defvar org-table-buffer-is-an nil)
5270 (defvar bidi-paragraph-direction)
5271 (defvar buffer-face-mode-face)
5273 (require 'outline)
5274 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5275 (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"))
5276 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5278 ;; Other stuff we need.
5279 (require 'time-date)
5280 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5281 (require 'easymenu)
5282 (require 'overlay)
5284 ;; (require 'org-macs) moved higher up in the file before it is first used
5285 (require 'org-entities)
5286 ;; (require 'org-compat) moved higher up in the file before it is first used
5287 (require 'org-faces)
5288 (require 'org-list)
5289 (require 'org-pcomplete)
5290 (require 'org-src)
5291 (require 'org-footnote)
5292 (require 'org-macro)
5294 ;; babel
5295 (require 'ob)
5297 ;;;###autoload
5298 (define-derived-mode org-mode outline-mode "Org"
5299 "Outline-based notes management and organizer, alias
5300 \"Carsten's outline-mode for keeping track of everything.\"
5302 Org-mode develops organizational tasks around a NOTES file which
5303 contains information about projects as plain text. Org-mode is
5304 implemented on top of outline-mode, which is ideal to keep the content
5305 of large files well structured. It supports ToDo items, deadlines and
5306 time stamps, which magically appear in the diary listing of the Emacs
5307 calendar. Tables are easily created with a built-in table editor.
5308 Plain text URL-like links connect to websites, emails (VM), Usenet
5309 messages (Gnus), BBDB entries, and any files related to the project.
5310 For printing and sharing of notes, an Org-mode file (or a part of it)
5311 can be exported as a structured ASCII or HTML file.
5313 The following commands are available:
5315 \\{org-mode-map}"
5317 ;; Get rid of Outline menus, they are not needed
5318 ;; Need to do this here because define-derived-mode sets up
5319 ;; the keymap so late. Still, it is a waste to call this each time
5320 ;; we switch another buffer into org-mode.
5321 (if (featurep 'xemacs)
5322 (when (boundp 'outline-mode-menu-heading)
5323 ;; Assume this is Greg's port, it uses easymenu
5324 (easy-menu-remove outline-mode-menu-heading)
5325 (easy-menu-remove outline-mode-menu-show)
5326 (easy-menu-remove outline-mode-menu-hide))
5327 (define-key org-mode-map [menu-bar headings] 'undefined)
5328 (define-key org-mode-map [menu-bar hide] 'undefined)
5329 (define-key org-mode-map [menu-bar show] 'undefined))
5331 (org-load-modules-maybe)
5332 (easy-menu-add org-org-menu)
5333 (easy-menu-add org-tbl-menu)
5334 (org-install-agenda-files-menu)
5335 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5336 (add-to-invisibility-spec '(org-cwidth))
5337 (add-to-invisibility-spec '(org-hide-block . t))
5338 (when (featurep 'xemacs)
5339 (org-set-local 'line-move-ignore-invisible t))
5340 (org-set-local 'outline-regexp org-outline-regexp)
5341 (org-set-local 'outline-level 'org-outline-level)
5342 (setq bidi-paragraph-direction 'left-to-right)
5343 (when (and org-ellipsis
5344 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5345 (fboundp 'make-glyph-code))
5346 (unless org-display-table
5347 (setq org-display-table (make-display-table)))
5348 (set-display-table-slot
5349 org-display-table 4
5350 (vconcat (mapcar
5351 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5352 org-ellipsis)))
5353 (if (stringp org-ellipsis) org-ellipsis "..."))))
5354 (setq buffer-display-table org-display-table))
5355 (org-set-regexps-and-options-for-tags)
5356 (org-set-regexps-and-options)
5357 (org-set-font-lock-defaults)
5358 (when (and org-tag-faces (not org-tags-special-faces-re))
5359 ;; tag faces set outside customize.... force initialization.
5360 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5361 ;; Calc embedded
5362 (org-set-local 'calc-embedded-open-mode "# ")
5363 ;; Modify a few syntax entries
5364 (modify-syntax-entry ?@ "w")
5365 (modify-syntax-entry ?\" "\"")
5366 (modify-syntax-entry ?\\ "_")
5367 (modify-syntax-entry ?~ "_")
5368 (if org-startup-truncated (setq truncate-lines t))
5369 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5370 (org-set-local 'font-lock-unfontify-region-function
5371 'org-unfontify-region)
5372 ;; Activate before-change-function
5373 (org-set-local 'org-table-may-need-update t)
5374 (org-add-hook 'before-change-functions 'org-before-change-function nil
5375 'local)
5376 ;; Check for running clock before killing a buffer
5377 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5378 ;; Initialize macros templates.
5379 (org-macro-initialize-templates)
5380 ;; Initialize radio targets.
5381 (org-update-radio-target-regexp)
5382 ;; Indentation.
5383 (org-set-local 'indent-line-function 'org-indent-line)
5384 (org-set-local 'indent-region-function 'org-indent-region)
5385 ;; Filling and auto-filling.
5386 (org-setup-filling)
5387 ;; Comments.
5388 (org-setup-comments-handling)
5389 ;; Beginning/end of defun
5390 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5391 (org-set-local 'end-of-defun-function
5392 (lambda ()
5393 (if (not (org-at-heading-p))
5394 (org-forward-element)
5395 (org-forward-element)
5396 (forward-char -1))))
5397 ;; Next error for sparse trees
5398 (org-set-local 'next-error-function 'org-occur-next-match)
5399 ;; Make sure dependence stuff works reliably, even for users who set it
5400 ;; too late :-(
5401 (if org-enforce-todo-dependencies
5402 (add-hook 'org-blocker-hook
5403 'org-block-todo-from-children-or-siblings-or-parent)
5404 (remove-hook 'org-blocker-hook
5405 'org-block-todo-from-children-or-siblings-or-parent))
5406 (if org-enforce-todo-checkbox-dependencies
5407 (add-hook 'org-blocker-hook
5408 'org-block-todo-from-checkboxes)
5409 (remove-hook 'org-blocker-hook
5410 'org-block-todo-from-checkboxes))
5412 ;; Align options lines
5413 (org-set-local
5414 'align-mode-rules-list
5415 '((org-in-buffer-settings
5416 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5417 (modes . '(org-mode)))))
5419 ;; Imenu
5420 (org-set-local 'imenu-create-index-function
5421 'org-imenu-get-tree)
5423 ;; Make isearch reveal context
5424 (if (or (featurep 'xemacs)
5425 (not (boundp 'outline-isearch-open-invisible-function)))
5426 ;; Emacs 21 and XEmacs make use of the hook
5427 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5428 ;; Emacs 22 deals with this through a special variable
5429 (org-set-local 'outline-isearch-open-invisible-function
5430 (lambda (&rest ignore) (org-show-context 'isearch))))
5432 ;; Setup the pcomplete hooks
5433 (set (make-local-variable 'pcomplete-command-completion-function)
5434 'org-pcomplete-initial)
5435 (set (make-local-variable 'pcomplete-command-name-function)
5436 'org-command-at-point)
5437 (set (make-local-variable 'pcomplete-default-completion-function)
5438 'ignore)
5439 (set (make-local-variable 'pcomplete-parse-arguments-function)
5440 'org-parse-arguments)
5441 (set (make-local-variable 'pcomplete-termination-string) "")
5442 (when (>= emacs-major-version 23)
5443 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5445 ;; If empty file that did not turn on org-mode automatically, make it to.
5446 (if (and org-insert-mode-line-in-empty-file
5447 (org-called-interactively-p 'any)
5448 (= (point-min) (point-max)))
5449 (insert "# -*- mode: org -*-\n\n"))
5450 (unless org-inhibit-startup
5451 (org-unmodified
5452 (and org-startup-with-beamer-mode (org-beamer-mode))
5453 (when org-startup-align-all-tables
5454 (org-table-map-tables 'org-table-align 'quietly))
5455 (when org-startup-with-inline-images
5456 (org-display-inline-images))
5457 (when org-startup-with-latex-preview
5458 (org-preview-latex-fragment))
5459 (unless org-inhibit-startup-visibility-stuff
5460 (org-set-startup-visibility))))
5461 ;; Try to set org-hide correctly
5462 (let ((foreground (org-find-invisible-foreground)))
5463 (if foreground
5464 (set-face-foreground 'org-hide foreground))))
5466 ;; Update `customize-package-emacs-version-alist'
5467 (add-to-list 'customize-package-emacs-version-alist
5468 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5469 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5470 ("8.2.6" . "24.4")))
5472 (defvar org-mode-transpose-word-syntax-table
5473 (let ((st (make-syntax-table)))
5474 (mapc (lambda(c) (modify-syntax-entry
5475 (string-to-char (car c)) "w p" st))
5476 org-emphasis-alist)
5477 st))
5479 (when (fboundp 'abbrev-table-put)
5480 (abbrev-table-put org-mode-abbrev-table
5481 :parents (list text-mode-abbrev-table)))
5483 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5485 (defun org-find-invisible-foreground ()
5486 (let ((candidates (remove
5487 "unspecified-bg"
5488 (nconc
5489 (list (face-background 'default)
5490 (face-background 'org-default))
5491 (mapcar
5492 (lambda (alist)
5493 (when (boundp alist)
5494 (cdr (assoc 'background-color (symbol-value alist)))))
5495 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5496 (list (face-foreground 'org-hide))))))
5497 (car (remove nil candidates))))
5499 (defun org-current-time (&optional rounding-minutes past)
5500 "Current time, possibly rounded to ROUNDING-MINUTES.
5501 When ROUNDING-MINUTES is not an integer, fall back on the car of
5502 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5503 the rounding returns a past time."
5504 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5505 (car org-time-stamp-rounding-minutes)))
5506 (time (decode-time)) res)
5507 (if (< r 1)
5508 (current-time)
5509 (setq res
5510 (apply 'encode-time
5511 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5512 (nthcdr 2 time))))
5513 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5514 (seconds-to-time (- (org-float-time res) (* r 60)))
5515 res))))
5517 (defun org-today ()
5518 "Return today date, considering `org-extend-today-until'."
5519 (time-to-days
5520 (time-subtract (current-time)
5521 (list 0 (* 3600 org-extend-today-until) 0))))
5523 ;;;; Font-Lock stuff, including the activators
5525 (defvar org-mouse-map (make-sparse-keymap))
5526 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5527 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5528 (when org-mouse-1-follows-link
5529 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5530 (when org-tab-follows-link
5531 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5532 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5534 (require 'font-lock)
5536 (defconst org-non-link-chars "]\t\n\r<>")
5537 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5538 "shell" "elisp" "doi" "message"))
5539 (defvar org-link-types-re nil
5540 "Matches a link that has a url-like prefix like \"http:\"")
5541 (defvar org-link-re-with-space nil
5542 "Matches a link with spaces, optional angular brackets around it.")
5543 (defvar org-link-re-with-space2 nil
5544 "Matches a link with spaces, optional angular brackets around it.")
5545 (defvar org-link-re-with-space3 nil
5546 "Matches a link with spaces, only for internal part in bracket links.")
5547 (defvar org-angle-link-re nil
5548 "Matches link with angular brackets, spaces are allowed.")
5549 (defvar org-plain-link-re nil
5550 "Matches plain link, without spaces.")
5551 (defvar org-bracket-link-regexp nil
5552 "Matches a link in double brackets.")
5553 (defvar org-bracket-link-analytic-regexp nil
5554 "Regular expression used to analyze links.
5555 Here is what the match groups contain after a match:
5556 1: http:
5557 2: http
5558 3: path
5559 4: [desc]
5560 5: desc")
5561 (defvar org-bracket-link-analytic-regexp++ nil
5562 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5563 (defvar org-any-link-re nil
5564 "Regular expression matching any link.")
5566 (defconst org-match-sexp-depth 3
5567 "Number of stacked braces for sub/superscript matching.")
5569 (defun org-create-multibrace-regexp (left right n)
5570 "Create a regular expression which will match a balanced sexp.
5571 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5572 as single character strings.
5573 The regexp returned will match the entire expression including the
5574 delimiters. It will also define a single group which contains the
5575 match except for the outermost delimiters. The maximum depth of
5576 stacked delimiters is N. Escaping delimiters is not possible."
5577 (let* ((nothing (concat "[^" left right "]*?"))
5578 (or "\\|")
5579 (re nothing)
5580 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5581 (while (> n 1)
5582 (setq n (1- n)
5583 re (concat re or next)
5584 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5585 (concat left "\\(" re "\\)" right)))
5587 (defvar org-match-substring-regexp
5588 (concat
5589 "\\(\\S-\\)\\([_^]\\)\\("
5590 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5591 "\\|"
5592 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5593 "\\|"
5594 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5595 "The regular expression matching a sub- or superscript.")
5597 (defvar org-match-substring-with-braces-regexp
5598 (concat
5599 "\\(\\S-\\)\\([_^]\\)\\("
5600 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5601 "\\)")
5602 "The regular expression matching a sub- or superscript, forcing braces.")
5604 (defun org-make-link-regexps ()
5605 "Update the link regular expressions.
5606 This should be called after the variable `org-link-types' has changed."
5607 (let ((types-re (regexp-opt org-link-types t)))
5608 (setq org-link-types-re
5609 (concat "\\`" types-re ":")
5610 org-link-re-with-space
5611 (concat "<?" types-re ":"
5612 "\\([^" org-non-link-chars " ]"
5613 "[^" org-non-link-chars "]*"
5614 "[^" org-non-link-chars " ]\\)>?")
5615 org-link-re-with-space2
5616 (concat "<?" types-re ":"
5617 "\\([^" org-non-link-chars " ]"
5618 "[^\t\n\r]*"
5619 "[^" org-non-link-chars " ]\\)>?")
5620 org-link-re-with-space3
5621 (concat "<?" types-re ":"
5622 "\\([^" org-non-link-chars " ]"
5623 "[^\t\n\r]*\\)")
5624 org-angle-link-re
5625 (concat "<" types-re ":"
5626 "\\([^" org-non-link-chars " ]"
5627 "[^" org-non-link-chars "]*"
5628 "\\)>")
5629 org-plain-link-re
5630 (concat
5631 "\\<" types-re ":"
5632 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5633 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5634 org-bracket-link-regexp
5635 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5636 org-bracket-link-analytic-regexp
5637 (concat
5638 "\\[\\["
5639 "\\(" types-re ":\\)?"
5640 "\\([^]]+\\)"
5641 "\\]"
5642 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5643 "\\]")
5644 org-bracket-link-analytic-regexp++
5645 (concat
5646 "\\[\\["
5647 "\\(" (regexp-opt (cons "coderef" org-link-types) t) ":\\)?"
5648 "\\([^]]+\\)"
5649 "\\]"
5650 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5651 "\\]")
5652 org-any-link-re
5653 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5654 org-angle-link-re "\\)\\|\\("
5655 org-plain-link-re "\\)"))))
5657 (org-make-link-regexps)
5659 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5660 "Regular expression for fast time stamp matching.")
5661 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5662 "Regular expression for fast time stamp matching.")
5663 (defconst org-ts-regexp0
5664 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5665 "Regular expression matching time strings for analysis.
5666 This one does not require the space after the date, so it can be used
5667 on a string that terminates immediately after the date.")
5668 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5669 "Regular expression matching time strings for analysis.")
5670 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5671 "Regular expression matching time stamps, with groups.")
5672 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5673 "Regular expression matching time stamps (also [..]), with groups.")
5674 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5675 "Regular expression matching a time stamp range.")
5676 (defconst org-tr-regexp-both
5677 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5678 "Regular expression matching a time stamp range.")
5679 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5680 org-ts-regexp "\\)?")
5681 "Regular expression matching a time stamp or time stamp range.")
5682 (defconst org-tsr-regexp-both
5683 (concat org-ts-regexp-both "\\(--?-?"
5684 org-ts-regexp-both "\\)?")
5685 "Regular expression matching a time stamp or time stamp range.
5686 The time stamps may be either active or inactive.")
5688 (defvar org-emph-face nil)
5690 (defun org-do-emphasis-faces (limit)
5691 "Run through the buffer and add overlays to emphasized strings."
5692 (let (rtn a)
5693 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5694 (let* ((border (char-after (match-beginning 3)))
5695 (bre (regexp-quote (char-to-string border))))
5696 (if (and (not (= border (char-after (match-beginning 4))))
5697 (not (save-match-data
5698 (string-match (concat bre ".*" bre)
5699 (replace-regexp-in-string
5700 "\n" " "
5701 (substring (match-string 2) 1 -1))))))
5702 (progn
5703 (setq rtn t)
5704 (setq a (assoc (match-string 3) org-emphasis-alist))
5705 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5706 'face
5707 (nth 1 a))
5708 (and (nth 2 a)
5709 (org-remove-flyspell-overlays-in
5710 (match-beginning 0) (match-end 0)))
5711 (add-text-properties (match-beginning 2) (match-end 2)
5712 '(font-lock-multiline t org-emphasis t))
5713 (when org-hide-emphasis-markers
5714 (add-text-properties (match-end 4) (match-beginning 5)
5715 '(invisible org-link))
5716 (add-text-properties (match-beginning 3) (match-end 3)
5717 '(invisible org-link))))))
5718 (goto-char (1+ (match-beginning 0))))
5719 rtn))
5721 (defun org-emphasize (&optional char)
5722 "Insert or change an emphasis, i.e. a font like bold or italic.
5723 If there is an active region, change that region to a new emphasis.
5724 If there is no region, just insert the marker characters and position
5725 the cursor between them.
5726 CHAR should be the marker character. If it is a space, it means to
5727 remove the emphasis of the selected region.
5728 If CHAR is not given (for example in an interactive call) it will be
5729 prompted for."
5730 (interactive)
5731 (let ((erc org-emphasis-regexp-components)
5732 (prompt "")
5733 (string "") beg end move c s)
5734 (if (org-region-active-p)
5735 (setq beg (region-beginning) end (region-end)
5736 string (buffer-substring beg end))
5737 (setq move t))
5739 (unless char
5740 (message "Emphasis marker or tag: [%s]"
5741 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5742 (setq char (read-char-exclusive)))
5743 (if (equal char ?\ )
5744 (setq s "" move nil)
5745 (unless (assoc (char-to-string char) org-emphasis-alist)
5746 (user-error "No such emphasis marker: \"%c\"" char))
5747 (setq s (char-to-string char)))
5748 (while (and (> (length string) 1)
5749 (equal (substring string 0 1) (substring string -1))
5750 (assoc (substring string 0 1) org-emphasis-alist))
5751 (setq string (substring string 1 -1)))
5752 (setq string (concat s string s))
5753 (if beg (delete-region beg end))
5754 (unless (or (bolp)
5755 (string-match (concat "[" (nth 0 erc) "\n]")
5756 (char-to-string (char-before (point)))))
5757 (insert " "))
5758 (unless (or (eobp)
5759 (string-match (concat "[" (nth 1 erc) "\n]")
5760 (char-to-string (char-after (point)))))
5761 (insert " ") (backward-char 1))
5762 (insert string)
5763 (and move (backward-char 1))))
5765 (defconst org-nonsticky-props
5766 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5768 (defsubst org-rear-nonsticky-at (pos)
5769 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5771 (defun org-activate-plain-links (limit)
5772 "Run through the buffer and add overlays to links."
5773 (let (f hl)
5774 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5775 (not (org-in-src-block-p)))
5776 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5777 (setq f (get-text-property (match-beginning 0) 'face))
5778 (setq hl (org-match-string-no-properties 0))
5779 (if (or (eq f 'org-tag)
5780 (and (listp f) (memq 'org-tag f)))
5782 (add-text-properties (match-beginning 0) (match-end 0)
5783 (list 'mouse-face 'highlight
5784 'face 'org-link
5785 'htmlize-link `(:uri ,hl)
5786 'keymap org-mouse-map))
5787 (org-rear-nonsticky-at (match-end 0)))
5788 t)))
5790 (defun org-activate-code (limit)
5791 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5792 (progn
5793 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5794 (remove-text-properties (match-beginning 0) (match-end 0)
5795 '(display t invisible t intangible t))
5796 t)))
5798 (defcustom org-src-fontify-natively nil
5799 "When non-nil, fontify code in code blocks."
5800 :type 'boolean
5801 :version "24.1"
5802 :group 'org-appearance
5803 :group 'org-babel)
5805 (defcustom org-allow-promoting-top-level-subtree nil
5806 "When non-nil, allow promoting a top level subtree.
5807 The leading star of the top level headline will be replaced
5808 by a #."
5809 :type 'boolean
5810 :version "24.1"
5811 :group 'org-appearance)
5813 (defun org-fontify-meta-lines-and-blocks (limit)
5814 (condition-case nil
5815 (org-fontify-meta-lines-and-blocks-1 limit)
5816 (error (message "org-mode fontification error"))))
5818 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5819 "Fontify #+ lines and blocks."
5820 (let ((case-fold-search t))
5821 (if (re-search-forward
5822 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5823 limit t)
5824 (let ((beg (match-beginning 0))
5825 (block-start (match-end 0))
5826 (block-end nil)
5827 (lang (match-string 7))
5828 (beg1 (line-beginning-position 2))
5829 (dc1 (downcase (match-string 2)))
5830 (dc3 (downcase (match-string 3)))
5831 end end1 quoting block-type ovl)
5832 (cond
5833 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5834 ;; a single line of backend-specific content
5835 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5836 (remove-text-properties (match-beginning 0) (match-end 0)
5837 '(display t invisible t intangible t))
5838 (add-text-properties (match-beginning 1) (match-end 3)
5839 '(font-lock-fontified t face org-meta-line))
5840 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5841 '(font-lock-fontified t face org-block))
5842 ; for backend-specific code
5844 ((and (match-end 4) (equal dc3 "+begin"))
5845 ;; Truly a block
5846 (setq block-type (downcase (match-string 5))
5847 quoting (member block-type org-protecting-blocks))
5848 (when (re-search-forward
5849 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5850 nil t) ;; on purpose, we look further than LIMIT
5851 (setq end (min (point-max) (match-end 0))
5852 end1 (min (point-max) (1- (match-beginning 0))))
5853 (setq block-end (match-beginning 0))
5854 (when quoting
5855 (remove-text-properties beg end
5856 '(display t invisible t intangible t)))
5857 (add-text-properties
5858 beg end
5859 '(font-lock-fontified t font-lock-multiline t))
5860 (add-text-properties beg beg1 '(face org-meta-line))
5861 (add-text-properties end1 (min (point-max) (1+ end))
5862 '(face org-meta-line)) ; for end_src
5863 (cond
5864 ((and lang (not (string= lang "")) org-src-fontify-natively)
5865 (org-src-font-lock-fontify-block lang block-start block-end)
5866 ;; remove old background overlays
5867 (mapc (lambda (ov)
5868 (if (eq (overlay-get ov 'face) 'org-block-background)
5869 (delete-overlay ov)))
5870 (overlays-at (/ (+ beg1 block-end) 2)))
5871 ;; add a background overlay
5872 (setq ovl (make-overlay beg1 block-end))
5873 (overlay-put ovl 'face 'org-block-background)
5874 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5875 (quoting
5876 (add-text-properties beg1 (min (point-max) (1+ end1))
5877 '(face org-block))) ; end of source block
5878 ((not org-fontify-quote-and-verse-blocks))
5879 ((string= block-type "quote")
5880 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5881 ((string= block-type "verse")
5882 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5883 (add-text-properties beg beg1 '(face org-block-begin-line))
5884 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5885 '(face org-block-end-line))
5887 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5888 (add-text-properties
5889 beg (match-end 3)
5890 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
5891 '(font-lock-fontified t invisible t)
5892 '(font-lock-fontified t face org-document-info-keyword)))
5893 (add-text-properties
5894 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5895 (if (string-equal dc1 "+title:")
5896 '(font-lock-fontified t face org-document-title)
5897 '(font-lock-fontified t face org-document-info))))
5898 ((or (equal dc1 "+results")
5899 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5900 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5901 "+call:" "+header:" "+headers:" "+name:"))
5902 (and (match-end 4) (equal dc3 "+attr")))
5903 (add-text-properties
5904 beg (match-end 0)
5905 '(font-lock-fontified t face org-meta-line))
5907 ((member dc3 '(" " ""))
5908 (add-text-properties
5909 beg (match-end 0)
5910 '(font-lock-fontified t face font-lock-comment-face)))
5911 ((not (member (char-after beg) '(?\ ?\t)))
5912 ;; just any other in-buffer setting, but not indented
5913 (add-text-properties
5914 beg (match-end 0)
5915 '(font-lock-fontified t face org-meta-line))
5917 (t nil))))))
5919 (defun org-activate-angle-links (limit)
5920 "Run through the buffer and add overlays to links."
5921 (if (and (re-search-forward org-angle-link-re limit t)
5922 (not (org-in-src-block-p)))
5923 (progn
5924 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5925 (add-text-properties (match-beginning 0) (match-end 0)
5926 (list 'mouse-face 'highlight
5927 'keymap org-mouse-map))
5928 (org-rear-nonsticky-at (match-end 0))
5929 t)))
5931 (defun org-activate-footnote-links (limit)
5932 "Run through the buffer and add overlays to footnotes."
5933 (let ((fn (org-footnote-next-reference-or-definition limit)))
5934 (when fn
5935 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5936 (org-remove-flyspell-overlays-in beg end)
5937 (add-text-properties beg end
5938 (list 'mouse-face 'highlight
5939 'keymap org-mouse-map
5940 'help-echo
5941 (if (= (point-at-bol) beg)
5942 "Footnote definition"
5943 "Footnote reference")
5944 'font-lock-fontified t
5945 'font-lock-multiline t
5946 'face 'org-footnote))))))
5948 (defun org-activate-bracket-links (limit)
5949 "Run through the buffer and add overlays to bracketed links."
5950 (if (and (re-search-forward org-bracket-link-regexp limit t)
5951 (not (org-in-src-block-p)))
5952 (let* ((hl (org-match-string-no-properties 1))
5953 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
5954 (ip (org-maybe-intangible
5955 (list 'invisible 'org-link
5956 'keymap org-mouse-map 'mouse-face 'highlight
5957 'font-lock-multiline t 'help-echo help
5958 'htmlize-link `(:uri ,hl))))
5959 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5960 'font-lock-multiline t 'help-echo help
5961 'htmlize-link `(:uri ,hl))))
5962 ;; We need to remove the invisible property here. Table narrowing
5963 ;; may have made some of this invisible.
5964 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5965 (remove-text-properties (match-beginning 0) (match-end 0)
5966 '(invisible nil))
5967 (if (match-end 3)
5968 (progn
5969 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5970 (org-rear-nonsticky-at (match-beginning 3))
5971 (add-text-properties (match-beginning 3) (match-end 3) vp)
5972 (org-rear-nonsticky-at (match-end 3))
5973 (add-text-properties (match-end 3) (match-end 0) ip)
5974 (org-rear-nonsticky-at (match-end 0)))
5975 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5976 (org-rear-nonsticky-at (match-beginning 1))
5977 (add-text-properties (match-beginning 1) (match-end 1) vp)
5978 (org-rear-nonsticky-at (match-end 1))
5979 (add-text-properties (match-end 1) (match-end 0) ip)
5980 (org-rear-nonsticky-at (match-end 0)))
5981 t)))
5983 (defun org-activate-dates (limit)
5984 "Run through the buffer and add overlays to dates."
5985 (if (and (re-search-forward org-tsr-regexp-both limit t)
5986 (not (equal (char-before (match-beginning 0)) 91)))
5987 (progn
5988 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5989 (add-text-properties (match-beginning 0) (match-end 0)
5990 (list 'mouse-face 'highlight
5991 'keymap org-mouse-map))
5992 (org-rear-nonsticky-at (match-end 0))
5993 (when org-display-custom-times
5994 (if (match-end 3)
5995 (org-display-custom-time (match-beginning 3) (match-end 3)))
5996 (org-display-custom-time (match-beginning 1) (match-end 1)))
5997 t)))
5999 (defvar org-target-link-regexp nil
6000 "Regular expression matching radio targets in plain text.")
6001 (make-variable-buffer-local 'org-target-link-regexp)
6002 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
6003 "Regular expression matching a link target.")
6004 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
6005 "Regular expression matching a radio target.")
6006 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
6007 "Regular expression matching any target.")
6009 (defun org-activate-target-links (limit)
6010 "Run through the buffer and add overlays to target matches."
6011 (when org-target-link-regexp
6012 (let ((case-fold-search t))
6013 (if (re-search-forward org-target-link-regexp limit t)
6014 (progn
6015 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6016 (add-text-properties (match-beginning 0) (match-end 0)
6017 (list 'mouse-face 'highlight
6018 'keymap org-mouse-map
6019 'help-echo "Radio target link"
6020 'org-linked-text t))
6021 (org-rear-nonsticky-at (match-end 0))
6022 t)))))
6024 (defun org-update-radio-target-regexp ()
6025 "Find all radio targets in this file and update the regular expression."
6026 (interactive)
6027 (when (memq 'radio org-activate-links)
6028 (setq org-target-link-regexp
6029 (org-make-target-link-regexp (org-all-targets 'radio)))
6030 (org-restart-font-lock)))
6032 (defun org-hide-wide-columns (limit)
6033 (let (s e)
6034 (setq s (text-property-any (point) (or limit (point-max))
6035 'org-cwidth t))
6036 (when s
6037 (setq e (next-single-property-change s 'org-cwidth))
6038 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6039 (goto-char e)
6040 t)))
6042 (defvar org-latex-and-related-regexp nil
6043 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6044 (defvar org-match-substring-regexp)
6045 (defvar org-match-substring-with-braces-regexp)
6047 (defun org-compute-latex-and-related-regexp ()
6048 "Compute regular expression for LaTeX, entities and sub/superscript.
6049 Result depends on variable `org-highlight-latex-and-related'."
6050 (org-set-local
6051 'org-latex-and-related-regexp
6052 (let* ((re-sub
6053 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6054 ((eq org-use-sub-superscripts '{})
6055 (list org-match-substring-with-braces-regexp))
6056 (org-use-sub-superscripts (list org-match-substring-regexp))))
6057 (re-latex
6058 (when (memq 'latex org-highlight-latex-and-related)
6059 (let ((matchers (plist-get org-format-latex-options :matchers)))
6060 (delq nil
6061 (mapcar (lambda (x)
6062 (and (member (car x) matchers) (nth 1 x)))
6063 org-latex-regexps)))))
6064 (re-entities
6065 (when (memq 'entities org-highlight-latex-and-related)
6066 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6067 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6069 (defun org-do-latex-and-related (limit)
6070 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6071 LIMIT bounds the search for syntax to highlight. Stop at first
6072 highlighted object, if any. Return t if some highlighting was
6073 done, nil otherwise."
6074 (when (org-string-nw-p org-latex-and-related-regexp)
6075 (catch 'found
6076 (while (re-search-forward org-latex-and-related-regexp limit t)
6077 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6078 'face))
6079 '(org-code org-verbatim underline))
6080 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6081 '(?_ ?^))
6083 0)))
6084 (font-lock-prepend-text-property
6085 (+ offset (match-beginning 0)) (match-end 0)
6086 'face 'org-latex-and-related)
6087 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6088 '(font-lock-multiline t)))
6089 (throw 'found t)))
6090 nil)))
6092 (defun org-restart-font-lock ()
6093 "Restart `font-lock-mode', to force refontification."
6094 (when (and (boundp 'font-lock-mode) font-lock-mode)
6095 (font-lock-mode -1)
6096 (font-lock-mode 1)))
6098 (defun org-all-targets (&optional radio)
6099 "Return a list of all targets in this file.
6100 When optional argument RADIO is non-nil, only find radio
6101 targets."
6102 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
6103 (save-excursion
6104 (goto-char (point-min))
6105 (while (re-search-forward re nil t)
6106 ;; Make sure point is really within the object.
6107 (backward-char)
6108 (let ((obj (org-element-context)))
6109 (when (memq (org-element-type obj) '(radio-target target))
6110 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
6111 rtn)))
6113 (defun org-make-target-link-regexp (targets)
6114 "Make regular expression matching all strings in TARGETS.
6115 The regular expression finds the targets also if there is a line break
6116 between words."
6117 (and targets
6118 (concat
6119 "\\_<\\("
6120 (mapconcat
6121 (lambda (x)
6122 (setq x (regexp-quote x))
6123 (while (string-match " +" x)
6124 (setq x (replace-match "\\s-+" t t x)))
6126 targets
6127 "\\|")
6128 "\\)\\_>")))
6130 (defun org-activate-tags (limit)
6131 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6132 (progn
6133 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6134 (add-text-properties (match-beginning 1) (match-end 1)
6135 (list 'mouse-face 'highlight
6136 'keymap org-mouse-map))
6137 (org-rear-nonsticky-at (match-end 1))
6138 t)))
6140 (defun org-outline-level ()
6141 "Compute the outline level of the heading at point.
6142 If this is called at a normal headline, the level is the number of stars.
6143 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6144 (save-excursion
6145 (if (not (condition-case nil
6146 (org-back-to-heading t)
6147 (error nil)))
6149 (looking-at org-outline-regexp)
6150 (1- (- (match-end 0) (match-beginning 0))))))
6152 (defvar org-font-lock-keywords nil)
6154 (defsubst org-re-property (property &optional literal allow-null)
6155 "Return a regexp matching a PROPERTY line.
6156 Match group 3 will be set to the value if it exists."
6157 (concat "^\\(?4:[ \t]*\\)\\(?1::\\(?2:"
6158 (if literal property (regexp-quote property))
6159 "\\):\\)[ \t]+\\(?3:[^ \t\r\n]"
6160 (if allow-null "*")
6161 ".*?\\)\\(?5:[ \t]*\\)$"))
6163 (defconst org-property-re
6164 (org-re-property ".*?" 'literal t)
6165 "Regular expression matching a property line.
6166 There are four matching groups:
6167 1: :PROPKEY: including the leading and trailing colon,
6168 2: PROPKEY without the leading and trailing colon,
6169 3: PROPVAL without leading or trailing spaces,
6170 4: the indentation of the current line,
6171 5: trailing whitespace.")
6173 (defvar org-font-lock-hook nil
6174 "Functions to be called for special font lock stuff.")
6176 (defvar org-font-lock-set-keywords-hook nil
6177 "Functions that can manipulate `org-font-lock-extra-keywords'.
6178 This is called after `org-font-lock-extra-keywords' is defined, but before
6179 it is installed to be used by font lock. This can be useful if something
6180 needs to be inserted at a specific position in the font-lock sequence.")
6182 (defun org-font-lock-hook (limit)
6183 "Run `org-font-lock-hook' within LIMIT."
6184 (run-hook-with-args 'org-font-lock-hook limit))
6186 (defun org-set-font-lock-defaults ()
6187 "Set font lock defaults for the current buffer."
6188 (let* ((em org-fontify-emphasized-text)
6189 (lk org-activate-links)
6190 (org-font-lock-extra-keywords
6191 (list
6192 ;; Call the hook
6193 '(org-font-lock-hook)
6194 ;; Headlines
6195 `(,(if org-fontify-whole-heading-line
6196 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6197 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6198 (1 (org-get-level-face 1))
6199 (2 (org-get-level-face 2))
6200 (3 (org-get-level-face 3)))
6201 ;; Table lines
6202 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6203 (1 'org-table t))
6204 ;; Table internals
6205 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6206 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6207 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6208 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6209 ;; Drawers
6210 (list org-drawer-regexp '(0 'org-special-keyword t))
6211 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
6212 ;; Properties
6213 (list org-property-re
6214 '(1 'org-special-keyword t)
6215 '(3 'org-property-value t))
6216 ;; Links
6217 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6218 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6219 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6220 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6221 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6222 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6223 (if (memq 'footnote lk) '(org-activate-footnote-links))
6224 ;; Targets.
6225 (list org-any-target-regexp '(0 'org-target t))
6226 ;; Diary sexps.
6227 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6228 ;; Macro
6229 '("{{{.+}}}" (0 'org-macro t))
6230 '(org-hide-wide-columns (0 nil append))
6231 ;; TODO keyword
6232 (list (format org-heading-keyword-regexp-format
6233 org-todo-regexp)
6234 '(2 (org-get-todo-face 2) t))
6235 ;; DONE
6236 (if org-fontify-done-headline
6237 (list (format org-heading-keyword-regexp-format
6238 (concat
6239 "\\(?:"
6240 (mapconcat 'regexp-quote org-done-keywords "\\|")
6241 "\\)"))
6242 '(2 'org-headline-done t))
6243 nil)
6244 ;; Priorities
6245 '(org-font-lock-add-priority-faces)
6246 ;; Tags
6247 '(org-font-lock-add-tag-faces)
6248 ;; Tags groups
6249 (if (and org-group-tags org-tag-groups-alist)
6250 (list (concat org-outline-regexp-bol ".+\\(:"
6251 (regexp-opt (mapcar 'car org-tag-groups-alist))
6252 ":\\).*$")
6253 '(1 'org-tag-group prepend)))
6254 ;; Special keywords
6255 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6256 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6257 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6258 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6259 ;; Emphasis
6260 (if em
6261 (if (featurep 'xemacs)
6262 '(org-do-emphasis-faces (0 nil append))
6263 '(org-do-emphasis-faces)))
6264 ;; Checkboxes
6265 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6266 1 'org-checkbox prepend)
6267 (if (cdr (assq 'checkbox org-list-automatic-rules))
6268 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6269 (0 (org-get-checkbox-statistics-face) t)))
6270 ;; Description list items
6271 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6272 1 'org-list-dt prepend)
6273 ;; ARCHIVEd headings
6274 (list (concat
6275 org-outline-regexp-bol
6276 "\\(.*:" org-archive-tag ":.*\\)")
6277 '(1 'org-archived prepend))
6278 ;; Specials
6279 '(org-do-latex-and-related)
6280 '(org-fontify-entities)
6281 '(org-raise-scripts)
6282 ;; Code
6283 '(org-activate-code (1 'org-code t))
6284 ;; COMMENT
6285 (list (format org-heading-keyword-regexp-format
6286 (concat "\\("
6287 org-comment-string "\\|" org-quote-string
6288 "\\)"))
6289 '(2 'org-special-keyword t))
6290 ;; Blocks and meta lines
6291 '(org-fontify-meta-lines-and-blocks))))
6292 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6293 (run-hooks 'org-font-lock-set-keywords-hook)
6294 ;; Now set the full font-lock-keywords
6295 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6296 (org-set-local 'font-lock-defaults
6297 '(org-font-lock-keywords t nil nil backward-paragraph))
6298 (kill-local-variable 'font-lock-keywords) nil))
6300 (defun org-toggle-pretty-entities ()
6301 "Toggle the composition display of entities as UTF8 characters."
6302 (interactive)
6303 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6304 (org-restart-font-lock)
6305 (if org-pretty-entities
6306 (message "Entities are now displayed as UTF8 characters")
6307 (save-restriction
6308 (widen)
6309 (org-decompose-region (point-min) (point-max))
6310 (message "Entities are now displayed as plain text"))))
6312 (defvar org-custom-properties-overlays nil
6313 "List of overlays used for custom properties.")
6314 (make-variable-buffer-local 'org-custom-properties-overlays)
6316 (defun org-toggle-custom-properties-visibility ()
6317 "Display or hide properties in `org-custom-properties'."
6318 (interactive)
6319 (if org-custom-properties-overlays
6320 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6321 (setq org-custom-properties-overlays nil))
6322 (unless (not org-custom-properties)
6323 (save-excursion
6324 (save-restriction
6325 (widen)
6326 (goto-char (point-min))
6327 (while (re-search-forward org-property-re nil t)
6328 (mapc (lambda(p)
6329 (when (equal p (substring (match-string 1) 1 -1))
6330 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6331 (overlay-put o 'invisible t)
6332 (overlay-put o 'org-custom-property t)
6333 (push o org-custom-properties-overlays))))
6334 org-custom-properties)))))))
6336 (defun org-fontify-entities (limit)
6337 "Find an entity to fontify."
6338 (let (ee)
6339 (when org-pretty-entities
6340 (catch 'match
6341 (while (re-search-forward
6342 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6343 limit t)
6344 (if (and (not (org-in-indented-comment-line))
6345 (setq ee (org-entity-get (match-string 1)))
6346 (= (length (nth 6 ee)) 1))
6347 (let*
6348 ((end (if (equal (match-string 2) "{}")
6349 (match-end 2)
6350 (match-end 1))))
6351 (add-text-properties
6352 (match-beginning 0) end
6353 (list 'font-lock-fontified t))
6354 (compose-region (match-beginning 0) end
6355 (nth 6 ee) nil)
6356 (backward-char 1)
6357 (throw 'match t))))
6358 nil))))
6360 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6361 "Fontify string S like in Org-mode."
6362 (with-temp-buffer
6363 (insert s)
6364 (let ((org-odd-levels-only odd-levels))
6365 (org-mode)
6366 (font-lock-fontify-buffer)
6367 (buffer-string))))
6369 (defvar org-m nil)
6370 (defvar org-l nil)
6371 (defvar org-f nil)
6372 (defun org-get-level-face (n)
6373 "Get the right face for match N in font-lock matching of headlines."
6374 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6375 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6376 (if org-cycle-level-faces
6377 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6378 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6379 (cond
6380 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6381 ((eq n 2) org-f)
6382 (t (if org-level-color-stars-only nil org-f))))
6385 (defun org-get-todo-face (kwd)
6386 "Get the right face for a TODO keyword KWD.
6387 If KWD is a number, get the corresponding match group."
6388 (if (numberp kwd) (setq kwd (match-string kwd)))
6389 (or (org-face-from-face-or-color
6390 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6391 (and (member kwd org-done-keywords) 'org-done)
6392 'org-todo))
6394 (defun org-face-from-face-or-color (context inherit face-or-color)
6395 "Create a face list that inherits INHERIT, but sets the foreground color.
6396 When FACE-OR-COLOR is not a string, just return it."
6397 (if (stringp face-or-color)
6398 (list :inherit inherit
6399 (cdr (assoc context org-faces-easy-properties))
6400 face-or-color)
6401 face-or-color))
6403 (defun org-font-lock-add-tag-faces (limit)
6404 "Add the special tag faces."
6405 (when (and org-tag-faces org-tags-special-faces-re)
6406 (while (re-search-forward org-tags-special-faces-re limit t)
6407 (add-text-properties (match-beginning 1) (match-end 1)
6408 (list 'face (org-get-tag-face 1)
6409 'font-lock-fontified t))
6410 (backward-char 1))))
6412 (defun org-font-lock-add-priority-faces (limit)
6413 "Add the special priority faces."
6414 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6415 (when (save-match-data (org-at-heading-p))
6416 (add-text-properties
6417 (match-beginning 0) (match-end 0)
6418 (list 'face (or (org-face-from-face-or-color
6419 'priority 'org-priority
6420 (cdr (assoc (char-after (match-beginning 1))
6421 org-priority-faces)))
6422 'org-priority)
6423 'font-lock-fontified t)))))
6425 (defun org-get-tag-face (kwd)
6426 "Get the right face for a TODO keyword KWD.
6427 If KWD is a number, get the corresponding match group."
6428 (if (numberp kwd) (setq kwd (match-string kwd)))
6429 (or (org-face-from-face-or-color
6430 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6431 'org-tag))
6433 (defun org-unfontify-region (beg end &optional maybe_loudly)
6434 "Remove fontification and activation overlays from links."
6435 (font-lock-default-unfontify-region beg end)
6436 (let* ((buffer-undo-list t)
6437 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6438 (inhibit-modification-hooks t)
6439 deactivate-mark buffer-file-name buffer-file-truename)
6440 (org-decompose-region beg end)
6441 (remove-text-properties beg end
6442 '(mouse-face t keymap t org-linked-text t
6443 invisible t intangible t
6444 org-no-flyspell t org-emphasis t))
6445 (org-remove-font-lock-display-properties beg end)))
6447 (defconst org-script-display '(((raise -0.3) (height 0.7))
6448 ((raise 0.3) (height 0.7))
6449 ((raise -0.5))
6450 ((raise 0.5)))
6451 "Display properties for showing superscripts and subscripts.")
6453 (defun org-remove-font-lock-display-properties (beg end)
6454 "Remove specific display properties that have been added by font lock.
6455 The will remove the raise properties that are used to show superscripts
6456 and subscripts."
6457 (let (next prop)
6458 (while (< beg end)
6459 (setq next (next-single-property-change beg 'display nil end)
6460 prop (get-text-property beg 'display))
6461 (if (member prop org-script-display)
6462 (put-text-property beg next 'display nil))
6463 (setq beg next))))
6465 (defun org-raise-scripts (limit)
6466 "Add raise properties to sub/superscripts."
6467 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6468 (if (re-search-forward
6469 (if (eq org-use-sub-superscripts t)
6470 org-match-substring-regexp
6471 org-match-substring-with-braces-regexp)
6472 limit t)
6473 (let* ((pos (point)) table-p comment-p
6474 (mpos (match-beginning 3))
6475 (emph-p (get-text-property mpos 'org-emphasis))
6476 (link-p (get-text-property mpos 'mouse-face))
6477 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6478 (goto-char (point-at-bol))
6479 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6480 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6481 (goto-char pos)
6482 ;; Handle a_b^c
6483 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6484 (if (or comment-p emph-p link-p keyw-p)
6486 (put-text-property (match-beginning 3) (match-end 0)
6487 'display
6488 (if (equal (char-after (match-beginning 2)) ?^)
6489 (nth (if table-p 3 1) org-script-display)
6490 (nth (if table-p 2 0) org-script-display)))
6491 (add-text-properties (match-beginning 2) (match-end 2)
6492 (list 'invisible t
6493 'org-dwidth t 'org-dwidth-n 1))
6494 (if (and (eq (char-after (match-beginning 3)) ?{)
6495 (eq (char-before (match-end 3)) ?}))
6496 (progn
6497 (add-text-properties
6498 (match-beginning 3) (1+ (match-beginning 3))
6499 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6500 (add-text-properties
6501 (1- (match-end 3)) (match-end 3)
6502 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6503 t)))))
6505 ;;;; Visibility cycling, including org-goto and indirect buffer
6507 ;;; Cycling
6509 (defvar org-cycle-global-status nil)
6510 (make-variable-buffer-local 'org-cycle-global-status)
6511 (put 'org-cycle-global-status 'org-state t)
6512 (defvar org-cycle-subtree-status nil)
6513 (make-variable-buffer-local 'org-cycle-subtree-status)
6514 (put 'org-cycle-subtree-status 'org-state t)
6516 (defvar org-inlinetask-min-level)
6518 (defun org-unlogged-message (&rest args)
6519 "Display a message, but avoid logging it in the *Messages* buffer."
6520 (let ((message-log-max nil))
6521 (apply 'message args)))
6523 ;;;###autoload
6524 (defun org-cycle (&optional arg)
6525 "TAB-action and visibility cycling for Org-mode.
6527 This is the command invoked in Org-mode by the TAB key. Its main purpose
6528 is outline visibility cycling, but it also invokes other actions
6529 in special contexts.
6531 - When this function is called with a prefix argument, rotate the entire
6532 buffer through 3 states (global cycling)
6533 1. OVERVIEW: Show only top-level headlines.
6534 2. CONTENTS: Show all headlines of all levels, but no body text.
6535 3. SHOW ALL: Show everything.
6536 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6537 determined by the variable `org-startup-folded', and by any VISIBILITY
6538 properties in the buffer.
6539 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6540 including any drawers.
6542 - When inside a table, re-align the table and move to the next field.
6544 - When point is at the beginning of a headline, rotate the subtree started
6545 by this line through 3 different states (local cycling)
6546 1. FOLDED: Only the main headline is shown.
6547 2. CHILDREN: The main headline and the direct children are shown.
6548 From this state, you can move to one of the children
6549 and zoom in further.
6550 3. SUBTREE: Show the entire subtree, including body text.
6551 If there is no subtree, switch directly from CHILDREN to FOLDED.
6553 - When point is at the beginning of an empty headline and the variable
6554 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6555 of the headline by demoting and promoting it to likely levels. This
6556 speeds up creation document structure by pressing TAB once or several
6557 times right after creating a new headline.
6559 - When there is a numeric prefix, go up to a heading with level ARG, do
6560 a `show-subtree' and return to the previous cursor position. If ARG
6561 is negative, go up that many levels.
6563 - When point is not at the beginning of a headline, execute the global
6564 binding for TAB, which is re-indenting the line. See the option
6565 `org-cycle-emulate-tab' for details.
6567 - Special case: if point is at the beginning of the buffer and there is
6568 no headline in line 1, this function will act as if called with prefix arg
6569 (C-u TAB, same as S-TAB) also when called without prefix arg.
6570 But only if also the variable `org-cycle-global-at-bob' is t."
6571 (interactive "P")
6572 (org-load-modules-maybe)
6573 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6574 (and org-cycle-level-after-item/entry-creation
6575 (or (org-cycle-level)
6576 (org-cycle-item-indentation))))
6577 (let* ((limit-level
6578 (or org-cycle-max-level
6579 (and (boundp 'org-inlinetask-min-level)
6580 org-inlinetask-min-level
6581 (1- org-inlinetask-min-level))))
6582 (nstars (and limit-level
6583 (if org-odd-levels-only
6584 (and limit-level (1- (* limit-level 2)))
6585 limit-level)))
6586 (org-outline-regexp
6587 (if (not (derived-mode-p 'org-mode))
6588 outline-regexp
6589 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6590 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6591 (not (looking-at org-outline-regexp))))
6592 (org-cycle-hook
6593 (if bob-special
6594 (delq 'org-optimize-window-after-visibility-change
6595 (copy-sequence org-cycle-hook))
6596 org-cycle-hook))
6597 (pos (point)))
6599 (if (or bob-special (equal arg '(4)))
6600 ;; special case: use global cycling
6601 (setq arg t))
6603 (cond
6605 ((equal arg '(16))
6606 (setq last-command 'dummy)
6607 (org-set-startup-visibility)
6608 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6610 ((equal arg '(64))
6611 (show-all)
6612 (org-unlogged-message "Entire buffer visible, including drawers"))
6614 ;; Try cdlatex TAB completion
6615 ((org-try-cdlatex-tab))
6617 ;; Table: enter it or move to the next field.
6618 ((org-at-table-p 'any)
6619 (if (org-at-table.el-p)
6620 (message "Use C-c ' to edit table.el tables")
6621 (if arg (org-table-edit-field t)
6622 (org-table-justify-field-maybe)
6623 (call-interactively 'org-table-next-field))))
6625 ((run-hook-with-args-until-success
6626 'org-tab-after-check-for-table-hook))
6628 ;; Global cycling: delegate to `org-cycle-internal-global'.
6629 ((eq arg t) (org-cycle-internal-global))
6631 ;; Drawers: delegate to `org-flag-drawer'.
6632 ((and org-drawers org-drawer-regexp
6633 (save-excursion
6634 (beginning-of-line 1)
6635 (looking-at org-drawer-regexp)))
6636 (org-flag-drawer ; toggle block visibility
6637 (not (get-char-property (match-end 0) 'invisible))))
6639 ;; Show-subtree, ARG levels up from here.
6640 ((integerp arg)
6641 (save-excursion
6642 (org-back-to-heading)
6643 (outline-up-heading (if (< arg 0) (- arg)
6644 (- (funcall outline-level) arg)))
6645 (org-show-subtree)))
6647 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6648 ((and (featurep 'org-inlinetask)
6649 (org-inlinetask-at-task-p)
6650 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6651 (org-inlinetask-toggle-visibility))
6653 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6654 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6655 (save-excursion (beginning-of-line 1)
6656 (looking-at org-outline-regexp)))
6657 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6658 (org-cycle-internal-local))
6660 ;; From there: TAB emulation and template completion.
6661 (buffer-read-only (org-back-to-heading))
6663 ((run-hook-with-args-until-success
6664 'org-tab-after-check-for-cycling-hook))
6666 ((org-try-structure-completion))
6668 ((run-hook-with-args-until-success
6669 'org-tab-before-tab-emulation-hook))
6671 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6672 (or (not (bolp))
6673 (not (looking-at org-outline-regexp))))
6674 (call-interactively (global-key-binding "\t")))
6676 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6677 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6678 (or (and (eq org-cycle-emulate-tab 'white)
6679 (= (match-end 0) (point-at-eol)))
6680 (and (eq org-cycle-emulate-tab 'whitestart)
6681 (>= (match-end 0) pos))))
6683 (eq org-cycle-emulate-tab t))
6684 (call-interactively (global-key-binding "\t")))
6686 (t (save-excursion
6687 (org-back-to-heading)
6688 (org-cycle)))))))
6690 (defun org-cycle-internal-global ()
6691 "Do the global cycling action."
6692 ;; Hack to avoid display of messages for .org attachments in Gnus
6693 (let ((ga (string-match "\\*fontification" (buffer-name))))
6694 (cond
6695 ((and (eq last-command this-command)
6696 (eq org-cycle-global-status 'overview))
6697 ;; We just created the overview - now do table of contents
6698 ;; This can be slow in very large buffers, so indicate action
6699 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6700 (unless ga (org-unlogged-message "CONTENTS..."))
6701 (org-content)
6702 (unless ga (org-unlogged-message "CONTENTS...done"))
6703 (setq org-cycle-global-status 'contents)
6704 (run-hook-with-args 'org-cycle-hook 'contents))
6706 ((and (eq last-command this-command)
6707 (eq org-cycle-global-status 'contents))
6708 ;; We just showed the table of contents - now show everything
6709 (run-hook-with-args 'org-pre-cycle-hook 'all)
6710 (show-all)
6711 (unless ga (org-unlogged-message "SHOW ALL"))
6712 (setq org-cycle-global-status 'all)
6713 (run-hook-with-args 'org-cycle-hook 'all))
6716 ;; Default action: go to overview
6717 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6718 (org-overview)
6719 (unless ga (org-unlogged-message "OVERVIEW"))
6720 (setq org-cycle-global-status 'overview)
6721 (run-hook-with-args 'org-cycle-hook 'overview)))))
6723 (defvar org-called-with-limited-levels);Dyn-bound in ̀org-with-limited-levels'.
6725 (defun org-cycle-internal-local ()
6726 "Do the local cycling action."
6727 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6728 ;; First, determine end of headline (EOH), end of subtree or item
6729 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6730 (save-excursion
6731 (if (org-at-item-p)
6732 (progn
6733 (beginning-of-line)
6734 (setq struct (org-list-struct))
6735 (setq eoh (point-at-eol))
6736 (setq eos (org-list-get-item-end-before-blank (point) struct))
6737 (setq has-children (org-list-has-child-p (point) struct)))
6738 (org-back-to-heading)
6739 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6740 (setq eos (save-excursion (org-end-of-subtree t t)
6741 (when (bolp) (backward-char)) (point)))
6742 (setq has-children
6743 (or (save-excursion
6744 (let ((level (funcall outline-level)))
6745 (outline-next-heading)
6746 (and (org-at-heading-p t)
6747 (> (funcall outline-level) level))))
6748 (save-excursion
6749 (org-list-search-forward (org-item-beginning-re) eos t)))))
6750 ;; Determine end invisible part of buffer (EOL)
6751 (beginning-of-line 2)
6752 ;; XEmacs doesn't have `next-single-char-property-change'
6753 (if (featurep 'xemacs)
6754 (while (and (not (eobp)) ;; this is like `next-line'
6755 (get-char-property (1- (point)) 'invisible))
6756 (beginning-of-line 2))
6757 (while (and (not (eobp)) ;; this is like `next-line'
6758 (get-char-property (1- (point)) 'invisible))
6759 (goto-char (next-single-char-property-change (point) 'invisible))
6760 (and (eolp) (beginning-of-line 2))))
6761 (setq eol (point)))
6762 ;; Find out what to do next and set `this-command'
6763 (cond
6764 ((= eos eoh)
6765 ;; Nothing is hidden behind this heading
6766 (unless (org-before-first-heading-p)
6767 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6768 (org-unlogged-message "EMPTY ENTRY")
6769 (setq org-cycle-subtree-status nil)
6770 (save-excursion
6771 (goto-char eos)
6772 (outline-next-heading)
6773 (if (outline-invisible-p) (org-flag-heading nil))))
6774 ((and (or (>= eol eos)
6775 (not (string-match "\\S-" (buffer-substring eol eos))))
6776 (or has-children
6777 (not (setq children-skipped
6778 org-cycle-skip-children-state-if-no-children))))
6779 ;; Entire subtree is hidden in one line: children view
6780 (unless (org-before-first-heading-p)
6781 (run-hook-with-args 'org-pre-cycle-hook 'children))
6782 (if (org-at-item-p)
6783 (org-list-set-item-visibility (point-at-bol) struct 'children)
6784 (org-show-entry)
6785 (org-with-limited-levels (show-children))
6786 ;; FIXME: This slows down the func way too much.
6787 ;; How keep drawers hidden in subtree anyway?
6788 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6789 ;; (org-cycle-hide-drawers 'subtree))
6791 ;; Fold every list in subtree to top-level items.
6792 (when (eq org-cycle-include-plain-lists 'integrate)
6793 (save-excursion
6794 (org-back-to-heading)
6795 (while (org-list-search-forward (org-item-beginning-re) eos t)
6796 (beginning-of-line 1)
6797 (let* ((struct (org-list-struct))
6798 (prevs (org-list-prevs-alist struct))
6799 (end (org-list-get-bottom-point struct)))
6800 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6801 (org-list-get-all-items (point) struct prevs))
6802 (goto-char (if (< end eos) end eos)))))))
6803 (org-unlogged-message "CHILDREN")
6804 (save-excursion
6805 (goto-char eos)
6806 (outline-next-heading)
6807 (if (outline-invisible-p) (org-flag-heading nil)))
6808 (setq org-cycle-subtree-status 'children)
6809 (unless (org-before-first-heading-p)
6810 (run-hook-with-args 'org-cycle-hook 'children)))
6811 ((or children-skipped
6812 (and (eq last-command this-command)
6813 (eq org-cycle-subtree-status 'children)))
6814 ;; We just showed the children, or no children are there,
6815 ;; now show everything.
6816 (unless (org-before-first-heading-p)
6817 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6818 (outline-flag-region eoh eos nil)
6819 (org-unlogged-message
6820 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6821 (setq org-cycle-subtree-status 'subtree)
6822 (unless (org-before-first-heading-p)
6823 (run-hook-with-args 'org-cycle-hook 'subtree)))
6825 ;; Default action: hide the subtree.
6826 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6827 (outline-flag-region eoh eos t)
6828 (org-unlogged-message "FOLDED")
6829 (setq org-cycle-subtree-status 'folded)
6830 (unless (org-before-first-heading-p)
6831 (run-hook-with-args 'org-cycle-hook 'folded))))))
6833 ;;;###autoload
6834 (defun org-global-cycle (&optional arg)
6835 "Cycle the global visibility. For details see `org-cycle'.
6836 With \\[universal-argument] prefix arg, switch to startup visibility.
6837 With a numeric prefix, show all headlines up to that level."
6838 (interactive "P")
6839 (let ((org-cycle-include-plain-lists
6840 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6841 (cond
6842 ((integerp arg)
6843 (show-all)
6844 (hide-sublevels arg)
6845 (setq org-cycle-global-status 'contents))
6846 ((equal arg '(4))
6847 (org-set-startup-visibility)
6848 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6850 (org-cycle '(4))))))
6852 (defun org-set-startup-visibility ()
6853 "Set the visibility required by startup options and properties."
6854 (cond
6855 ((eq org-startup-folded t)
6856 (org-overview))
6857 ((eq org-startup-folded 'content)
6858 (org-content))
6859 ((or (eq org-startup-folded 'showeverything)
6860 (eq org-startup-folded nil))
6861 (show-all)))
6862 (unless (eq org-startup-folded 'showeverything)
6863 (if org-hide-block-startup (org-hide-block-all))
6864 (org-set-visibility-according-to-property 'no-cleanup)
6865 (org-cycle-hide-archived-subtrees 'all)
6866 (org-cycle-hide-drawers 'all)
6867 (org-cycle-show-empty-lines t)))
6869 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6870 "Switch subtree visibilities according to :VISIBILITY: property."
6871 (interactive)
6872 (let (org-show-entry-below state)
6873 (save-excursion
6874 (goto-char (point-min))
6875 (while (re-search-forward
6876 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6877 nil t)
6878 (setq state (match-string 1))
6879 (save-excursion
6880 (org-back-to-heading t)
6881 (hide-subtree)
6882 (org-reveal)
6883 (cond
6884 ((equal state '("fold" "folded"))
6885 (hide-subtree))
6886 ((equal state "children")
6887 (org-show-hidden-entry)
6888 (show-children))
6889 ((equal state "content")
6890 (save-excursion
6891 (save-restriction
6892 (org-narrow-to-subtree)
6893 (org-content))))
6894 ((member state '("all" "showall"))
6895 (show-subtree)))))
6896 (unless no-cleanup
6897 (org-cycle-hide-archived-subtrees 'all)
6898 (org-cycle-hide-drawers 'all)
6899 (org-cycle-show-empty-lines 'all)))))
6901 ;; This function uses outline-regexp instead of the more fundamental
6902 ;; org-outline-regexp so that org-cycle-global works outside of Org
6903 ;; buffers, where outline-regexp is needed.
6904 (defun org-overview ()
6905 "Switch to overview mode, showing only top-level headlines.
6906 This shows all headlines with a level equal or greater than the level
6907 of the first headline in the buffer. This is important, because if the
6908 first headline is not level one, then (hide-sublevels 1) gives confusing
6909 results."
6910 (interactive)
6911 (save-excursion
6912 (let ((level
6913 (save-excursion
6914 (goto-char (point-min))
6915 (if (re-search-forward (concat "^" outline-regexp) nil t)
6916 (progn
6917 (goto-char (match-beginning 0))
6918 (funcall outline-level))))))
6919 (and level (hide-sublevels level)))))
6921 (defun org-content (&optional arg)
6922 "Show all headlines in the buffer, like a table of contents.
6923 With numerical argument N, show content up to level N."
6924 (interactive "P")
6925 (org-overview)
6926 (save-excursion
6927 ;; Visit all headings and show their offspring
6928 (and (integerp arg) (org-overview))
6929 (goto-char (point-max))
6930 (catch 'exit
6931 (while (and (progn (condition-case nil
6932 (outline-previous-visible-heading 1)
6933 (error (goto-char (point-min))))
6935 (looking-at org-outline-regexp))
6936 (if (integerp arg)
6937 (show-children (1- arg))
6938 (show-branches))
6939 (if (bobp) (throw 'exit nil))))))
6941 (defun org-optimize-window-after-visibility-change (state)
6942 "Adjust the window after a change in outline visibility.
6943 This function is the default value of the hook `org-cycle-hook'."
6944 (when (get-buffer-window (current-buffer))
6945 (cond
6946 ((eq state 'content) nil)
6947 ((eq state 'all) nil)
6948 ((eq state 'folded) nil)
6949 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6950 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6952 (defun org-remove-empty-overlays-at (pos)
6953 "Remove outline overlays that do not contain non-white stuff."
6954 (mapc
6955 (lambda (o)
6956 (and (eq 'outline (overlay-get o 'invisible))
6957 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6958 (overlay-end o))))
6959 (delete-overlay o)))
6960 (overlays-at pos)))
6962 (defun org-clean-visibility-after-subtree-move ()
6963 "Fix visibility issues after moving a subtree."
6964 ;; First, find a reasonable region to look at:
6965 ;; Start two siblings above, end three below
6966 (let* ((beg (save-excursion
6967 (and (org-get-last-sibling)
6968 (org-get-last-sibling))
6969 (point)))
6970 (end (save-excursion
6971 (and (org-get-next-sibling)
6972 (org-get-next-sibling)
6973 (org-get-next-sibling))
6974 (if (org-at-heading-p)
6975 (point-at-eol)
6976 (point))))
6977 (level (looking-at "\\*+"))
6978 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6979 (save-excursion
6980 (save-restriction
6981 (narrow-to-region beg end)
6982 (when re
6983 ;; Properly fold already folded siblings
6984 (goto-char (point-min))
6985 (while (re-search-forward re nil t)
6986 (if (and (not (outline-invisible-p))
6987 (save-excursion
6988 (goto-char (point-at-eol)) (outline-invisible-p)))
6989 (hide-entry))))
6990 (org-cycle-show-empty-lines 'overview)
6991 (org-cycle-hide-drawers 'overview)))))
6993 (defun org-cycle-show-empty-lines (state)
6994 "Show empty lines above all visible headlines.
6995 The region to be covered depends on STATE when called through
6996 `org-cycle-hook'. Lisp program can use t for STATE to get the
6997 entire buffer covered. Note that an empty line is only shown if there
6998 are at least `org-cycle-separator-lines' empty lines before the headline."
6999 (when (not (= org-cycle-separator-lines 0))
7000 (save-excursion
7001 (let* ((n (abs org-cycle-separator-lines))
7002 (re (cond
7003 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7004 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7005 (t (let ((ns (number-to-string (- n 2))))
7006 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7007 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7008 beg end b e)
7009 (cond
7010 ((memq state '(overview contents t))
7011 (setq beg (point-min) end (point-max)))
7012 ((memq state '(children folded))
7013 (setq beg (point) end (progn (org-end-of-subtree t t)
7014 (beginning-of-line 2)
7015 (point)))))
7016 (when beg
7017 (goto-char beg)
7018 (while (re-search-forward re end t)
7019 (unless (get-char-property (match-end 1) 'invisible)
7020 (setq e (match-end 1))
7021 (if (< org-cycle-separator-lines 0)
7022 (setq b (save-excursion
7023 (goto-char (match-beginning 0))
7024 (org-back-over-empty-lines)
7025 (if (save-excursion
7026 (goto-char (max (point-min) (1- (point))))
7027 (org-at-heading-p))
7028 (1- (point))
7029 (point))))
7030 (setq b (match-beginning 1)))
7031 (outline-flag-region b e nil)))))))
7032 ;; Never hide empty lines at the end of the file.
7033 (save-excursion
7034 (goto-char (point-max))
7035 (outline-previous-heading)
7036 (outline-end-of-heading)
7037 (if (and (looking-at "[ \t\n]+")
7038 (= (match-end 0) (point-max)))
7039 (outline-flag-region (point) (match-end 0) nil))))
7041 (defun org-show-empty-lines-in-parent ()
7042 "Move to the parent and re-show empty lines before visible headlines."
7043 (save-excursion
7044 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7045 (org-cycle-show-empty-lines context))))
7047 (defun org-files-list ()
7048 "Return `org-agenda-files' list, plus all open org-mode files.
7049 This is useful for operations that need to scan all of a user's
7050 open and agenda-wise Org files."
7051 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7052 (dolist (buf (buffer-list))
7053 (with-current-buffer buf
7054 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7055 (let ((file (expand-file-name (buffer-file-name))))
7056 (unless (member file files)
7057 (push file files))))))
7058 files))
7060 (defsubst org-entry-beginning-position ()
7061 "Return the beginning position of the current entry."
7062 (save-excursion (outline-back-to-heading t) (point)))
7064 (defsubst org-entry-end-position ()
7065 "Return the end position of the current entry."
7066 (save-excursion (outline-next-heading) (point)))
7068 (defun org-cycle-hide-drawers (state)
7069 "Re-hide all drawers after a visibility state change."
7070 (when (and (derived-mode-p 'org-mode)
7071 (not (memq state '(overview folded contents))))
7072 (save-excursion
7073 (let* ((globalp (memq state '(contents all)))
7074 (beg (if globalp (point-min) (point)))
7075 (end (if globalp (point-max)
7076 (if (eq state 'children)
7077 (save-excursion (outline-next-heading) (point))
7078 (org-end-of-subtree t)))))
7079 (goto-char beg)
7080 (while (re-search-forward org-drawer-regexp end t)
7081 (org-flag-drawer t))))))
7083 (defun org-cycle-hide-inline-tasks (state)
7084 "Re-hide inline tasks when switching to 'contents or 'children
7085 visibility state."
7086 (case state
7087 (contents
7088 (when (org-bound-and-true-p org-inlinetask-min-level)
7089 (hide-sublevels (1- org-inlinetask-min-level))))
7090 (children
7091 (when (featurep 'org-inlinetask)
7092 (save-excursion
7093 (while (and (outline-next-heading)
7094 (org-inlinetask-at-task-p))
7095 (org-inlinetask-toggle-visibility)
7096 (org-inlinetask-goto-end)))))))
7098 (defun org-flag-drawer (flag)
7099 "When FLAG is non-nil, hide the drawer we are within.
7100 Otherwise make it visible."
7101 (save-excursion
7102 (beginning-of-line 1)
7103 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
7104 (let ((b (match-end 0)))
7105 (if (re-search-forward
7106 "^[ \t]*:END:"
7107 (save-excursion (outline-next-heading) (point)) t)
7108 (outline-flag-region b (point-at-eol) flag)
7109 (user-error ":END: line missing at position %s" b))))))
7111 (defun org-subtree-end-visible-p ()
7112 "Is the end of the current subtree visible?"
7113 (pos-visible-in-window-p
7114 (save-excursion (org-end-of-subtree t) (point))))
7116 (defun org-first-headline-recenter ()
7117 "Move cursor to the first headline and recenter the headline."
7118 (goto-char (point-min))
7119 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7120 (set-window-start (selected-window) (point-at-bol))))
7122 ;;; Saving and restoring visibility
7124 (defun org-outline-overlay-data (&optional use-markers)
7125 "Return a list of the locations of all outline overlays.
7126 These are overlays with the `invisible' property value `outline'.
7127 The return value is a list of cons cells, with start and stop
7128 positions for each overlay.
7129 If USE-MARKERS is set, return the positions as markers."
7130 (let (beg end)
7131 (save-excursion
7132 (save-restriction
7133 (widen)
7134 (delq nil
7135 (mapcar (lambda (o)
7136 (when (eq (overlay-get o 'invisible) 'outline)
7137 (setq beg (overlay-start o)
7138 end (overlay-end o))
7139 (and beg end (> end beg)
7140 (if use-markers
7141 (cons (move-marker (make-marker) beg)
7142 (move-marker (make-marker) end))
7143 (cons beg end)))))
7144 (overlays-in (point-min) (point-max))))))))
7146 (defun org-set-outline-overlay-data (data)
7147 "Create visibility overlays for all positions in DATA.
7148 DATA should have been made by `org-outline-overlay-data'."
7149 (let (o)
7150 (save-excursion
7151 (save-restriction
7152 (widen)
7153 (show-all)
7154 (mapc (lambda (c)
7155 (outline-flag-region (car c) (cdr c) t))
7156 data)))))
7158 ;;; Folding of blocks
7160 (defvar org-hide-block-overlays nil
7161 "Overlays hiding blocks.")
7162 (make-variable-buffer-local 'org-hide-block-overlays)
7164 (defun org-block-map (function &optional start end)
7165 "Call FUNCTION at the head of all source blocks in the current buffer.
7166 Optional arguments START and END can be used to limit the range."
7167 (let ((start (or start (point-min)))
7168 (end (or end (point-max))))
7169 (save-excursion
7170 (goto-char start)
7171 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7172 (save-excursion
7173 (save-match-data
7174 (goto-char (match-beginning 0))
7175 (funcall function)))))))
7177 (defun org-hide-block-toggle-all ()
7178 "Toggle the visibility of all blocks in the current buffer."
7179 (org-block-map #'org-hide-block-toggle))
7181 (defun org-hide-block-all ()
7182 "Fold all blocks in the current buffer."
7183 (interactive)
7184 (org-show-block-all)
7185 (org-block-map #'org-hide-block-toggle-maybe))
7187 (defun org-show-block-all ()
7188 "Unfold all blocks in the current buffer."
7189 (interactive)
7190 (mapc 'delete-overlay org-hide-block-overlays)
7191 (setq org-hide-block-overlays nil))
7193 (defun org-hide-block-toggle-maybe ()
7194 "Toggle visibility of block at point."
7195 (interactive)
7196 (let ((case-fold-search t))
7197 (if (save-excursion
7198 (beginning-of-line 1)
7199 (looking-at org-block-regexp))
7200 (progn (org-hide-block-toggle)
7201 t) ;; to signal that we took action
7202 nil))) ;; to signal that we did not
7204 (defun org-hide-block-toggle (&optional force)
7205 "Toggle the visibility of the current block."
7206 (interactive)
7207 (save-excursion
7208 (beginning-of-line)
7209 (if (re-search-forward org-block-regexp nil t)
7210 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7211 (end (match-end 0)) ;; end of entire body
7213 (if (memq t (mapcar (lambda (overlay)
7214 (eq (overlay-get overlay 'invisible)
7215 'org-hide-block))
7216 (overlays-at start)))
7217 (if (or (not force) (eq force 'off))
7218 (mapc (lambda (ov)
7219 (when (member ov org-hide-block-overlays)
7220 (setq org-hide-block-overlays
7221 (delq ov org-hide-block-overlays)))
7222 (when (eq (overlay-get ov 'invisible)
7223 'org-hide-block)
7224 (delete-overlay ov)))
7225 (overlays-at start)))
7226 (setq ov (make-overlay start end))
7227 (overlay-put ov 'invisible 'org-hide-block)
7228 ;; make the block accessible to isearch
7229 (overlay-put
7230 ov 'isearch-open-invisible
7231 (lambda (ov)
7232 (when (member ov org-hide-block-overlays)
7233 (setq org-hide-block-overlays
7234 (delq ov org-hide-block-overlays)))
7235 (when (eq (overlay-get ov 'invisible)
7236 'org-hide-block)
7237 (delete-overlay ov))))
7238 (push ov org-hide-block-overlays)))
7239 (user-error "Not looking at a source block"))))
7241 ;; org-tab-after-check-for-cycling-hook
7242 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7243 ;; Remove overlays when changing major mode
7244 (add-hook 'org-mode-hook
7245 (lambda () (org-add-hook 'change-major-mode-hook
7246 'org-show-block-all 'append 'local)))
7248 ;;; Org-goto
7250 (defvar org-goto-window-configuration nil)
7251 (defvar org-goto-marker nil)
7252 (defvar org-goto-map)
7253 (defun org-goto-map ()
7254 "Set the keymap `org-goto'."
7255 (setq org-goto-map
7256 (let ((map (make-sparse-keymap)))
7257 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7258 mouse-drag-region universal-argument org-occur))
7259 cmd)
7260 (while (setq cmd (pop cmds))
7261 (substitute-key-definition cmd cmd map global-map)))
7262 (suppress-keymap map)
7263 (org-defkey map "\C-m" 'org-goto-ret)
7264 (org-defkey map [(return)] 'org-goto-ret)
7265 (org-defkey map [(left)] 'org-goto-left)
7266 (org-defkey map [(right)] 'org-goto-right)
7267 (org-defkey map [(control ?g)] 'org-goto-quit)
7268 (org-defkey map "\C-i" 'org-cycle)
7269 (org-defkey map [(tab)] 'org-cycle)
7270 (org-defkey map [(down)] 'outline-next-visible-heading)
7271 (org-defkey map [(up)] 'outline-previous-visible-heading)
7272 (if org-goto-auto-isearch
7273 (if (fboundp 'define-key-after)
7274 (define-key-after map [t] 'org-goto-local-auto-isearch)
7275 nil)
7276 (org-defkey map "q" 'org-goto-quit)
7277 (org-defkey map "n" 'outline-next-visible-heading)
7278 (org-defkey map "p" 'outline-previous-visible-heading)
7279 (org-defkey map "f" 'outline-forward-same-level)
7280 (org-defkey map "b" 'outline-backward-same-level)
7281 (org-defkey map "u" 'outline-up-heading))
7282 (org-defkey map "/" 'org-occur)
7283 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7284 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7285 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7286 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7287 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7288 map)))
7290 (defconst org-goto-help
7291 "Browse buffer copy, to find location or copy text.%s
7292 RET=jump to location C-g=quit and return to previous location
7293 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7295 (defvar org-goto-start-pos) ; dynamically scoped parameter
7297 (defun org-goto (&optional alternative-interface)
7298 "Look up a different location in the current file, keeping current visibility.
7300 When you want look-up or go to a different location in a
7301 document, the fastest way is often to fold the entire buffer and
7302 then dive into the tree. This method has the disadvantage, that
7303 the previous location will be folded, which may not be what you
7304 want.
7306 This command works around this by showing a copy of the current
7307 buffer in an indirect buffer, in overview mode. You can dive
7308 into the tree in that copy, use org-occur and incremental search
7309 to find a location. When pressing RET or `Q', the command
7310 returns to the original buffer in which the visibility is still
7311 unchanged. After RET it will also jump to the location selected
7312 in the indirect buffer and expose the headline hierarchy above.
7314 With a prefix argument, use the alternative interface: e.g. if
7315 `org-goto-interface' is 'outline use 'outline-path-completion."
7316 (interactive "P")
7317 (org-goto-map)
7318 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7319 (org-refile-use-outline-path t)
7320 (org-refile-target-verify-function nil)
7321 (interface
7322 (if (not alternative-interface)
7323 org-goto-interface
7324 (if (eq org-goto-interface 'outline)
7325 'outline-path-completion
7326 'outline)))
7327 (org-goto-start-pos (point))
7328 (selected-point
7329 (if (eq interface 'outline)
7330 (car (org-get-location (current-buffer) org-goto-help))
7331 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7332 (org-refile-check-position pa)
7333 (nth 3 pa)))))
7334 (if selected-point
7335 (progn
7336 (org-mark-ring-push org-goto-start-pos)
7337 (goto-char selected-point)
7338 (if (or (outline-invisible-p) (org-invisible-p2))
7339 (org-show-context 'org-goto)))
7340 (message "Quit"))))
7342 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7343 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7344 (defvar org-goto-local-auto-isearch-map) ; defined below
7346 (defun org-get-location (buf help)
7347 "Let the user select a location in the Org-mode buffer BUF.
7348 This function uses a recursive edit. It returns the selected position
7349 or nil."
7350 (org-no-popups
7351 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7352 (isearch-hide-immediately nil)
7353 (isearch-search-fun-function
7354 (lambda () 'org-goto-local-search-headings))
7355 (org-goto-selected-point org-goto-exit-command))
7356 (save-excursion
7357 (save-window-excursion
7358 (delete-other-windows)
7359 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7360 (org-pop-to-buffer-same-window
7361 (condition-case nil
7362 (make-indirect-buffer (current-buffer) "*org-goto*")
7363 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7364 (with-output-to-temp-buffer "*Org Help*"
7365 (princ (format help (if org-goto-auto-isearch
7366 " Just type for auto-isearch."
7367 " n/p/f/b/u to navigate, q to quit."))))
7368 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7369 (setq buffer-read-only nil)
7370 (let ((org-startup-truncated t)
7371 (org-startup-folded nil)
7372 (org-startup-align-all-tables nil))
7373 (org-mode)
7374 (org-overview))
7375 (setq buffer-read-only t)
7376 (if (and (boundp 'org-goto-start-pos)
7377 (integer-or-marker-p org-goto-start-pos))
7378 (let ((org-show-hierarchy-above t)
7379 (org-show-siblings t)
7380 (org-show-following-heading t))
7381 (goto-char org-goto-start-pos)
7382 (and (outline-invisible-p) (org-show-context)))
7383 (goto-char (point-min)))
7384 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7385 (message "Select location and press RET")
7386 (use-local-map org-goto-map)
7387 (recursive-edit)))
7388 (kill-buffer "*org-goto*")
7389 (cons org-goto-selected-point org-goto-exit-command))))
7391 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7392 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7393 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7394 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7396 (defun org-goto-local-search-headings (string bound noerror)
7397 "Search and make sure that any matches are in headlines."
7398 (catch 'return
7399 (while (if isearch-forward
7400 (search-forward string bound noerror)
7401 (search-backward string bound noerror))
7402 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7403 (and (member :headline context)
7404 (not (member :tags context))))
7405 (throw 'return (point))))))
7407 (defun org-goto-local-auto-isearch ()
7408 "Start isearch."
7409 (interactive)
7410 (goto-char (point-min))
7411 (let ((keys (this-command-keys)))
7412 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7413 (isearch-mode t)
7414 (isearch-process-search-char (string-to-char keys)))))
7416 (defun org-goto-ret (&optional arg)
7417 "Finish `org-goto' by going to the new location."
7418 (interactive "P")
7419 (setq org-goto-selected-point (point)
7420 org-goto-exit-command 'return)
7421 (throw 'exit nil))
7423 (defun org-goto-left ()
7424 "Finish `org-goto' by going to the new location."
7425 (interactive)
7426 (if (org-at-heading-p)
7427 (progn
7428 (beginning-of-line 1)
7429 (setq org-goto-selected-point (point)
7430 org-goto-exit-command 'left)
7431 (throw 'exit nil))
7432 (user-error "Not on a heading")))
7434 (defun org-goto-right ()
7435 "Finish `org-goto' by going to the new location."
7436 (interactive)
7437 (if (org-at-heading-p)
7438 (progn
7439 (setq org-goto-selected-point (point)
7440 org-goto-exit-command 'right)
7441 (throw 'exit nil))
7442 (user-error "Not on a heading")))
7444 (defun org-goto-quit ()
7445 "Finish `org-goto' without cursor motion."
7446 (interactive)
7447 (setq org-goto-selected-point nil)
7448 (setq org-goto-exit-command 'quit)
7449 (throw 'exit nil))
7451 ;;; Indirect buffer display of subtrees
7453 (defvar org-indirect-dedicated-frame nil
7454 "This is the frame being used for indirect tree display.")
7455 (defvar org-last-indirect-buffer nil)
7457 (defun org-tree-to-indirect-buffer (&optional arg)
7458 "Create indirect buffer and narrow it to current subtree.
7459 With a numerical prefix ARG, go up to this level and then take that tree.
7460 If ARG is negative, go up that many levels.
7462 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7463 indirect buffer previously made with this command, to avoid proliferation of
7464 indirect buffers. However, when you call the command with a \
7465 \\[universal-argument] prefix, or
7466 when `org-indirect-buffer-display' is `new-frame', the last buffer
7467 is kept so that you can work with several indirect buffers at the same time.
7468 If `org-indirect-buffer-display' is `dedicated-frame', the \
7469 \\[universal-argument] prefix also
7470 requests that a new frame be made for the new buffer, so that the dedicated
7471 frame is not changed."
7472 (interactive "P")
7473 (let ((cbuf (current-buffer))
7474 (cwin (selected-window))
7475 (pos (point))
7476 beg end level heading ibuf)
7477 (save-excursion
7478 (org-back-to-heading t)
7479 (when (numberp arg)
7480 (setq level (org-outline-level))
7481 (if (< arg 0) (setq arg (+ level arg)))
7482 (while (> (setq level (org-outline-level)) arg)
7483 (org-up-heading-safe)))
7484 (setq beg (point)
7485 heading (org-get-heading))
7486 (org-end-of-subtree t t)
7487 (if (org-at-heading-p) (backward-char 1))
7488 (setq end (point)))
7489 (if (and (buffer-live-p org-last-indirect-buffer)
7490 (not (eq org-indirect-buffer-display 'new-frame))
7491 (not arg))
7492 (kill-buffer org-last-indirect-buffer))
7493 (setq ibuf (org-get-indirect-buffer cbuf)
7494 org-last-indirect-buffer ibuf)
7495 (cond
7496 ((or (eq org-indirect-buffer-display 'new-frame)
7497 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7498 (select-frame (make-frame))
7499 (delete-other-windows)
7500 (org-pop-to-buffer-same-window ibuf)
7501 (org-set-frame-title heading))
7502 ((eq org-indirect-buffer-display 'dedicated-frame)
7503 (raise-frame
7504 (select-frame (or (and org-indirect-dedicated-frame
7505 (frame-live-p org-indirect-dedicated-frame)
7506 org-indirect-dedicated-frame)
7507 (setq org-indirect-dedicated-frame (make-frame)))))
7508 (delete-other-windows)
7509 (org-pop-to-buffer-same-window ibuf)
7510 (org-set-frame-title (concat "Indirect: " heading)))
7511 ((eq org-indirect-buffer-display 'current-window)
7512 (org-pop-to-buffer-same-window ibuf))
7513 ((eq org-indirect-buffer-display 'other-window)
7514 (pop-to-buffer ibuf))
7515 (t (error "Invalid value")))
7516 (if (featurep 'xemacs)
7517 (save-excursion (org-mode) (turn-on-font-lock)))
7518 (narrow-to-region beg end)
7519 (show-all)
7520 (goto-char pos)
7521 (run-hook-with-args 'org-cycle-hook 'all)
7522 (and (window-live-p cwin) (select-window cwin))))
7524 (defun org-get-indirect-buffer (&optional buffer)
7525 (setq buffer (or buffer (current-buffer)))
7526 (let ((n 1) (base (buffer-name buffer)) bname)
7527 (while (buffer-live-p
7528 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7529 (setq n (1+ n)))
7530 (condition-case nil
7531 (make-indirect-buffer buffer bname 'clone)
7532 (error (make-indirect-buffer buffer bname)))))
7534 (defun org-set-frame-title (title)
7535 "Set the title of the current frame to the string TITLE."
7536 ;; FIXME: how to name a single frame in XEmacs???
7537 (unless (featurep 'xemacs)
7538 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7540 ;;;; Structure editing
7542 ;;; Inserting headlines
7544 (defun org-previous-line-empty-p (&optional next)
7545 "Is the previous line a blank line?
7546 When NEXT is non-nil, check the next line instead."
7547 (save-excursion
7548 (and (not (bobp))
7549 (or (beginning-of-line (if next 2 0)) t)
7550 (save-match-data
7551 (looking-at "[ \t]*$")))))
7553 (defun org-insert-heading (&optional arg invisible-ok)
7554 "Insert a new heading or an item with the same depth at point.
7556 If point is at the beginning of a heading or a list item, insert
7557 a new heading or a new item above the current one. If point is
7558 at the beginning of a normal line, turn the line into a heading.
7560 If point is in the middle of a headline or a list item, split the
7561 headline or the item and create a new headline/item with the text
7562 in the current line after point \(see `org-M-RET-may-split-line'
7563 on how to modify this behavior).
7565 With one universal prefirx argument, set the user option
7566 `org-insert-heading-respect-content' to t for the duration of
7567 the command. This modifies the behavior described above in this
7568 ways: on list items and at the beginning of normal lines, force
7569 the insertion of a heading after the current subtree.
7571 With two universal prefix arguments, insert the heading at the
7572 end of the grandparent subtree. For example, if point is within
7573 a 2nd-level heading, then it will insert a 2nd-level heading at
7574 the end of the 1st-level parent heading.
7576 When INVISIBLE-OK is set, stop at invisible headlines when going
7577 back. This is important for non-interactive uses of the
7578 command."
7579 (interactive "P")
7580 (if (org-called-interactively-p 'any) (org-reveal))
7581 (let ((itemp (org-in-item-p))
7582 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7583 (respect-content (or org-insert-heading-respect-content
7584 (equal arg '(4))))
7585 (initial-content "")
7586 (adjust-empty-lines t))
7588 (cond
7590 ((or (= (buffer-size) 0)
7591 (and (not (save-excursion
7592 (and (ignore-errors (org-back-to-heading invisible-ok))
7593 (org-at-heading-p))))
7594 (or arg (not itemp))))
7595 ;; At beginning of buffer or so high up that only a heading
7596 ;; makes sense.
7597 (cond ((and (bolp) (not respect-content)) (insert "* "))
7598 ((not respect-content)
7599 (unless may-split (end-of-line))
7600 (insert "\n* "))
7601 ((re-search-forward org-outline-regexp-bol nil t)
7602 (beginning-of-line)
7603 (insert "* \n")
7604 (backward-char))
7605 (t (goto-char (point-max))
7606 (insert "\n* ")))
7607 (run-hooks 'org-insert-heading-hook))
7609 ((and itemp (not (member arg '((4) (16)))))
7610 ;; Insert an item
7611 (org-insert-item))
7614 ;; Maybe move at the end of the subtree
7615 (when (equal arg '(16))
7616 (org-up-heading-safe)
7617 (org-end-of-subtree t))
7618 ;; Insert a heading
7619 (save-restriction
7620 (widen)
7621 (let* ((level nil)
7622 (on-heading (org-at-heading-p))
7623 (empty-line-p (if on-heading
7624 (org-previous-line-empty-p)
7625 ;; We will decide later
7626 nil))
7627 ;; Get a level string to fall back on
7628 (fix-level
7629 (if (org-before-first-heading-p) "*"
7630 (save-excursion
7631 (org-back-to-heading t)
7632 (if (org-previous-line-empty-p) (setq empty-line-p t))
7633 (looking-at org-outline-regexp)
7634 (make-string (1- (length (match-string 0))) ?*))))
7635 (stars
7636 (save-excursion
7637 (condition-case nil
7638 (progn
7639 (org-back-to-heading invisible-ok)
7640 (when (and (not on-heading)
7641 (featurep 'org-inlinetask)
7642 (integerp org-inlinetask-min-level)
7643 (>= (length (match-string 0))
7644 org-inlinetask-min-level))
7645 ;; Find a heading level before the inline task
7646 (while (and (setq level (org-up-heading-safe))
7647 (>= level org-inlinetask-min-level)))
7648 (if (org-at-heading-p)
7649 (org-back-to-heading invisible-ok)
7650 (error "This should not happen")))
7651 (unless (and (save-excursion
7652 (save-match-data
7653 (org-backward-heading-same-level
7654 1 invisible-ok))
7655 (= (point) (match-beginning 0)))
7656 (not (org-previous-line-empty-p t)))
7657 (setq empty-line-p (or empty-line-p
7658 (org-previous-line-empty-p))))
7659 (match-string 0))
7660 (error (or fix-level "* ")))))
7661 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7662 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7663 pos hide-previous previous-pos)
7665 ;; If we insert after content, move there and clean up whitespace
7666 (when (and respect-content
7667 (not (org-looking-at-p org-outline-regexp-bol)))
7668 (if (not (org-before-first-heading-p))
7669 (org-end-of-subtree nil t)
7670 (re-search-forward org-outline-regexp-bol)
7671 (beginning-of-line 0))
7672 (skip-chars-backward " \r\n")
7673 (and (not (looking-back "^\*+"))
7674 (looking-at "[ \t]+") (replace-match ""))
7675 (unless (eobp) (forward-char 1))
7676 (when (looking-at "^\\*")
7677 (unless (bobp) (backward-char 1))
7678 (insert "\n")))
7680 ;; If we are splitting, grab the text that should be moved to the new headline
7681 (when may-split
7682 (if (org-on-heading-p)
7683 ;; This is a heading, we split intelligently (keeping tags)
7684 (let ((pos (point)))
7685 (goto-char (point-at-bol))
7686 (unless (looking-at org-complex-heading-regexp)
7687 (error "This should not happen"))
7688 (when (and (match-beginning 4)
7689 (> pos (match-beginning 4))
7690 (< pos (match-end 4)))
7691 (setq initial-content (buffer-substring pos (match-end 4)))
7692 (goto-char pos)
7693 (delete-region (point) (match-end 4))
7694 (if (looking-at "[ \t]*$")
7695 (replace-match "")
7696 (insert (make-string (length initial-content) ?\ )))
7697 (setq initial-content (org-trim initial-content)))
7698 (goto-char pos))
7699 ;; a normal line
7700 (setq initial-content
7701 (org-trim (buffer-substring (point) (point-at-eol))))
7702 (delete-region (point) (point-at-eol))))
7704 ;; If we are at the beginning of the line, insert before it. Else after
7705 (cond
7706 ((and (bolp) (looking-at "[ \t]*$")))
7707 ((and (bolp) (not (looking-at "[ \t]*$")))
7708 (open-line 1))
7710 (goto-char (point-at-eol))
7711 (insert "\n")))
7713 ;; Insert the new heading
7714 (insert stars)
7715 (just-one-space)
7716 (insert initial-content)
7717 (when adjust-empty-lines
7718 (if (or (not blank)
7719 (and blank (not (org-previous-line-empty-p))))
7720 (org-N-empty-lines-before-current (if blank 1 0))))
7721 (run-hooks 'org-insert-heading-hook)))))))
7723 (defun org-N-empty-lines-before-current (N)
7724 "Make the number of empty lines before current exactly N.
7725 So this will delete or add empty lines."
7726 (save-excursion
7727 (goto-char (point-at-bol))
7728 (if (looking-back "\\s-+" nil 'greedy)
7729 (replace-match ""))
7730 (or (bobp) (insert "\n"))
7731 (while (> N 0)
7732 (insert "\n")
7733 (setq N (1- N)))))
7735 (defun org-get-heading (&optional no-tags no-todo)
7736 "Return the heading of the current entry, without the stars.
7737 When NO-TAGS is non-nil, don't include tags.
7738 When NO-TODO is non-nil, don't include TODO keywords."
7739 (save-excursion
7740 (org-back-to-heading t)
7741 (cond
7742 ((and no-tags no-todo)
7743 (looking-at org-complex-heading-regexp)
7744 (match-string 4))
7745 (no-tags
7746 (looking-at (concat org-outline-regexp
7747 "\\(.*?\\)"
7748 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7749 (match-string 1))
7750 (no-todo
7751 (looking-at org-todo-line-regexp)
7752 (match-string 3))
7753 (t (looking-at org-heading-regexp)
7754 (match-string 2)))))
7756 (defvar orgstruct-mode) ; defined below
7758 (defun org-heading-components ()
7759 "Return the components of the current heading.
7760 This is a list with the following elements:
7761 - the level as an integer
7762 - the reduced level, different if `org-odd-levels-only' is set.
7763 - the TODO keyword, or nil
7764 - the priority character, like ?A, or nil if no priority is given
7765 - the headline text itself, or the tags string if no headline text
7766 - the tags string, or nil."
7767 (save-excursion
7768 (org-back-to-heading t)
7769 (if (let (case-fold-search)
7770 (looking-at
7771 (if orgstruct-mode
7772 org-heading-regexp
7773 org-complex-heading-regexp)))
7774 (if orgstruct-mode
7775 (list (length (match-string 1))
7776 (org-reduced-level (length (match-string 1)))
7779 (match-string 2)
7780 nil)
7781 (list (length (match-string 1))
7782 (org-reduced-level (length (match-string 1)))
7783 (org-match-string-no-properties 2)
7784 (and (match-end 3) (aref (match-string 3) 2))
7785 (org-match-string-no-properties 4)
7786 (org-match-string-no-properties 5))))))
7788 (defun org-get-entry ()
7789 "Get the entry text, after heading, entire subtree."
7790 (save-excursion
7791 (org-back-to-heading t)
7792 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7794 (defun org-insert-heading-after-current ()
7795 "Insert a new heading with same level as current, after current subtree."
7796 (interactive)
7797 (org-back-to-heading)
7798 (org-insert-heading)
7799 (org-move-subtree-down)
7800 (end-of-line 1))
7802 (defun org-insert-heading-respect-content (&optional invisible-ok)
7803 "Insert heading with `org-insert-heading-respect-content' set to t."
7804 (interactive)
7805 (org-insert-heading '(4) invisible-ok))
7807 (defun org-insert-todo-heading-respect-content (&optional force-state)
7808 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7809 (interactive)
7810 (org-insert-todo-heading force-state '(4)))
7812 (defun org-insert-todo-heading (arg &optional force-heading)
7813 "Insert a new heading with the same level and TODO state as current heading.
7814 If the heading has no TODO state, or if the state is DONE, use the first
7815 state (TODO by default). Also with one prefix arg, force first state. With
7816 two prefix args, force inserting at the end of the parent subtree."
7817 (interactive "P")
7818 (when (or force-heading (not (org-insert-item 'checkbox)))
7819 (org-insert-heading (or (and (equal arg '(16)) '(16))
7820 force-heading))
7821 (save-excursion
7822 (org-back-to-heading)
7823 (outline-previous-heading)
7824 (looking-at org-todo-line-regexp))
7825 (let*
7826 ((new-mark-x
7827 (if (or (equal arg '(4))
7828 (not (match-beginning 2))
7829 (member (match-string 2) org-done-keywords))
7830 (car org-todo-keywords-1)
7831 (match-string 2)))
7832 (new-mark
7834 (run-hook-with-args-until-success
7835 'org-todo-get-default-hook new-mark-x nil)
7836 new-mark-x)))
7837 (beginning-of-line 1)
7838 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7839 (if org-treat-insert-todo-heading-as-state-change
7840 (org-todo new-mark)
7841 (insert new-mark " "))))
7842 (when org-provide-todo-statistics
7843 (org-update-parent-todo-statistics))))
7845 (defun org-insert-subheading (arg)
7846 "Insert a new subheading and demote it.
7847 Works for outline headings and for plain lists alike."
7848 (interactive "P")
7849 (org-insert-heading arg)
7850 (cond
7851 ((org-at-heading-p) (org-do-demote))
7852 ((org-at-item-p) (org-indent-item))))
7854 (defun org-insert-todo-subheading (arg)
7855 "Insert a new subheading with TODO keyword or checkbox and demote it.
7856 Works for outline headings and for plain lists alike."
7857 (interactive "P")
7858 (org-insert-todo-heading arg)
7859 (cond
7860 ((org-at-heading-p) (org-do-demote))
7861 ((org-at-item-p) (org-indent-item))))
7863 ;;; Promotion and Demotion
7865 (defvar org-after-demote-entry-hook nil
7866 "Hook run after an entry has been demoted.
7867 The cursor will be at the beginning of the entry.
7868 When a subtree is being demoted, the hook will be called for each node.")
7870 (defvar org-after-promote-entry-hook nil
7871 "Hook run after an entry has been promoted.
7872 The cursor will be at the beginning of the entry.
7873 When a subtree is being promoted, the hook will be called for each node.")
7875 (defun org-promote-subtree ()
7876 "Promote the entire subtree.
7877 See also `org-promote'."
7878 (interactive)
7879 (save-excursion
7880 (org-with-limited-levels (org-map-tree 'org-promote)))
7881 (org-fix-position-after-promote))
7883 (defun org-demote-subtree ()
7884 "Demote the entire subtree. See `org-demote'.
7885 See also `org-promote'."
7886 (interactive)
7887 (save-excursion
7888 (org-with-limited-levels (org-map-tree 'org-demote)))
7889 (org-fix-position-after-promote))
7892 (defun org-do-promote ()
7893 "Promote the current heading higher up the tree.
7894 If the region is active in `transient-mark-mode', promote all headings
7895 in the region."
7896 (interactive)
7897 (save-excursion
7898 (if (org-region-active-p)
7899 (org-map-region 'org-promote (region-beginning) (region-end))
7900 (org-promote)))
7901 (org-fix-position-after-promote))
7903 (defun org-do-demote ()
7904 "Demote the current heading lower down the tree.
7905 If the region is active in `transient-mark-mode', demote all headings
7906 in the region."
7907 (interactive)
7908 (save-excursion
7909 (if (org-region-active-p)
7910 (org-map-region 'org-demote (region-beginning) (region-end))
7911 (org-demote)))
7912 (org-fix-position-after-promote))
7914 (defun org-fix-position-after-promote ()
7915 "Make sure that after pro/demotion cursor position is right."
7916 (let ((pos (point)))
7917 (when (save-excursion
7918 (beginning-of-line 1)
7919 (looking-at org-todo-line-regexp)
7920 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7921 (cond ((eobp) (insert " "))
7922 ((eolp) (insert " "))
7923 ((equal (char-after) ?\ ) (forward-char 1))))))
7925 (defun org-current-level ()
7926 "Return the level of the current entry, or nil if before the first headline.
7927 The level is the number of stars at the beginning of the headline."
7928 (save-excursion
7929 (org-with-limited-levels
7930 (if (ignore-errors (org-back-to-heading t))
7931 (funcall outline-level)))))
7933 (defun org-get-previous-line-level ()
7934 "Return the outline depth of the last headline before the current line.
7935 Returns 0 for the first headline in the buffer, and nil if before the
7936 first headline."
7937 (and (org-current-level)
7938 (or (and (/= (line-beginning-position) (point-min))
7939 (save-excursion (beginning-of-line 0) (org-current-level)))
7940 0)))
7942 (defun org-reduced-level (l)
7943 "Compute the effective level of a heading.
7944 This takes into account the setting of `org-odd-levels-only'."
7945 (cond
7946 ((zerop l) 0)
7947 (org-odd-levels-only (1+ (floor (/ l 2))))
7948 (t l)))
7950 (defun org-level-increment ()
7951 "Return the number of stars that will be added or removed at a
7952 time to headlines when structure editing, based on the value of
7953 `org-odd-levels-only'."
7954 (if org-odd-levels-only 2 1))
7956 (defun org-get-valid-level (level &optional change)
7957 "Rectify a level change under the influence of `org-odd-levels-only'
7958 LEVEL is a current level, CHANGE is by how much the level should be
7959 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7960 even level numbers will become the next higher odd number."
7961 (if org-odd-levels-only
7962 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7963 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7964 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7965 (max 1 (+ level (or change 0)))))
7967 (if (boundp 'define-obsolete-function-alias)
7968 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7969 (define-obsolete-function-alias 'org-get-legal-level
7970 'org-get-valid-level)
7971 (define-obsolete-function-alias 'org-get-legal-level
7972 'org-get-valid-level "23.1")))
7974 (defun org-promote ()
7975 "Promote the current heading higher up the tree.
7976 If the region is active in `transient-mark-mode', promote all headings
7977 in the region."
7978 (org-back-to-heading t)
7979 (let* ((level (save-match-data (funcall outline-level)))
7980 (after-change-functions (remove 'flyspell-after-change-function
7981 after-change-functions))
7982 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7983 (diff (abs (- level (length up-head) -1))))
7984 (cond ((and (= level 1) org-called-with-limited-levels
7985 org-allow-promoting-top-level-subtree)
7986 (replace-match "# " nil t))
7987 ((= level 1)
7988 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
7989 (t (replace-match up-head nil t)))
7990 ;; Fixup tag positioning
7991 (unless (= level 1)
7992 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
7993 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7994 (run-hooks 'org-after-promote-entry-hook)))
7996 (defun org-demote ()
7997 "Demote the current heading lower down the tree.
7998 If the region is active in `transient-mark-mode', demote all headings
7999 in the region."
8000 (org-back-to-heading t)
8001 (let* ((level (save-match-data (funcall outline-level)))
8002 (after-change-functions (remove 'flyspell-after-change-function
8003 after-change-functions))
8004 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8005 (diff (abs (- level (length down-head) -1))))
8006 (replace-match down-head nil t)
8007 ;; Fixup tag positioning
8008 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
8009 (if org-adapt-indentation (org-fixup-indentation diff))
8010 (run-hooks 'org-after-demote-entry-hook)))
8012 (defun org-cycle-level ()
8013 "Cycle the level of an empty headline through possible states.
8014 This goes first to child, then to parent, level, then up the hierarchy.
8015 After top level, it switches back to sibling level."
8016 (interactive)
8017 (let ((org-adapt-indentation nil))
8018 (when (org-point-at-end-of-empty-headline)
8019 (setq this-command 'org-cycle-level) ; Only needed for caching
8020 (let ((cur-level (org-current-level))
8021 (prev-level (org-get-previous-line-level)))
8022 (cond
8023 ;; If first headline in file, promote to top-level.
8024 ((= prev-level 0)
8025 (loop repeat (/ (- cur-level 1) (org-level-increment))
8026 do (org-do-promote)))
8027 ;; If same level as prev, demote one.
8028 ((= prev-level cur-level)
8029 (org-do-demote))
8030 ;; If parent is top-level, promote to top level if not already.
8031 ((= prev-level 1)
8032 (loop repeat (/ (- cur-level 1) (org-level-increment))
8033 do (org-do-promote)))
8034 ;; If top-level, return to prev-level.
8035 ((= cur-level 1)
8036 (loop repeat (/ (- prev-level 1) (org-level-increment))
8037 do (org-do-demote)))
8038 ;; If less than prev-level, promote one.
8039 ((< cur-level prev-level)
8040 (org-do-promote))
8041 ;; If deeper than prev-level, promote until higher than
8042 ;; prev-level.
8043 ((> cur-level prev-level)
8044 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8045 do (org-do-promote))))
8046 t))))
8048 (defun org-map-tree (fun)
8049 "Call FUN for every heading underneath the current one."
8050 (org-back-to-heading)
8051 (let ((level (funcall outline-level)))
8052 (save-excursion
8053 (funcall fun)
8054 (while (and (progn
8055 (outline-next-heading)
8056 (> (funcall outline-level) level))
8057 (not (eobp)))
8058 (funcall fun)))))
8060 (defun org-map-region (fun beg end)
8061 "Call FUN for every heading between BEG and END."
8062 (let ((org-ignore-region t))
8063 (save-excursion
8064 (setq end (copy-marker end))
8065 (goto-char beg)
8066 (if (and (re-search-forward org-outline-regexp-bol nil t)
8067 (< (point) end))
8068 (funcall fun))
8069 (while (and (progn
8070 (outline-next-heading)
8071 (< (point) end))
8072 (not (eobp)))
8073 (funcall fun)))))
8075 (defvar org-property-end-re) ; silence byte-compiler
8076 (defun org-fixup-indentation (diff)
8077 "Change the indentation in the current entry by DIFF.
8078 However, if any line in the current entry has no indentation, or if it
8079 would end up with no indentation after the change, nothing at all is done."
8080 (save-excursion
8081 (let ((end (save-excursion (outline-next-heading)
8082 (point-marker)))
8083 (prohibit (if (> diff 0)
8084 "^\\S-"
8085 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8086 col)
8087 (unless (save-excursion (end-of-line 1)
8088 (re-search-forward prohibit end t))
8089 (while (and (< (point) end)
8090 (re-search-forward "^[ \t]+" end t))
8091 (goto-char (match-end 0))
8092 (setq col (current-column))
8093 (if (< diff 0) (replace-match ""))
8094 (org-indent-to-column (+ diff col))))
8095 (move-marker end nil))))
8097 (defun org-convert-to-odd-levels ()
8098 "Convert an org-mode file with all levels allowed to one with odd levels.
8099 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8100 level 5 etc."
8101 (interactive)
8102 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8103 (let ((outline-level 'org-outline-level)
8104 (org-odd-levels-only nil) n)
8105 (save-excursion
8106 (goto-char (point-min))
8107 (while (re-search-forward "^\\*\\*+ " nil t)
8108 (setq n (- (length (match-string 0)) 2))
8109 (while (>= (setq n (1- n)) 0)
8110 (org-demote))
8111 (end-of-line 1))))))
8113 (defun org-convert-to-oddeven-levels ()
8114 "Convert an org-mode file with only odd levels to one with odd/even levels.
8115 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8116 file contains a section with an even level, conversion would
8117 destroy the structure of the file. An error is signaled in this
8118 case."
8119 (interactive)
8120 (goto-char (point-min))
8121 ;; First check if there are no even levels
8122 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8123 (org-show-context t)
8124 (error "Not all levels are odd in this file. Conversion not possible"))
8125 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8126 (let ((outline-regexp org-outline-regexp)
8127 (outline-level 'org-outline-level)
8128 (org-odd-levels-only nil) n)
8129 (save-excursion
8130 (goto-char (point-min))
8131 (while (re-search-forward "^\\*\\*+ " nil t)
8132 (setq n (/ (1- (length (match-string 0))) 2))
8133 (while (>= (setq n (1- n)) 0)
8134 (org-promote))
8135 (end-of-line 1))))))
8137 (defun org-tr-level (n)
8138 "Make N odd if required."
8139 (if org-odd-levels-only (1+ (/ n 2)) n))
8141 ;;; Vertical tree motion, cutting and pasting of subtrees
8143 (defun org-move-subtree-up (&optional arg)
8144 "Move the current subtree up past ARG headlines of the same level."
8145 (interactive "p")
8146 (org-move-subtree-down (- (prefix-numeric-value arg))))
8148 (defun org-move-subtree-down (&optional arg)
8149 "Move the current subtree down past ARG headlines of the same level."
8150 (interactive "p")
8151 (setq arg (prefix-numeric-value arg))
8152 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8153 'org-get-last-sibling))
8154 (ins-point (make-marker))
8155 (cnt (abs arg))
8156 (col (current-column))
8157 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8158 ;; Select the tree
8159 (org-back-to-heading)
8160 (setq beg0 (point))
8161 (save-excursion
8162 (setq ne-beg (org-back-over-empty-lines))
8163 (setq beg (point)))
8164 (save-match-data
8165 (save-excursion (outline-end-of-heading)
8166 (setq folded (outline-invisible-p)))
8167 (progn (org-end-of-subtree nil t)
8168 (unless (eobp) (backward-char))))
8169 (outline-next-heading)
8170 (setq ne-end (org-back-over-empty-lines))
8171 (setq end (point))
8172 (goto-char beg0)
8173 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8174 ;; include less whitespace
8175 (save-excursion
8176 (goto-char beg)
8177 (forward-line (- ne-beg ne-end))
8178 (setq beg (point))))
8179 ;; Find insertion point, with error handling
8180 (while (> cnt 0)
8181 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8182 (progn (goto-char beg0)
8183 (user-error "Cannot move past superior level or buffer limit")))
8184 (setq cnt (1- cnt)))
8185 (if (> arg 0)
8186 ;; Moving forward - still need to move over subtree
8187 (progn (org-end-of-subtree t t)
8188 (save-excursion
8189 (org-back-over-empty-lines)
8190 (or (bolp) (newline)))))
8191 (setq ne-ins (org-back-over-empty-lines))
8192 (move-marker ins-point (point))
8193 (setq txt (buffer-substring beg end))
8194 (org-save-markers-in-region beg end)
8195 (delete-region beg end)
8196 (org-remove-empty-overlays-at beg)
8197 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8198 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8199 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8200 (let ((bbb (point)))
8201 (insert-before-markers txt)
8202 (org-reinstall-markers-in-region bbb)
8203 (move-marker ins-point bbb))
8204 (or (bolp) (insert "\n"))
8205 (setq ins-end (point))
8206 (goto-char ins-point)
8207 (org-skip-whitespace)
8208 (when (and (< arg 0)
8209 (org-first-sibling-p)
8210 (> ne-ins ne-beg))
8211 ;; Move whitespace back to beginning
8212 (save-excursion
8213 (goto-char ins-end)
8214 (let ((kill-whole-line t))
8215 (kill-line (- ne-ins ne-beg)) (point)))
8216 (insert (make-string (- ne-ins ne-beg) ?\n)))
8217 (move-marker ins-point nil)
8218 (if folded
8219 (hide-subtree)
8220 (org-show-entry)
8221 (show-children)
8222 (org-cycle-hide-drawers 'children))
8223 (org-clean-visibility-after-subtree-move)
8224 ;; move back to the initial column we were at
8225 (move-to-column col)))
8227 (defvar org-subtree-clip ""
8228 "Clipboard for cut and paste of subtrees.
8229 This is actually only a copy of the kill, because we use the normal kill
8230 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8232 (defvar org-subtree-clip-folded nil
8233 "Was the last copied subtree folded?
8234 This is used to fold the tree back after pasting.")
8236 (defun org-cut-subtree (&optional n)
8237 "Cut the current subtree into the clipboard.
8238 With prefix arg N, cut this many sequential subtrees.
8239 This is a short-hand for marking the subtree and then cutting it."
8240 (interactive "p")
8241 (org-copy-subtree n 'cut))
8243 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8244 "Copy the current subtree it in the clipboard.
8245 With prefix arg N, copy this many sequential subtrees.
8246 This is a short-hand for marking the subtree and then copying it.
8247 If CUT is non-nil, actually cut the subtree.
8248 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8249 of some markers in the region, even if CUT is non-nil. This is
8250 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8251 (interactive "p")
8252 (let (beg end folded (beg0 (point)))
8253 (if (org-called-interactively-p 'any)
8254 (org-back-to-heading nil) ; take what looks like a subtree
8255 (org-back-to-heading t)) ; take what is really there
8256 (setq beg (point))
8257 (skip-chars-forward " \t\r\n")
8258 (save-match-data
8259 (if nosubtrees
8260 (outline-next-heading)
8261 (save-excursion (outline-end-of-heading)
8262 (setq folded (outline-invisible-p)))
8263 (condition-case nil
8264 (org-forward-heading-same-level (1- n) t)
8265 (error nil))
8266 (org-end-of-subtree t t)))
8267 (setq end (point))
8268 (goto-char beg0)
8269 (when (> end beg)
8270 (setq org-subtree-clip-folded folded)
8271 (when (or cut force-store-markers)
8272 (org-save-markers-in-region beg end))
8273 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8274 (setq org-subtree-clip (current-kill 0))
8275 (message "%s: Subtree(s) with %d characters"
8276 (if cut "Cut" "Copied")
8277 (length org-subtree-clip)))))
8279 (defun org-paste-subtree (&optional level tree for-yank)
8280 "Paste the clipboard as a subtree, with modification of headline level.
8281 The entire subtree is promoted or demoted in order to match a new headline
8282 level.
8284 If the cursor is at the beginning of a headline, the same level as
8285 that headline is used to paste the tree.
8287 If not, the new level is derived from the *visible* headings
8288 before and after the insertion point, and taken to be the inferior headline
8289 level of the two. So if the previous visible heading is level 3 and the
8290 next is level 4 (or vice versa), level 4 will be used for insertion.
8291 This makes sure that the subtree remains an independent subtree and does
8292 not swallow low level entries.
8294 You can also force a different level, either by using a numeric prefix
8295 argument, or by inserting the heading marker by hand. For example, if the
8296 cursor is after \"*****\", then the tree will be shifted to level 5.
8298 If optional TREE is given, use this text instead of the kill ring.
8300 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8301 move back over whitespace before inserting, and move point to the end of
8302 the inserted text when done."
8303 (interactive "P")
8304 (setq tree (or tree (and kill-ring (current-kill 0))))
8305 (unless (org-kill-is-subtree-p tree)
8306 (user-error "%s"
8307 (substitute-command-keys
8308 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8309 (org-with-limited-levels
8310 (let* ((visp (not (outline-invisible-p)))
8311 (txt tree)
8312 (^re_ "\\(\\*+\\)[ \t]*")
8313 (old-level (if (string-match org-outline-regexp-bol txt)
8314 (- (match-end 0) (match-beginning 0) 1)
8315 -1))
8316 (force-level (cond (level (prefix-numeric-value level))
8317 ((and (looking-at "[ \t]*$")
8318 (string-match
8319 "^\\*+$" (buffer-substring
8320 (point-at-bol) (point))))
8321 (- (match-end 0) (match-beginning 0)))
8322 ((and (bolp)
8323 (looking-at org-outline-regexp))
8324 (- (match-end 0) (point) 1))))
8325 (previous-level (save-excursion
8326 (condition-case nil
8327 (progn
8328 (outline-previous-visible-heading 1)
8329 (if (looking-at ^re_)
8330 (- (match-end 0) (match-beginning 0) 1)
8332 (error 1))))
8333 (next-level (save-excursion
8334 (condition-case nil
8335 (progn
8336 (or (looking-at org-outline-regexp)
8337 (outline-next-visible-heading 1))
8338 (if (looking-at ^re_)
8339 (- (match-end 0) (match-beginning 0) 1)
8341 (error 1))))
8342 (new-level (or force-level (max previous-level next-level)))
8343 (shift (if (or (= old-level -1)
8344 (= new-level -1)
8345 (= old-level new-level))
8347 (- new-level old-level)))
8348 (delta (if (> shift 0) -1 1))
8349 (func (if (> shift 0) 'org-demote 'org-promote))
8350 (org-odd-levels-only nil)
8351 beg end newend)
8352 ;; Remove the forced level indicator
8353 (if force-level
8354 (delete-region (point-at-bol) (point)))
8355 ;; Paste
8356 (beginning-of-line (if (bolp) 1 2))
8357 (setq beg (point))
8358 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8359 (insert-before-markers txt)
8360 (unless (string-match "\n\\'" txt) (insert "\n"))
8361 (setq newend (point))
8362 (org-reinstall-markers-in-region beg)
8363 (setq end (point))
8364 (goto-char beg)
8365 (skip-chars-forward " \t\n\r")
8366 (setq beg (point))
8367 (if (and (outline-invisible-p) visp)
8368 (save-excursion (outline-show-heading)))
8369 ;; Shift if necessary
8370 (unless (= shift 0)
8371 (save-restriction
8372 (narrow-to-region beg end)
8373 (while (not (= shift 0))
8374 (org-map-region func (point-min) (point-max))
8375 (setq shift (+ delta shift)))
8376 (goto-char (point-min))
8377 (setq newend (point-max))))
8378 (when (or (org-called-interactively-p 'interactive) for-yank)
8379 (message "Clipboard pasted as level %d subtree" new-level))
8380 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8381 kill-ring
8382 (eq org-subtree-clip (current-kill 0))
8383 org-subtree-clip-folded)
8384 ;; The tree was folded before it was killed/copied
8385 (hide-subtree))
8386 (and for-yank (goto-char newend)))))
8388 (defun org-kill-is-subtree-p (&optional txt)
8389 "Check if the current kill is an outline subtree, or a set of trees.
8390 Returns nil if kill does not start with a headline, or if the first
8391 headline level is not the largest headline level in the tree.
8392 So this will actually accept several entries of equal levels as well,
8393 which is OK for `org-paste-subtree'.
8394 If optional TXT is given, check this string instead of the current kill."
8395 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8396 (re (org-get-limited-outline-regexp))
8397 (^re (concat "^" re))
8398 (start-level (and kill
8399 (string-match
8400 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8401 kill)
8402 (- (match-end 2) (match-beginning 2) 1)))
8403 (start (1+ (or (match-beginning 2) -1))))
8404 (if (not start-level)
8405 (progn
8406 nil) ;; does not even start with a heading
8407 (catch 'exit
8408 (while (setq start (string-match ^re kill (1+ start)))
8409 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8410 (throw 'exit nil)))
8411 t))))
8413 (defvar org-markers-to-move nil
8414 "Markers that should be moved with a cut-and-paste operation.
8415 Those markers are stored together with their positions relative to
8416 the start of the region.")
8418 (defun org-save-markers-in-region (beg end)
8419 "Check markers in region.
8420 If these markers are between BEG and END, record their position relative
8421 to BEG, so that after moving the block of text, we can put the markers back
8422 into place.
8423 This function gets called just before an entry or tree gets cut from the
8424 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8425 called immediately, to move the markers with the entries."
8426 (setq org-markers-to-move nil)
8427 (when (featurep 'org-clock)
8428 (org-clock-save-markers-for-cut-and-paste beg end))
8429 (when (featurep 'org-agenda)
8430 (org-agenda-save-markers-for-cut-and-paste beg end)))
8432 (defun org-check-and-save-marker (marker beg end)
8433 "Check if MARKER is between BEG and END.
8434 If yes, remember the marker and the distance to BEG."
8435 (when (and (marker-buffer marker)
8436 (equal (marker-buffer marker) (current-buffer)))
8437 (if (and (>= marker beg) (< marker end))
8438 (push (cons marker (- marker beg)) org-markers-to-move))))
8440 (defun org-reinstall-markers-in-region (beg)
8441 "Move all remembered markers to their position relative to BEG."
8442 (mapc (lambda (x)
8443 (move-marker (car x) (+ beg (cdr x))))
8444 org-markers-to-move)
8445 (setq org-markers-to-move nil))
8447 (defun org-narrow-to-subtree ()
8448 "Narrow buffer to the current subtree."
8449 (interactive)
8450 (save-excursion
8451 (save-match-data
8452 (org-with-limited-levels
8453 (narrow-to-region
8454 (progn (org-back-to-heading t) (point))
8455 (progn (org-end-of-subtree t t)
8456 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8457 (point)))))))
8459 (defun org-narrow-to-block ()
8460 "Narrow buffer to the current block."
8461 (interactive)
8462 (let* ((case-fold-search t)
8463 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8464 "^[ \t]*#\\+end_.*")))
8465 (if blockp
8466 (narrow-to-region (car blockp) (cdr blockp))
8467 (user-error "Not in a block"))))
8469 (eval-when-compile
8470 (defvar org-property-drawer-re))
8472 (defvar org-property-start-re) ;; defined below
8473 (defun org-clone-subtree-with-time-shift (n &optional shift)
8474 "Clone the task (subtree) at point N times.
8475 The clones will be inserted as siblings.
8477 In interactive use, the user will be prompted for the number of
8478 clones to be produced. If the entry has a timestamp, the user
8479 will also be prompted for a time shift, which may be a repeater
8480 as used in time stamps, for example `+3d'. To disable this,
8481 you can call the function with a universal prefix argument.
8483 When a valid repeater is given and the entry contains any time
8484 stamps, the clones will become a sequence in time, with time
8485 stamps in the subtree shifted for each clone produced. If SHIFT
8486 is nil or the empty string, time stamps will be left alone. The
8487 ID property of the original subtree is removed.
8489 If the original subtree did contain time stamps with a repeater,
8490 the following will happen:
8491 - the repeater will be removed in each clone
8492 - an additional clone will be produced, with the current, unshifted
8493 date(s) in the entry.
8494 - the original entry will be placed *after* all the clones, with
8495 repeater intact.
8496 - the start days in the repeater in the original entry will be shifted
8497 to past the last clone.
8498 In this way you can spell out a number of instances of a repeating task,
8499 and still retain the repeater to cover future instances of the task."
8500 (interactive "nNumber of clones to produce: ")
8501 (let ((shift
8502 (or shift
8503 (if (and (not (equal current-prefix-arg '(4)))
8504 (save-excursion
8505 (re-search-forward org-ts-regexp-both
8506 (save-excursion
8507 (org-end-of-subtree t)
8508 (point)) t)))
8509 (read-from-minibuffer
8510 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8511 ""))) ;; No time shift
8512 (n-no-remove -1)
8513 (drawer-re org-drawer-regexp)
8514 beg end template task idprop
8515 shift-n shift-what doshift nmin nmax)
8516 (if (not (and (integerp n) (> n 0)))
8517 (error "Invalid number of replications %s" n))
8518 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8519 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8520 shift)))
8521 (error "Invalid shift specification %s" shift))
8522 (when doshift
8523 (setq shift-n (string-to-number (match-string 1 shift))
8524 shift-what (cdr (assoc (match-string 2 shift)
8525 '(("d" . day) ("w" . week)
8526 ("m" . month) ("y" . year))))))
8527 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8528 (setq nmin 1 nmax n)
8529 (org-back-to-heading t)
8530 (setq beg (point))
8531 (setq idprop (org-entry-get nil "ID"))
8532 (org-end-of-subtree t t)
8533 (or (bolp) (insert "\n"))
8534 (setq end (point))
8535 (setq template (buffer-substring beg end))
8536 (when (and doshift
8537 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8538 (delete-region beg end)
8539 (setq end beg)
8540 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8541 (goto-char end)
8542 (loop for n from nmin to nmax do
8543 ;; prepare clone
8544 (with-temp-buffer
8545 (insert template)
8546 (org-mode)
8547 (goto-char (point-min))
8548 (org-show-subtree)
8549 (and idprop (if org-clone-delete-id
8550 (org-entry-delete nil "ID")
8551 (org-id-get-create t)))
8552 (unless (= n 0)
8553 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8554 (kill-whole-line))
8555 (goto-char (point-min))
8556 (while (re-search-forward drawer-re nil t)
8557 (mapc (lambda (d)
8558 (org-remove-empty-drawer-at d (point))) org-drawers)))
8559 (goto-char (point-min))
8560 (when doshift
8561 (while (re-search-forward org-ts-regexp-both nil t)
8562 (org-timestamp-change (* n shift-n) shift-what))
8563 (unless (= n n-no-remove)
8564 (goto-char (point-min))
8565 (while (re-search-forward org-ts-regexp nil t)
8566 (save-excursion
8567 (goto-char (match-beginning 0))
8568 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8569 (delete-region (match-beginning 1) (match-end 1)))))))
8570 (setq task (buffer-string)))
8571 (insert task))
8572 (goto-char beg)))
8574 ;;; Outline Sorting
8576 (defun org-sort (with-case)
8577 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8578 Optional argument WITH-CASE means sort case-sensitively."
8579 (interactive "P")
8580 (cond
8581 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8582 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8584 (org-call-with-arg 'org-sort-entries with-case))))
8586 (defun org-sort-remove-invisible (s)
8587 "Remove invisible links from string S."
8588 (remove-text-properties 0 (length s) org-rm-props s)
8589 (while (string-match org-bracket-link-regexp s)
8590 (setq s (replace-match (if (match-end 2)
8591 (match-string 3 s)
8592 (match-string 1 s)) t t s)))
8593 (let ((st (format " %s " s)))
8594 (while (string-match org-emph-re st)
8595 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8596 (setq s (substring st 1 -1)))
8599 (defvar org-priority-regexp) ; defined later in the file
8601 (defvar org-after-sorting-entries-or-items-hook nil
8602 "Hook that is run after a bunch of entries or items have been sorted.
8603 When children are sorted, the cursor is in the parent line when this
8604 hook gets called. When a region or a plain list is sorted, the cursor
8605 will be in the first entry of the sorted region/list.")
8607 (defun org-sort-entries
8608 (&optional with-case sorting-type getkey-func compare-func property)
8609 "Sort entries on a certain level of an outline tree.
8610 If there is an active region, the entries in the region are sorted.
8611 Else, if the cursor is before the first entry, sort the top-level items.
8612 Else, the children of the entry at point are sorted.
8614 Sorting can be alphabetically, numerically, by date/time as given by
8615 a time stamp, by a property, by priority order, or by a custom function.
8617 The command prompts for the sorting type unless it has been given to the
8618 function through the SORTING-TYPE argument, which needs to be a character,
8619 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8620 precise meaning of each character:
8622 n Numerically, by converting the beginning of the entry/item to a number.
8623 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8624 o By order of TODO keywords.
8625 t By date/time, either the first active time stamp in the entry, or, if
8626 none exist, by the first inactive one.
8627 s By the scheduled date/time.
8628 d By deadline date/time.
8629 c By creation time, which is assumed to be the first inactive time stamp
8630 at the beginning of a line.
8631 p By priority according to the cookie.
8632 r By the value of a property.
8634 Capital letters will reverse the sort order.
8636 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8637 called with point at the beginning of the record. It must return either
8638 a string or a number that should serve as the sorting key for that record.
8640 Comparing entries ignores case by default. However, with an optional argument
8641 WITH-CASE, the sorting considers case as well.
8643 Sorting is done against the visible part of the headlines, it ignores hidden
8644 links."
8645 (interactive "P")
8646 (let ((case-func (if with-case 'identity 'downcase))
8647 (cmstr
8648 ;; The clock marker is lost when using `sort-subr', let's
8649 ;; store the clocking string.
8650 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8651 (save-excursion
8652 (goto-char org-clock-marker)
8653 (looking-back "^.*") (match-string-no-properties 0))))
8654 start beg end stars re re2
8655 txt what tmp)
8656 ;; Find beginning and end of region to sort
8657 (cond
8658 ((org-region-active-p)
8659 ;; we will sort the region
8660 (setq end (region-end)
8661 what "region")
8662 (goto-char (region-beginning))
8663 (if (not (org-at-heading-p)) (outline-next-heading))
8664 (setq start (point)))
8665 ((or (org-at-heading-p)
8666 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8667 ;; we will sort the children of the current headline
8668 (org-back-to-heading)
8669 (setq start (point)
8670 end (progn (org-end-of-subtree t t)
8671 (or (bolp) (insert "\n"))
8672 (when (>= (org-back-over-empty-lines) 1)
8673 (forward-line 1))
8674 (point))
8675 what "children")
8676 (goto-char start)
8677 (show-subtree)
8678 (outline-next-heading))
8680 ;; we will sort the top-level entries in this file
8681 (goto-char (point-min))
8682 (or (org-at-heading-p) (outline-next-heading))
8683 (setq start (point))
8684 (goto-char (point-max))
8685 (beginning-of-line 1)
8686 (when (looking-at ".*?\\S-")
8687 ;; File ends in a non-white line
8688 (end-of-line 1)
8689 (insert "\n"))
8690 (setq end (point-max))
8691 (setq what "top-level")
8692 (goto-char start)
8693 (show-all)))
8695 (setq beg (point))
8696 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8698 (looking-at "\\(\\*+\\)")
8699 (setq stars (match-string 1)
8700 re (concat "^" (regexp-quote stars) " +")
8701 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8702 txt (buffer-substring beg end))
8703 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8704 (if (and (not (equal stars "*")) (string-match re2 txt))
8705 (user-error "Region to sort contains a level above the first entry"))
8707 (unless sorting-type
8708 (message
8709 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8710 [t]ime [s]cheduled [d]eadline [c]reated
8711 A/N/P/R/O/F/T/S/D/C means reversed:"
8712 what)
8713 (setq sorting-type (read-char-exclusive))
8715 (unless getkey-func
8716 (and (= (downcase sorting-type) ?f)
8717 (setq getkey-func
8718 (org-icompleting-read "Sort using function: "
8719 obarray 'fboundp t nil nil))
8720 (setq getkey-func (intern getkey-func))))
8722 (and (= (downcase sorting-type) ?r)
8723 (not property)
8724 (setq property
8725 (org-icompleting-read "Property: "
8726 (mapcar 'list (org-buffer-property-keys t))
8727 nil t))))
8729 (message "Sorting entries...")
8731 (save-restriction
8732 (narrow-to-region start end)
8733 (let ((dcst (downcase sorting-type))
8734 (case-fold-search nil)
8735 (now (current-time)))
8736 (sort-subr
8737 (/= dcst sorting-type)
8738 ;; This function moves to the beginning character of the "record" to
8739 ;; be sorted.
8740 (lambda nil
8741 (if (re-search-forward re nil t)
8742 (goto-char (match-beginning 0))
8743 (goto-char (point-max))))
8744 ;; This function moves to the last character of the "record" being
8745 ;; sorted.
8746 (lambda nil
8747 (save-match-data
8748 (condition-case nil
8749 (outline-forward-same-level 1)
8750 (error
8751 (goto-char (point-max))))))
8752 ;; This function returns the value that gets sorted against.
8753 (lambda nil
8754 (cond
8755 ((= dcst ?n)
8756 (if (looking-at org-complex-heading-regexp)
8757 (string-to-number (org-sort-remove-invisible (match-string 4)))
8758 nil))
8759 ((= dcst ?a)
8760 (if (looking-at org-complex-heading-regexp)
8761 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8762 nil))
8763 ((= dcst ?t)
8764 (let ((end (save-excursion (outline-next-heading) (point))))
8765 (if (or (re-search-forward org-ts-regexp end t)
8766 (re-search-forward org-ts-regexp-both end t))
8767 (org-time-string-to-seconds (match-string 0))
8768 (org-float-time now))))
8769 ((= dcst ?c)
8770 (let ((end (save-excursion (outline-next-heading) (point))))
8771 (if (re-search-forward
8772 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8773 end t)
8774 (org-time-string-to-seconds (match-string 0))
8775 (org-float-time now))))
8776 ((= dcst ?s)
8777 (let ((end (save-excursion (outline-next-heading) (point))))
8778 (if (re-search-forward org-scheduled-time-regexp end t)
8779 (org-time-string-to-seconds (match-string 1))
8780 (org-float-time now))))
8781 ((= dcst ?d)
8782 (let ((end (save-excursion (outline-next-heading) (point))))
8783 (if (re-search-forward org-deadline-time-regexp end t)
8784 (org-time-string-to-seconds (match-string 1))
8785 (org-float-time now))))
8786 ((= dcst ?p)
8787 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8788 (string-to-char (match-string 2))
8789 org-default-priority))
8790 ((= dcst ?r)
8791 (or (org-entry-get nil property) ""))
8792 ((= dcst ?o)
8793 (if (looking-at org-complex-heading-regexp)
8794 (- 9999 (length (member (match-string 2)
8795 org-todo-keywords-1)))))
8796 ((= dcst ?f)
8797 (if getkey-func
8798 (progn
8799 (setq tmp (funcall getkey-func))
8800 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8801 tmp)
8802 (error "Invalid key function `%s'" getkey-func)))
8803 (t (error "Invalid sorting type `%c'" sorting-type))))
8805 (cond
8806 ((= dcst ?a) 'string<)
8807 ((= dcst ?f) compare-func)
8808 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8809 (run-hooks 'org-after-sorting-entries-or-items-hook)
8810 ;; Reset the clock marker if needed
8811 (when cmstr
8812 (save-excursion
8813 (goto-char start)
8814 (search-forward cmstr nil t)
8815 (move-marker org-clock-marker (point))))
8816 (message "Sorting entries...done")))
8818 (defun org-do-sort (table what &optional with-case sorting-type)
8819 "Sort TABLE of WHAT according to SORTING-TYPE.
8820 The user will be prompted for the SORTING-TYPE if the call to this
8821 function does not specify it. WHAT is only for the prompt, to indicate
8822 what is being sorted. The sorting key will be extracted from
8823 the car of the elements of the table.
8824 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8825 (unless sorting-type
8826 (message
8827 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8828 what)
8829 (setq sorting-type (read-char-exclusive)))
8830 (let ((dcst (downcase sorting-type))
8831 extractfun comparefun)
8832 ;; Define the appropriate functions
8833 (cond
8834 ((= dcst ?n)
8835 (setq extractfun 'string-to-number
8836 comparefun (if (= dcst sorting-type) '< '>)))
8837 ((= dcst ?a)
8838 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8839 (lambda(x) (downcase (org-sort-remove-invisible x))))
8840 comparefun (if (= dcst sorting-type)
8841 'string<
8842 (lambda (a b) (and (not (string< a b))
8843 (not (string= a b)))))))
8844 ((= dcst ?t)
8845 (setq extractfun
8846 (lambda (x)
8847 (if (or (string-match org-ts-regexp x)
8848 (string-match org-ts-regexp-both x))
8849 (org-float-time
8850 (org-time-string-to-time (match-string 0 x)))
8852 comparefun (if (= dcst sorting-type) '< '>)))
8853 (t (error "Invalid sorting type `%c'" sorting-type)))
8855 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8856 table)
8857 (lambda (a b) (funcall comparefun (car a) (car b))))))
8860 ;;; The orgstruct minor mode
8862 ;; Define a minor mode which can be used in other modes in order to
8863 ;; integrate the org-mode structure editing commands.
8865 ;; This is really a hack, because the org-mode structure commands use
8866 ;; keys which normally belong to the major mode. Here is how it
8867 ;; works: The minor mode defines all the keys necessary to operate the
8868 ;; structure commands, but wraps the commands into a function which
8869 ;; tests if the cursor is currently at a headline or a plain list
8870 ;; item. If that is the case, the structure command is used,
8871 ;; temporarily setting many Org-mode variables like regular
8872 ;; expressions for filling etc. However, when any of those keys is
8873 ;; used at a different location, function uses `key-binding' to look
8874 ;; up if the key has an associated command in another currently active
8875 ;; keymap (minor modes, major mode, global), and executes that
8876 ;; command. There might be problems if any of the keys is otherwise
8877 ;; used as a prefix key.
8879 (defcustom orgstruct-heading-prefix-regexp ""
8880 "Regexp that matches the custom prefix of Org headlines in
8881 orgstruct(++)-mode."
8882 :group 'org
8883 :version "24.4"
8884 :package-version '(Org . "8.3")
8885 :type 'regexp)
8886 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8888 (defcustom orgstruct-setup-hook nil
8889 "Hook run after orgstruct-mode-map is filled."
8890 :group 'org
8891 :version "24.4"
8892 :package-version '(Org . "8.0")
8893 :type 'hook)
8895 (defvar orgstruct-initialized nil)
8897 (defvar org-local-vars nil
8898 "List of local variables, for use by `orgstruct-mode'.")
8900 ;;;###autoload
8901 (define-minor-mode orgstruct-mode
8902 "Toggle the minor mode `orgstruct-mode'.
8903 This mode is for using Org-mode structure commands in other
8904 modes. The following keys behave as if Org-mode were active, if
8905 the cursor is on a headline, or on a plain list item (both as
8906 defined by Org-mode)."
8907 nil " OrgStruct" (make-sparse-keymap)
8908 (funcall (if orgstruct-mode
8909 'add-to-invisibility-spec
8910 'remove-from-invisibility-spec)
8911 '(outline . t))
8912 (when orgstruct-mode
8913 (org-load-modules-maybe)
8914 (unless orgstruct-initialized
8915 (orgstruct-setup)
8916 (setq orgstruct-initialized t))))
8918 ;;;###autoload
8919 (defun turn-on-orgstruct ()
8920 "Unconditionally turn on `orgstruct-mode'."
8921 (orgstruct-mode 1))
8923 (defvar org-fb-vars nil)
8924 (make-variable-buffer-local 'org-fb-vars)
8925 (defun orgstruct++-mode (&optional arg)
8926 "Toggle `orgstruct-mode', the enhanced version of it.
8927 In addition to setting orgstruct-mode, this also exports all
8928 indentation and autofilling variables from org-mode into the
8929 buffer. It will also recognize item context in multiline items."
8930 (interactive "P")
8931 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8932 (if (< arg 1)
8933 (progn (orgstruct-mode -1)
8934 (mapc (lambda(v)
8935 (org-set-local (car v)
8936 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8937 org-fb-vars))
8938 (orgstruct-mode 1)
8939 (setq org-fb-vars nil)
8940 (unless org-local-vars
8941 (setq org-local-vars (org-get-local-variables)))
8942 (let (var val)
8943 (mapc
8944 (lambda (x)
8945 (when (string-match
8946 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8947 (symbol-name (car x)))
8948 (setq var (car x) val (nth 1 x))
8949 (push (list var `(quote ,(eval var))) org-fb-vars)
8950 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8951 org-local-vars)
8952 (org-set-local 'orgstruct-is-++ t))))
8954 (defvar orgstruct-is-++ nil
8955 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8956 (make-variable-buffer-local 'orgstruct-is-++)
8958 ;;;###autoload
8959 (defun turn-on-orgstruct++ ()
8960 "Unconditionally turn on `orgstruct++-mode'."
8961 (orgstruct++-mode 1))
8963 (defun orgstruct-error ()
8964 "Error when there is no default binding for a structure key."
8965 (interactive)
8966 (funcall (if (fboundp 'user-error)
8967 'user-error
8968 'error)
8969 "This key has no function outside structure elements"))
8971 (defun orgstruct-setup ()
8972 "Setup orgstruct keymap."
8973 (dolist (cell '((org-demote . t)
8974 (org-metaleft . t)
8975 (org-metaright . t)
8976 (org-promote . t)
8977 (org-shiftmetaleft . t)
8978 (org-shiftmetaright . t)
8979 org-backward-element
8980 org-backward-heading-same-level
8981 org-ctrl-c-ret
8982 org-ctrl-c-minus
8983 org-ctrl-c-star
8984 org-cycle
8985 org-forward-heading-same-level
8986 org-insert-heading
8987 org-insert-heading-respect-content
8988 org-kill-note-or-show-branches
8989 org-mark-subtree
8990 org-meta-return
8991 org-metadown
8992 org-metaup
8993 org-narrow-to-subtree
8994 org-promote-subtree
8995 org-reveal
8996 org-shiftdown
8997 org-shiftleft
8998 org-shiftmetadown
8999 org-shiftmetaup
9000 org-shiftright
9001 org-shifttab
9002 org-shifttab
9003 org-shiftup
9004 org-show-subtree
9005 org-sort
9006 org-up-element
9007 outline-demote
9008 outline-next-visible-heading
9009 outline-previous-visible-heading
9010 outline-promote
9011 outline-up-heading
9012 show-children))
9013 (let ((f (or (car-safe cell) cell))
9014 (disable-when-heading-prefix (cdr-safe cell)))
9015 (when (fboundp f)
9016 (let ((new-bindings))
9017 (dolist (binding (nconc (where-is-internal f org-mode-map)
9018 (where-is-internal f outline-mode-map)))
9019 (push binding new-bindings)
9020 ;; TODO use local-function-key-map
9021 (dolist (rep '(("<tab>" . "TAB")
9022 ("<return>" . "RET")
9023 ("<escape>" . "ESC")
9024 ("<delete>" . "DEL")))
9025 (setq binding (read-kbd-macro
9026 (let ((case-fold-search))
9027 (replace-regexp-in-string
9028 (regexp-quote (cdr rep))
9029 (car rep)
9030 (key-description binding)))))
9031 (pushnew binding new-bindings :test 'equal)))
9032 (dolist (binding new-bindings)
9033 (let ((key (lookup-key orgstruct-mode-map binding)))
9034 (when (or (not key) (numberp key))
9035 (condition-case nil
9036 (org-defkey orgstruct-mode-map
9037 binding
9038 (orgstruct-make-binding f binding disable-when-heading-prefix))
9039 (error nil)))))))))
9040 (run-hooks 'orgstruct-setup-hook))
9042 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9043 "Create a function for binding in the structure minor mode.
9044 FUN is the command to call inside a table. KEY is the key that
9045 should be checked in for a command to execute outside of tables.
9046 Non-nil `disable-when-heading-prefix' means to disable the command
9047 if `orgstruct-heading-prefix-regexp' is not empty."
9048 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9049 (let ((nname name)
9050 (i 0))
9051 (while (fboundp (intern nname))
9052 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9053 (setq name (intern nname)))
9054 (eval
9055 (let ((bindings '((org-heading-regexp
9056 (concat "^"
9057 orgstruct-heading-prefix-regexp
9058 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9059 (org-outline-regexp
9060 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9061 (org-outline-regexp-bol
9062 (concat "^" org-outline-regexp))
9063 (outline-regexp org-outline-regexp)
9064 (outline-heading-end-regexp "\n")
9065 (outline-level 'org-outline-level)
9066 (outline-heading-alist))))
9067 `(defun ,name (arg)
9068 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9069 "Outside of structure, run the binding of `"
9070 (key-description key) "'."
9071 (when disable-when-heading-prefix
9072 (concat
9073 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9074 "back to the default binding due to limitations of Org's implementation of\n"
9075 "`" (symbol-name fun) "'.")))
9076 (interactive "p")
9077 (let* ((disable
9078 ,(and disable-when-heading-prefix
9079 '(not (string= orgstruct-heading-prefix-regexp ""))))
9080 (fallback
9081 (or disable
9082 (not
9083 (let* ,bindings
9084 (org-context-p 'headline 'item
9085 ,(when (memq fun
9086 '(org-insert-heading
9087 org-insert-heading-respect-content
9088 org-meta-return))
9089 '(when orgstruct-is-++
9090 'item-body))))))))
9091 (if fallback
9092 (let* ((orgstruct-mode)
9093 (binding
9094 (loop with key = ,key
9095 for rep in
9096 '(nil
9097 ("<\\([^>]*\\)tab>" . "\\1TAB")
9098 ("<\\([^>]*\\)return>" . "\\1RET")
9099 ("<\\([^>]*\\)escape>" . "\\1ESC")
9100 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9102 (when rep
9103 (setq key (read-kbd-macro
9104 (let ((case-fold-search))
9105 (replace-regexp-in-string
9106 (car rep)
9107 (cdr rep)
9108 (key-description key))))))
9109 thereis (key-binding key))))
9110 (if (keymapp binding)
9111 (org-set-transient-map binding)
9112 (let ((func (or binding
9113 (unless disable
9114 'orgstruct-error))))
9115 (when func
9116 (call-interactively func)))))
9117 (org-run-like-in-org-mode
9118 (lambda ()
9119 (interactive)
9120 (let* ,bindings
9121 (call-interactively ',fun)))))))))
9122 name))
9124 (defun org-contextualize-keys (alist contexts)
9125 "Return valid elements in ALIST depending on CONTEXTS.
9127 `org-agenda-custom-commands' or `org-capture-templates' are the
9128 values used for ALIST, and `org-agenda-custom-commands-contexts'
9129 or `org-capture-templates-contexts' are the associated contexts
9130 definitions."
9131 (let ((contexts
9132 ;; normalize contexts
9133 (mapcar
9134 (lambda(c) (cond ((listp (cadr c))
9135 (list (car c) (car c) (cadr c)))
9136 ((string= "" (cadr c))
9137 (list (car c) (car c) (caddr c)))
9138 (t c))) contexts))
9139 (a alist) c r s)
9140 ;; loop over all commands or templates
9141 (while (setq c (pop a))
9142 (let (vrules repl)
9143 (cond
9144 ((not (assoc (car c) contexts))
9145 (push c r))
9146 ((and (assoc (car c) contexts)
9147 (setq vrules (org-contextualize-validate-key
9148 (car c) contexts)))
9149 (mapc (lambda (vr)
9150 (when (not (equal (car vr) (cadr vr)))
9151 (setq repl vr))) vrules)
9152 (if (not repl) (push c r)
9153 (push (cadr repl) s)
9154 (push
9155 (cons (car c)
9156 (cdr (or (assoc (cadr repl) alist)
9157 (error "Undefined key `%s' as contextual replacement for `%s'"
9158 (cadr repl) (car c)))))
9159 r))))))
9160 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9161 (delq
9163 (delete-dups
9164 (mapcar (lambda (x)
9165 (let ((tpl (car x)))
9166 (when (not (delq
9168 (mapcar (lambda(y)
9169 (equal y tpl)) s))) x)))
9170 (reverse r))))))
9172 (defun org-contextualize-validate-key (key contexts)
9173 "Check CONTEXTS for agenda or capture KEY."
9174 (let (r rr res)
9175 (while (setq r (pop contexts))
9176 (mapc
9177 (lambda (rr)
9178 (when
9179 (and (equal key (car r))
9180 (if (functionp rr) (funcall rr)
9181 (or (and (eq (car rr) 'in-file)
9182 (buffer-file-name)
9183 (string-match (cdr rr) (buffer-file-name)))
9184 (and (eq (car rr) 'in-mode)
9185 (string-match (cdr rr) (symbol-name major-mode)))
9186 (and (eq (car rr) 'in-buffer)
9187 (string-match (cdr rr) (buffer-name)))
9188 (when (and (eq (car rr) 'not-in-file)
9189 (buffer-file-name))
9190 (not (string-match (cdr rr) (buffer-file-name))))
9191 (when (eq (car rr) 'not-in-mode)
9192 (not (string-match (cdr rr) (symbol-name major-mode))))
9193 (when (eq (car rr) 'not-in-buffer)
9194 (not (string-match (cdr rr) (buffer-name)))))))
9195 (push r res)))
9196 (car (last r))))
9197 (delete-dups (delq nil res))))
9199 (defun org-context-p (&rest contexts)
9200 "Check if local context is any of CONTEXTS.
9201 Possible values in the list of contexts are `table', `headline', and `item'."
9202 (let ((pos (point)))
9203 (goto-char (point-at-bol))
9204 (prog1 (or (and (memq 'table contexts)
9205 (looking-at "[ \t]*|"))
9206 (and (memq 'headline contexts)
9207 (looking-at org-outline-regexp))
9208 (and (memq 'item contexts)
9209 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9210 (and (memq 'item-body contexts)
9211 (org-in-item-p)))
9212 (goto-char pos))))
9214 (defun org-get-local-variables ()
9215 "Return a list of all local variables in an Org mode buffer."
9216 (let (varlist)
9217 (with-current-buffer (get-buffer-create "*Org tmp*")
9218 (erase-buffer)
9219 (org-mode)
9220 (setq varlist (buffer-local-variables)))
9221 (kill-buffer "*Org tmp*")
9222 (delq nil
9223 (mapcar
9224 (lambda (x)
9225 (setq x
9226 (if (symbolp x)
9227 (list x)
9228 (list (car x) (cdr x))))
9229 (if (and (not (get (car x) 'org-state))
9230 (string-match
9231 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9232 (symbol-name (car x))))
9233 x nil))
9234 varlist))))
9236 (defun org-clone-local-variables (from-buffer &optional regexp)
9237 "Clone local variables from FROM-BUFFER.
9238 Optional argument REGEXP selects variables to clone."
9239 (mapc
9240 (lambda (pair)
9241 (and (symbolp (car pair))
9242 (or (null regexp)
9243 (string-match regexp (symbol-name (car pair))))
9244 (set (make-local-variable (car pair))
9245 (cdr pair))))
9246 (buffer-local-variables from-buffer)))
9248 ;;;###autoload
9249 (defun org-run-like-in-org-mode (cmd)
9250 "Run a command, pretending that the current buffer is in Org-mode.
9251 This will temporarily bind local variables that are typically bound in
9252 Org-mode to the values they have in Org-mode, and then interactively
9253 call CMD."
9254 (org-load-modules-maybe)
9255 (unless org-local-vars
9256 (setq org-local-vars (org-get-local-variables)))
9257 (let (binds)
9258 (dolist (var org-local-vars)
9259 (when (or (not (boundp (car var)))
9260 (eq (symbol-value (car var))
9261 (default-value (car var))))
9262 (push (list (car var) `(quote ,(cadr var))) binds)))
9263 (eval `(let ,binds
9264 (call-interactively (quote ,cmd))))))
9266 ;;;; Archiving
9268 (defun org-get-category (&optional pos force-refresh)
9269 "Get the category applying to position POS."
9270 (save-match-data
9271 (if force-refresh (org-refresh-category-properties))
9272 (let ((pos (or pos (point))))
9273 (or (get-text-property pos 'org-category)
9274 (progn (org-refresh-category-properties)
9275 (get-text-property pos 'org-category))))))
9277 (defun org-refresh-category-properties ()
9278 "Refresh category text properties in the buffer."
9279 (let ((case-fold-search t)
9280 (inhibit-read-only t)
9281 (def-cat (cond
9282 ((null org-category)
9283 (if buffer-file-name
9284 (file-name-sans-extension
9285 (file-name-nondirectory buffer-file-name))
9286 "???"))
9287 ((symbolp org-category) (symbol-name org-category))
9288 (t org-category)))
9289 beg end cat pos optionp)
9290 (org-with-silent-modifications
9291 (save-excursion
9292 (save-restriction
9293 (widen)
9294 (goto-char (point-min))
9295 (put-text-property (point) (point-max) 'org-category def-cat)
9296 (while (re-search-forward
9297 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9298 (setq pos (match-end 0)
9299 optionp (equal (char-after (match-beginning 0)) ?#)
9300 cat (org-trim (match-string 2)))
9301 (if optionp
9302 (setq beg (point-at-bol) end (point-max))
9303 (org-back-to-heading t)
9304 (setq beg (point) end (org-end-of-subtree t t)))
9305 (put-text-property beg end 'org-category cat)
9306 (put-text-property beg end 'org-category-position beg)
9307 (goto-char pos)))))))
9309 (defun org-refresh-properties (dprop tprop)
9310 "Refresh buffer text properties.
9311 DPROP is the drawer property and TPROP is the corresponding text
9312 property to set."
9313 (let ((case-fold-search t)
9314 (inhibit-read-only t) p)
9315 (org-with-silent-modifications
9316 (save-excursion
9317 (save-restriction
9318 (widen)
9319 (goto-char (point-min))
9320 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9321 (setq p (org-match-string-no-properties 1))
9322 (save-excursion
9323 (org-back-to-heading t)
9324 (put-text-property
9325 (point-at-bol) (or (outline-next-heading) (point-max)) tprop p))))))))
9328 ;;;; Link Stuff
9330 ;;; Link abbreviations
9332 (defun org-link-expand-abbrev (link)
9333 "Apply replacements as defined in `org-link-abbrev-alist'."
9334 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9335 (let* ((key (match-string 1 link))
9336 (as (or (assoc key org-link-abbrev-alist-local)
9337 (assoc key org-link-abbrev-alist)))
9338 (tag (and (match-end 2) (match-string 3 link)))
9339 rpl)
9340 (if (not as)
9341 link
9342 (setq rpl (cdr as))
9343 (cond
9344 ((symbolp rpl) (funcall rpl tag))
9345 ((string-match "%(\\([^)]+\\))" rpl)
9346 (replace-match
9347 (save-match-data
9348 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9349 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9350 ((string-match "%h" rpl)
9351 (replace-match (url-hexify-string (or tag "")) t t rpl))
9352 (t (concat rpl tag)))))
9353 link))
9355 ;;; Storing and inserting links
9357 (defvar org-insert-link-history nil
9358 "Minibuffer history for links inserted with `org-insert-link'.")
9360 (defvar org-stored-links nil
9361 "Contains the links stored with `org-store-link'.")
9363 (defvar org-store-link-plist nil
9364 "Plist with info about the most recently link created with `org-store-link'.")
9366 (defvar org-link-protocols nil
9367 "Link protocols added to Org-mode using `org-add-link-type'.")
9369 (defvar org-store-link-functions nil
9370 "List of functions that are called to create and store a link.
9371 Each function will be called in turn until one returns a non-nil
9372 value. Each function should check if it is responsible for creating
9373 this link (for example by looking at the major mode).
9374 If not, it must exit and return nil.
9375 If yes, it should return a non-nil value after a calling
9376 `org-store-link-props' with a list of properties and values.
9377 Special properties are:
9379 :type The link prefix, like \"http\". This must be given.
9380 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9381 This is obligatory as well.
9382 :description Optional default description for the second pair
9383 of brackets in an Org-mode link. The user can still change
9384 this when inserting this link into an Org-mode buffer.
9386 In addition to these, any additional properties can be specified
9387 and then used in capture templates.")
9389 (defun org-add-link-type (type &optional follow export)
9390 "Add TYPE to the list of `org-link-types'.
9391 Re-compute all regular expressions depending on `org-link-types'
9393 FOLLOW and EXPORT are two functions.
9395 FOLLOW should take the link path as the single argument and do whatever
9396 is necessary to follow the link, for example find a file or display
9397 a mail message.
9399 EXPORT should format the link path for export to one of the export formats.
9400 It should be a function accepting three arguments:
9402 path the path of the link, the text after the prefix (like \"http:\")
9403 desc the description of the link, if any, or a description added by
9404 org-export-normalize-links if there is none
9405 format the export format, a symbol like `html' or `latex' or `ascii'..
9407 The function may use the FORMAT information to return different values
9408 depending on the format. The return value will be put literally into
9409 the exported file. If the return value is nil, this means Org should
9410 do what it normally does with links which do not have EXPORT defined.
9412 Org-mode has a built-in default for exporting links. If you are happy with
9413 this default, there is no need to define an export function for the link
9414 type. For a simple example of an export function, see `org-bbdb.el'."
9415 (add-to-list 'org-link-types type t)
9416 (org-make-link-regexps)
9417 (if (assoc type org-link-protocols)
9418 (setcdr (assoc type org-link-protocols) (list follow export))
9419 (push (list type follow export) org-link-protocols)))
9421 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9422 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9424 ;;;###autoload
9425 (defun org-store-link (arg)
9426 "\\<org-mode-map>Store an org-link to the current location.
9427 This link is added to `org-stored-links' and can later be inserted
9428 into an org-buffer with \\[org-insert-link].
9430 For some link types, a prefix arg is interpreted.
9431 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9432 For file links, arg negates `org-context-in-file-links'.
9434 A double prefix arg force skipping storing functions that are not
9435 part of Org's core.
9437 A triple prefix arg force storing a link for each line in the
9438 active region."
9439 (interactive "P")
9440 (org-load-modules-maybe)
9441 (if (and (equal arg '(64)) (org-region-active-p))
9442 (save-excursion
9443 (let ((end (region-end)))
9444 (goto-char (region-beginning))
9445 (set-mark (point))
9446 (while (< (point-at-eol) end)
9447 (move-end-of-line 1) (activate-mark)
9448 (let (current-prefix-arg)
9449 (call-interactively 'org-store-link))
9450 (move-beginning-of-line 2)
9451 (set-mark (point)))))
9452 (org-with-limited-levels
9453 (setq org-store-link-plist nil)
9454 (let (link cpltxt desc description search
9455 txt custom-id agenda-link sfuns sfunsn)
9456 (cond
9458 ;; Store a link using an external link type
9459 ((and (not (equal arg '(16)))
9460 (setq sfuns
9461 (delq
9462 nil (mapcar (lambda (f)
9463 (let (fs) (if (funcall f) (push f fs))))
9464 org-store-link-functions))
9465 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9466 (or (and (cdr sfuns)
9467 (funcall (intern
9468 (completing-read
9469 "Which function for creating the link? "
9470 sfunsn nil t (car sfunsn)))))
9471 (funcall (caar sfuns)))
9472 (setq link (plist-get org-store-link-plist :link)
9473 desc (or (plist-get org-store-link-plist
9474 :description) link))))
9476 ;; Store a link from a source code buffer
9477 ((org-src-edit-buffer-p)
9478 (let (label gc)
9479 (while (or (not label)
9480 (save-excursion
9481 (save-restriction
9482 (widen)
9483 (goto-char (point-min))
9484 (re-search-forward
9485 (regexp-quote (format org-coderef-label-format label))
9486 nil t))))
9487 (when label (message "Label exists already") (sit-for 2))
9488 (setq label (read-string "Code line label: " label)))
9489 (end-of-line 1)
9490 (setq link (format org-coderef-label-format label))
9491 (setq gc (- 79 (length link)))
9492 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9493 (insert link)
9494 (setq link (concat "(" label ")") desc nil)))
9496 ;; We are in the agenda, link to referenced location
9497 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9498 (let ((m (or (get-text-property (point) 'org-hd-marker)
9499 (get-text-property (point) 'org-marker))))
9500 (when m
9501 (org-with-point-at m
9502 (setq agenda-link
9503 (if (org-called-interactively-p 'any)
9504 (call-interactively 'org-store-link)
9505 (org-store-link nil)))))))
9507 ((eq major-mode 'calendar-mode)
9508 (let ((cd (calendar-cursor-to-date)))
9509 (setq link
9510 (format-time-string
9511 (car org-time-stamp-formats)
9512 (apply 'encode-time
9513 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9514 nil nil nil))))
9515 (org-store-link-props :type "calendar" :date cd)))
9517 ((eq major-mode 'help-mode)
9518 (setq link (concat "help:" (save-excursion
9519 (goto-char (point-min))
9520 (looking-at "^[^ ]+")
9521 (match-string 0))))
9522 (org-store-link-props :type "help"))
9524 ((eq major-mode 'w3-mode)
9525 (setq cpltxt (if (and (buffer-name)
9526 (not (string-match "Untitled" (buffer-name))))
9527 (buffer-name)
9528 (url-view-url t))
9529 link (url-view-url t))
9530 (org-store-link-props :type "w3" :url (url-view-url t)))
9532 ((eq major-mode 'image-mode)
9533 (setq cpltxt (concat "file:"
9534 (abbreviate-file-name buffer-file-name))
9535 link cpltxt)
9536 (org-store-link-props :type "image" :file buffer-file-name))
9538 ;; In dired, store a link to the file of the current line
9539 ((eq major-mode 'dired-mode)
9540 (let ((file (dired-get-filename nil t)))
9541 (setq file (if file
9542 (abbreviate-file-name
9543 (expand-file-name (dired-get-filename nil t)))
9544 ;; otherwise, no file so use current directory.
9545 default-directory))
9546 (setq cpltxt (concat "file:" file)
9547 link cpltxt)))
9549 ((setq search (run-hook-with-args-until-success
9550 'org-create-file-search-functions))
9551 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9552 "::" search))
9553 (setq cpltxt (or description link)))
9555 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9556 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9557 (cond
9558 ;; Store a link using the target at point
9559 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9560 (setq cpltxt
9561 (concat "file:"
9562 (abbreviate-file-name
9563 (buffer-file-name (buffer-base-buffer)))
9564 "::" (match-string 1))
9565 link cpltxt))
9566 ((and (featurep 'org-id)
9567 (or (eq org-id-link-to-org-use-id t)
9568 (and (org-called-interactively-p 'any)
9569 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9570 (and (eq org-id-link-to-org-use-id
9571 'create-if-interactive-and-no-custom-id)
9572 (not custom-id))))
9573 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9574 ;; Store a link using the ID at point
9575 (setq link (condition-case nil
9576 (prog1 (org-id-store-link)
9577 (setq desc (or (plist-get org-store-link-plist
9578 :description)
9579 "")))
9580 (error
9581 ;; Probably before first headline, link only to file
9582 (concat "file:"
9583 (abbreviate-file-name
9584 (buffer-file-name (buffer-base-buffer))))))))
9586 ;; Just link to current headline
9587 (setq cpltxt (concat "file:"
9588 (abbreviate-file-name
9589 (buffer-file-name (buffer-base-buffer)))))
9590 ;; Add a context search string
9591 (when (org-xor org-context-in-file-links arg)
9592 (let* ((ee (org-element-at-point))
9593 (et (org-element-type ee))
9594 (ev (plist-get (cadr ee) :value))
9595 (ek (plist-get (cadr ee) :key))
9596 (eok (and (stringp ek) (string-match "name" ek))))
9597 (setq txt (cond
9598 ((org-at-heading-p) nil)
9599 ((and (eq et 'keyword) eok) ev)
9600 ((org-region-active-p)
9601 (buffer-substring (region-beginning) (region-end)))))
9602 (when (or (null txt) (string-match "\\S-" txt))
9603 (setq cpltxt
9604 (concat cpltxt "::"
9605 (condition-case nil
9606 (org-make-org-heading-search-string txt)
9607 (error "")))
9608 desc (or (and (eq et 'keyword) eok ev)
9609 (nth 4 (ignore-errors (org-heading-components)))
9610 "NONE")))))
9611 (if (string-match "::\\'" cpltxt)
9612 (setq cpltxt (substring cpltxt 0 -2)))
9613 (setq link cpltxt))))
9615 ((buffer-file-name (buffer-base-buffer))
9616 ;; Just link to this file here.
9617 (setq cpltxt (concat "file:"
9618 (abbreviate-file-name
9619 (buffer-file-name (buffer-base-buffer)))))
9620 ;; Add a context string.
9621 (when (org-xor org-context-in-file-links arg)
9622 (setq txt (if (org-region-active-p)
9623 (buffer-substring (region-beginning) (region-end))
9624 (buffer-substring (point-at-bol) (point-at-eol))))
9625 ;; Only use search option if there is some text.
9626 (when (string-match "\\S-" txt)
9627 (setq cpltxt
9628 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9629 desc "NONE")))
9630 (setq link cpltxt))
9632 ((org-called-interactively-p 'interactive)
9633 (user-error "No method for storing a link from this buffer"))
9635 (t (setq link nil)))
9637 ;; We're done setting link and desc, clean up
9638 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9639 (setq link (or link cpltxt)
9640 desc (or desc cpltxt))
9641 (cond ((equal desc "NONE") (setq desc nil))
9642 ((and desc (string-match org-bracket-link-analytic-regexp desc))
9643 (let ((d0 (match-string 3 desc))
9644 (p0 (match-string 5 desc)))
9645 (setq desc
9646 (replace-regexp-in-string
9647 org-bracket-link-regexp
9648 (concat (or p0 d0)
9649 (if (equal (length (match-string 0 desc))
9650 (length desc)) "*" "")) desc)))))
9652 ;; Return the link
9653 (if (not (and (or (org-called-interactively-p 'any)
9654 executing-kbd-macro) link))
9655 (or agenda-link (and link (org-make-link-string link desc)))
9656 (push (list link desc) org-stored-links)
9657 (message "Stored: %s" (or desc link))
9658 (when custom-id
9659 (setq link (concat "file:" (abbreviate-file-name
9660 (buffer-file-name)) "::#" custom-id))
9661 (push (list link desc) org-stored-links))
9662 (car org-stored-links))))))
9664 (defun org-store-link-props (&rest plist)
9665 "Store link properties, extract names and addresses."
9666 (let (x adr)
9667 (when (setq x (plist-get plist :from))
9668 (setq adr (mail-extract-address-components x))
9669 (setq plist (plist-put plist :fromname (car adr)))
9670 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9671 (when (setq x (plist-get plist :to))
9672 (setq adr (mail-extract-address-components x))
9673 (setq plist (plist-put plist :toname (car adr)))
9674 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9675 (let ((from (plist-get plist :from))
9676 (to (plist-get plist :to)))
9677 (when (and from to org-from-is-user-regexp)
9678 (setq plist
9679 (plist-put plist :fromto
9680 (if (string-match org-from-is-user-regexp from)
9681 (concat "to %t")
9682 (concat "from %f"))))))
9683 (setq org-store-link-plist plist))
9685 (defun org-add-link-props (&rest plist)
9686 "Add these properties to the link property list."
9687 (let (key value)
9688 (while plist
9689 (setq key (pop plist) value (pop plist))
9690 (setq org-store-link-plist
9691 (plist-put org-store-link-plist key value)))))
9693 (defun org-email-link-description (&optional fmt)
9694 "Return the description part of an email link.
9695 This takes information from `org-store-link-plist' and formats it
9696 according to FMT (default from `org-email-link-description-format')."
9697 (setq fmt (or fmt org-email-link-description-format))
9698 (let* ((p org-store-link-plist)
9699 (to (plist-get p :toaddress))
9700 (from (plist-get p :fromaddress))
9701 (table
9702 (list
9703 (cons "%c" (plist-get p :fromto))
9704 (cons "%F" (plist-get p :from))
9705 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9706 (cons "%T" (plist-get p :to))
9707 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9708 (cons "%s" (plist-get p :subject))
9709 (cons "%d" (plist-get p :date))
9710 (cons "%m" (plist-get p :message-id)))))
9711 (when (string-match "%c" fmt)
9712 ;; Check if the user wrote this message
9713 (if (and org-from-is-user-regexp from to
9714 (save-match-data (string-match org-from-is-user-regexp from)))
9715 (setq fmt (replace-match "to %t" t t fmt))
9716 (setq fmt (replace-match "from %f" t t fmt))))
9717 (org-replace-escapes fmt table)))
9719 (defun org-make-org-heading-search-string (&optional string)
9720 "Make search string for the current headline or STRING."
9721 (let ((s (or string
9722 (and (derived-mode-p 'org-mode)
9723 (save-excursion
9724 (org-back-to-heading t)
9725 (org-element-property :raw-value (org-element-at-point))))))
9726 (lines org-context-in-file-links))
9727 (or string (setq s (concat "*" s))) ; Add * for headlines
9728 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9729 (when (and string (integerp lines) (> lines 0))
9730 (let ((slines (org-split-string s "\n")))
9731 (when (< lines (length slines))
9732 (setq s (mapconcat
9733 'identity
9734 (reverse (nthcdr (- (length slines) lines)
9735 (reverse slines))) "\n")))))
9736 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9738 (defun org-make-link-string (link &optional description)
9739 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9740 (unless (string-match "\\S-" link)
9741 (error "Empty link"))
9742 (when (and description
9743 (stringp description)
9744 (not (string-match "\\S-" description)))
9745 (setq description nil))
9746 (when (stringp description)
9747 ;; Remove brackets from the description, they are fatal.
9748 (while (string-match "\\[" description)
9749 (setq description (replace-match "{" t t description)))
9750 (while (string-match "\\]" description)
9751 (setq description (replace-match "}" t t description))))
9752 (when (equal link description)
9753 ;; No description needed, it is identical
9754 (setq description nil))
9755 (when (and (not description)
9756 (not (string-match (org-image-file-name-regexp) link))
9757 (not (equal link (org-link-escape link))))
9758 (setq description (org-extract-attributes link)))
9759 (setq link
9760 (cond ((string-match (org-image-file-name-regexp) link) link)
9761 ((string-match org-link-types-re link)
9762 (concat (match-string 1 link)
9763 (org-link-escape (substring link (match-end 1)))))
9764 (t (org-link-escape link))))
9765 (concat "[[" link "]"
9766 (if description (concat "[" description "]") "")
9767 "]"))
9769 (defconst org-link-escape-chars
9770 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9771 "List of characters that should be escaped in link.
9772 This is the list that is used for internal purposes.")
9774 (defconst org-link-escape-chars-browser
9775 '(?\ ?\")
9776 "List of escapes for characters that are problematic in links.
9777 This is the list that is used before handing over to the browser.")
9779 (defun org-link-escape (text &optional table merge)
9780 "Return percent escaped representation of TEXT.
9781 TEXT is a string with the text to escape.
9782 Optional argument TABLE is a list with characters that should be
9783 escaped. When nil, `org-link-escape-chars' is used.
9784 If optional argument MERGE is set, merge TABLE into
9785 `org-link-escape-chars'."
9786 (cond
9787 ((and table merge)
9788 (mapc (lambda (defchr)
9789 (unless (member defchr table)
9790 (setq table (cons defchr table)))) org-link-escape-chars))
9791 ((null table)
9792 (setq table org-link-escape-chars)))
9793 (mapconcat
9794 (lambda (char)
9795 (if (or (member char table)
9796 (and (or (< char 32) (= char 37) (> char 126))
9797 org-url-hexify-p))
9798 (mapconcat (lambda (sequence-element)
9799 (format "%%%.2X" sequence-element))
9800 (or (encode-coding-char char 'utf-8)
9801 (error "Unable to percent escape character: %s"
9802 (char-to-string char))) "")
9803 (char-to-string char))) text ""))
9805 (defun org-link-unescape (str)
9806 "Unhex hexified Unicode strings as returned from the JavaScript function
9807 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9808 (unless (and (null str) (string= "" str))
9809 (let ((pos 0) (case-fold-search t) unhexed)
9810 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9811 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9812 (setq str (replace-match unhexed t t str))
9813 (setq pos (+ pos (length unhexed))))))
9814 str)
9816 (defun org-link-unescape-compound (hex)
9817 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9818 Note: this function also decodes single byte encodings like
9819 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9820 (save-match-data
9821 (let* ((bytes (cdr (split-string hex "%")))
9822 (ret "")
9823 (eat 0)
9824 (sum 0))
9825 (while bytes
9826 (let* ((val (string-to-number (pop bytes) 16))
9827 (shift-xor
9828 (if (= 0 eat)
9829 (cond
9830 ((>= val 252) (cons 6 252))
9831 ((>= val 248) (cons 5 248))
9832 ((>= val 240) (cons 4 240))
9833 ((>= val 224) (cons 3 224))
9834 ((>= val 192) (cons 2 192))
9835 (t (cons 0 0)))
9836 (cons 6 128))))
9837 (if (>= val 192) (setq eat (car shift-xor)))
9838 (setq val (logxor val (cdr shift-xor)))
9839 (setq sum (+ (lsh sum (car shift-xor)) val))
9840 (if (> eat 0) (setq eat (- eat 1)))
9841 (cond
9842 ((= 0 eat) ;multi byte
9843 (setq ret (concat ret (org-char-to-string sum)))
9844 (setq sum 0))
9845 ((not bytes) ; single byte(s)
9846 (setq ret (org-link-unescape-single-byte-sequence hex))))
9847 )) ;; end (while bytes
9848 ret )))
9850 (defun org-link-unescape-single-byte-sequence (hex)
9851 "Unhexify hex-encoded single byte character sequences."
9852 (mapconcat (lambda (byte)
9853 (char-to-string (string-to-number byte 16)))
9854 (cdr (split-string hex "%")) ""))
9856 (defun org-xor (a b)
9857 "Exclusive or."
9858 (if a (not b) b))
9860 (defun org-fixup-message-id-for-http (s)
9861 "Replace special characters in a message id, so it can be used in an http query."
9862 (when (string-match "%" s)
9863 (setq s (mapconcat (lambda (c)
9864 (if (eq c ?%)
9865 "%25"
9866 (char-to-string c)))
9867 s "")))
9868 (while (string-match "<" s)
9869 (setq s (replace-match "%3C" t t s)))
9870 (while (string-match ">" s)
9871 (setq s (replace-match "%3E" t t s)))
9872 (while (string-match "@" s)
9873 (setq s (replace-match "%40" t t s)))
9876 (defun org-link-prettify (link)
9877 "Return a human-readable representation of LINK.
9878 The car of LINK must be a raw link the cdr of LINK must be either
9879 a link description or nil."
9880 (let ((desc (or (cadr link) "<no description>")))
9881 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9882 "<" (car link) ">")))
9884 ;;;###autoload
9885 (defun org-insert-link-global ()
9886 "Insert a link like Org-mode does.
9887 This command can be called in any mode to insert a link in Org-mode syntax."
9888 (interactive)
9889 (org-load-modules-maybe)
9890 (org-run-like-in-org-mode 'org-insert-link))
9892 (defun org-insert-all-links (&optional keep)
9893 "Insert all links in `org-stored-links'."
9894 (interactive "P")
9895 (let ((links (copy-sequence org-stored-links)) l)
9896 (while (setq l (if keep (pop links) (pop org-stored-links)))
9897 (insert "- ")
9898 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9899 (insert "\n"))))
9901 (defun org-link-fontify-links-to-this-file ()
9902 "Fontify links to the current file in `org-stored-links'."
9903 (let ((f (buffer-file-name)) a b)
9904 (setq a (mapcar (lambda(l)
9905 (let ((ll (car l)))
9906 (when (and (string-match "^file:\\(.+\\)::" ll)
9907 (equal f (expand-file-name (match-string 1 ll))))
9908 ll)))
9909 org-stored-links))
9910 (when (featurep 'org-id)
9911 (setq b (mapcar (lambda(l)
9912 (let ((ll (car l)))
9913 (when (and (string-match "^id:\\(.+\\)$" ll)
9914 (equal f (expand-file-name
9915 (or (org-id-find-id-file
9916 (match-string 1 ll)) ""))))
9917 ll)))
9918 org-stored-links)))
9919 (mapcar (lambda(l)
9920 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9921 (delq nil (append a b)))))
9923 (defvar org-link-links-in-this-file nil)
9924 (defun org-insert-link (&optional complete-file link-location default-description)
9925 "Insert a link. At the prompt, enter the link.
9927 Completion can be used to insert any of the link protocol prefixes like
9928 http or ftp in use.
9930 The history can be used to select a link previously stored with
9931 `org-store-link'. When the empty string is entered (i.e. if you just
9932 press RET at the prompt), the link defaults to the most recently
9933 stored link. As SPC triggers completion in the minibuffer, you need to
9934 use M-SPC or C-q SPC to force the insertion of a space character.
9936 You will also be prompted for a description, and if one is given, it will
9937 be displayed in the buffer instead of the link.
9939 If there is already a link at point, this command will allow you to edit link
9940 and description parts.
9942 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9943 be selected using completion. The path to the file will be relative to the
9944 current directory if the file is in the current directory or a subdirectory.
9945 Otherwise, the link will be the absolute path as completed in the minibuffer
9946 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9947 option `org-link-file-path-type'.
9949 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9950 the current directory or below.
9952 With three \\[universal-argument] prefixes, negate the meaning of
9953 `org-keep-stored-link-after-insertion'.
9955 If `org-make-link-description-function' is non-nil, this function will be
9956 called with the link target, and the result will be the default
9957 link description.
9959 If the LINK-LOCATION parameter is non-nil, this value will be
9960 used as the link location instead of reading one interactively.
9962 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9963 be used as the default description."
9964 (interactive "P")
9965 (let* ((wcf (current-window-configuration))
9966 (origbuf (current-buffer))
9967 (region (if (org-region-active-p)
9968 (buffer-substring (region-beginning) (region-end))))
9969 (remove (and region (list (region-beginning) (region-end))))
9970 (desc region)
9971 tmphist ; byte-compile incorrectly complains about this
9972 (link link-location)
9973 (abbrevs org-link-abbrev-alist-local)
9974 entry file all-prefixes auto-desc)
9975 (cond
9976 (link-location) ; specified by arg, just use it.
9977 ((org-in-regexp org-bracket-link-regexp 1)
9978 ;; We do have a link at point, and we are going to edit it.
9979 (setq remove (list (match-beginning 0) (match-end 0)))
9980 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9981 (setq link (read-string "Link: "
9982 (org-link-unescape
9983 (org-match-string-no-properties 1)))))
9984 ((or (org-in-regexp org-angle-link-re)
9985 (org-in-regexp org-plain-link-re))
9986 ;; Convert to bracket link
9987 (setq remove (list (match-beginning 0) (match-end 0))
9988 link (read-string "Link: "
9989 (org-remove-angle-brackets (match-string 0)))))
9990 ((member complete-file '((4) (16)))
9991 ;; Completing read for file names.
9992 (setq link (org-file-complete-link complete-file)))
9994 ;; Read link, with completion for stored links.
9995 (org-link-fontify-links-to-this-file)
9996 (org-switch-to-buffer-other-window "*Org Links*")
9997 (with-current-buffer "*Org Links*"
9998 (erase-buffer)
9999 (insert "Insert a link.
10000 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10001 (when org-stored-links
10002 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10003 (insert (mapconcat 'org-link-prettify
10004 (reverse org-stored-links) "\n")))
10005 (goto-char (point-min)))
10006 (let ((cw (selected-window)))
10007 (select-window (get-buffer-window "*Org Links*" 'visible))
10008 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10009 (unless (pos-visible-in-window-p (point-max))
10010 (org-fit-window-to-buffer))
10011 (and (window-live-p cw) (select-window cw)))
10012 ;; Fake a link history, containing the stored links.
10013 (setq tmphist (append (mapcar 'car org-stored-links)
10014 org-insert-link-history))
10015 (setq all-prefixes (append (mapcar 'car abbrevs)
10016 (mapcar 'car org-link-abbrev-alist)
10017 org-link-types))
10018 (unwind-protect
10019 (progn
10020 (setq link
10021 (org-completing-read
10022 "Link: "
10023 (append
10024 (mapcar (lambda (x) (concat x ":"))
10025 all-prefixes)
10026 (mapcar 'car org-stored-links))
10027 nil nil nil
10028 'tmphist
10029 (caar org-stored-links)))
10030 (if (not (string-match "\\S-" link))
10031 (user-error "No link selected"))
10032 (mapc (lambda(l)
10033 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
10034 org-stored-links)
10035 (if (or (member link all-prefixes)
10036 (and (equal ":" (substring link -1))
10037 (member (substring link 0 -1) all-prefixes)
10038 (setq link (substring link 0 -1))))
10039 (setq link (with-current-buffer origbuf
10040 (org-link-try-special-completion link)))))
10041 (set-window-configuration wcf)
10042 (kill-buffer "*Org Links*"))
10043 (setq entry (assoc link org-stored-links))
10044 (or entry (push link org-insert-link-history))
10045 (setq desc (or desc (nth 1 entry)))))
10047 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10048 (not org-keep-stored-link-after-insertion))
10049 (setq org-stored-links (delq (assoc link org-stored-links)
10050 org-stored-links)))
10052 (if (and (string-match org-plain-link-re link)
10053 (not (string-match org-ts-regexp link)))
10054 ;; URL-like link, normalize the use of angular brackets.
10055 (setq link (org-remove-angle-brackets link)))
10057 ;; Check if we are linking to the current file with a search
10058 ;; option If yes, simplify the link by using only the search
10059 ;; option.
10060 (when (and buffer-file-name
10061 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10062 (let* ((path (match-string 1 link))
10063 (case-fold-search nil)
10064 (search (match-string 2 link)))
10065 (save-match-data
10066 (if (equal (file-truename buffer-file-name) (file-truename path))
10067 ;; We are linking to this same file, with a search option
10068 (setq link search)))))
10070 ;; Check if we can/should use a relative path. If yes, simplify the link
10071 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10072 (let* ((type (match-string 1 link))
10073 (path (match-string 2 link))
10074 (origpath path)
10075 (case-fold-search nil))
10076 (cond
10077 ((or (eq org-link-file-path-type 'absolute)
10078 (equal complete-file '(16)))
10079 (setq path (abbreviate-file-name (expand-file-name path))))
10080 ((eq org-link-file-path-type 'noabbrev)
10081 (setq path (expand-file-name path)))
10082 ((eq org-link-file-path-type 'relative)
10083 (setq path (file-relative-name path)))
10085 (save-match-data
10086 (if (string-match (concat "^" (regexp-quote
10087 (expand-file-name
10088 (file-name-as-directory
10089 default-directory))))
10090 (expand-file-name path))
10091 ;; We are linking a file with relative path name.
10092 (setq path (substring (expand-file-name path)
10093 (match-end 0)))
10094 (setq path (abbreviate-file-name (expand-file-name path)))))))
10095 (setq link (concat type path))
10096 (if (equal desc origpath)
10097 (setq desc path))))
10099 (if org-make-link-description-function
10100 (setq desc
10101 (or (condition-case nil
10102 (funcall org-make-link-description-function link desc)
10103 (error (progn (message "Can't get link description from `%s'"
10104 (symbol-name org-make-link-description-function))
10105 (sit-for 2) nil)))
10106 (read-string "Description: " default-description)))
10107 (if default-description (setq desc default-description)
10108 (setq desc (or (and auto-desc desc)
10109 (read-string "Description: " desc)))))
10111 (unless (string-match "\\S-" desc) (setq desc nil))
10112 (if remove (apply 'delete-region remove))
10113 (insert (org-make-link-string link desc))))
10115 (defun org-link-try-special-completion (type)
10116 "If there is completion support for link type TYPE, offer it."
10117 (let ((fun (intern (concat "org-" type "-complete-link"))))
10118 (if (functionp fun)
10119 (funcall fun)
10120 (read-string "Link (no completion support): " (concat type ":")))))
10122 (defun org-file-complete-link (&optional arg)
10123 "Create a file link using completion."
10124 (let (file link)
10125 (setq file (org-iread-file-name "File: "))
10126 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10127 (pwd1 (file-name-as-directory (abbreviate-file-name
10128 (expand-file-name ".")))))
10129 (cond
10130 ((equal arg '(16))
10131 (setq link (concat
10132 "file:"
10133 (abbreviate-file-name (expand-file-name file)))))
10134 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10135 (setq link (concat "file:" (match-string 1 file))))
10136 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10137 (expand-file-name file))
10138 (setq link (concat
10139 "file:" (match-string 1 (expand-file-name file)))))
10140 (t (setq link (concat "file:" file)))))
10141 link))
10143 (defun org-iread-file-name (&rest args)
10144 "Read-file-name using `ido-mode' speedup if available.
10145 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10146 See `read-file-name' for a description of parameters."
10147 (org-without-partial-completion
10148 (if (and org-completion-use-ido
10149 (fboundp 'ido-read-file-name)
10150 (boundp 'ido-mode) ido-mode
10151 (listp (second args)))
10152 (let ((ido-enter-matching-directory nil))
10153 (apply 'ido-read-file-name args))
10154 (apply 'read-file-name args))))
10156 (defun org-completing-read (&rest args)
10157 "Completing-read with SPACE being a normal character."
10158 (let ((enable-recursive-minibuffers t)
10159 (minibuffer-local-completion-map
10160 (copy-keymap minibuffer-local-completion-map)))
10161 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10162 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10163 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10164 (apply 'org-icompleting-read args)))
10166 (defun org-completing-read-no-i (&rest args)
10167 (let (org-completion-use-ido org-completion-use-iswitchb)
10168 (apply 'org-completing-read args)))
10170 (defun org-iswitchb-completing-read (prompt choices &rest args)
10171 "Use iswitch as a completing-read replacement to choose from choices.
10172 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10173 from."
10174 (let* ((iswitchb-use-virtual-buffers nil)
10175 (iswitchb-make-buflist-hook
10176 (lambda ()
10177 (setq iswitchb-temp-buflist choices))))
10178 (iswitchb-read-buffer prompt)))
10180 (defun org-icompleting-read (&rest args)
10181 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10182 (org-without-partial-completion
10183 (if (and org-completion-use-ido
10184 (fboundp 'ido-completing-read)
10185 (boundp 'ido-mode) ido-mode
10186 (listp (second args)))
10187 (let ((ido-enter-matching-directory nil))
10188 (apply 'ido-completing-read (concat (car args))
10189 (if (consp (car (nth 1 args)))
10190 (mapcar 'car (nth 1 args))
10191 (nth 1 args))
10192 (cddr args)))
10193 (if (and org-completion-use-iswitchb
10194 (boundp 'iswitchb-mode) iswitchb-mode
10195 (listp (second args)))
10196 (apply 'org-iswitchb-completing-read (concat (car args))
10197 (if (consp (car (nth 1 args)))
10198 (mapcar 'car (nth 1 args))
10199 (nth 1 args))
10200 (cddr args))
10201 (apply 'completing-read args)))))
10203 (defun org-extract-attributes (s)
10204 "Extract the attributes cookie from a string and set as text property."
10205 (let (a attr (start 0) key value)
10206 (save-match-data
10207 (when (string-match "{{\\([^}]+\\)}}$" s)
10208 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10209 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10210 (setq key (match-string 1 a) value (match-string 2 a)
10211 start (match-end 0)
10212 attr (plist-put attr (intern key) value))))
10213 (org-add-props s nil 'org-attr attr))
10216 ;;; Opening/following a link
10218 (defvar org-link-search-failed nil)
10220 (defvar org-open-link-functions nil
10221 "Hook for functions finding a plain text link.
10222 These functions must take a single argument, the link content.
10223 They will be called for links that look like [[link text][description]]
10224 when LINK TEXT does not have a protocol like \"http:\" and does not look
10225 like a filename (e.g. \"./blue.png\").
10227 These functions will be called *before* Org attempts to resolve the
10228 link by doing text searches in the current buffer - so if you want a
10229 link \"[[target]]\" to still find \"<<target>>\", your function should
10230 handle this as a special case.
10232 When the function does handle the link, it must return a non-nil value.
10233 If it decides that it is not responsible for this link, it must return
10234 nil to indicate that that Org-mode can continue with other options
10235 like exact and fuzzy text search.")
10237 (defun org-next-link (&optional search-backward)
10238 "Move forward to the next link.
10239 If the link is in hidden text, expose it."
10240 (interactive "P")
10241 (when (and org-link-search-failed (eq this-command last-command))
10242 (goto-char (point-min))
10243 (message "Link search wrapped back to beginning of buffer"))
10244 (setq org-link-search-failed nil)
10245 (let* ((pos (point))
10246 (ct (org-context))
10247 (a (assoc :link ct))
10248 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10249 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10250 ((looking-at org-any-link-re)
10251 ;; Don't stay stuck at link without an org-link face
10252 (forward-char (if search-backward -1 1))))
10253 (if (funcall srch-fun org-any-link-re nil t)
10254 (progn
10255 (goto-char (match-beginning 0))
10256 (if (outline-invisible-p) (org-show-context)))
10257 (goto-char pos)
10258 (setq org-link-search-failed t)
10259 (message "No further link found"))))
10261 (defun org-previous-link ()
10262 "Move backward to the previous link.
10263 If the link is in hidden text, expose it."
10264 (interactive)
10265 (funcall 'org-next-link t))
10267 (defun org-translate-link (s)
10268 "Translate a link string if a translation function has been defined."
10269 (if (and org-link-translation-function
10270 (fboundp org-link-translation-function)
10271 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10272 (progn
10273 (setq s (funcall org-link-translation-function
10274 (match-string 1 s) (match-string 2 s)))
10275 (concat (car s) ":" (cdr s)))
10278 (defun org-translate-link-from-planner (type path)
10279 "Translate a link from Emacs Planner syntax so that Org can follow it.
10280 This is still an experimental function, your mileage may vary."
10281 (cond
10282 ((member type '("http" "https" "news" "ftp"))
10283 ;; standard Internet links are the same.
10284 nil)
10285 ((and (equal type "irc") (string-match "^//" path))
10286 ;; Planner has two / at the beginning of an irc link, we have 1.
10287 ;; We should have zero, actually....
10288 (setq path (substring path 1)))
10289 ((and (equal type "lisp") (string-match "^/" path))
10290 ;; Planner has a slash, we do not.
10291 (setq type "elisp" path (substring path 1)))
10292 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10293 ;; A typical message link. Planner has the id after the final slash,
10294 ;; we separate it with a hash mark
10295 (setq path (concat (match-string 1 path) "#"
10296 (org-remove-angle-brackets (match-string 2 path))))))
10297 (cons type path))
10299 (defun org-find-file-at-mouse (ev)
10300 "Open file link or URL at mouse."
10301 (interactive "e")
10302 (mouse-set-point ev)
10303 (org-open-at-point 'in-emacs))
10305 (defun org-open-at-mouse (ev)
10306 "Open file link or URL at mouse.
10307 See the docstring of `org-open-file' for details."
10308 (interactive "e")
10309 (mouse-set-point ev)
10310 (if (eq major-mode 'org-agenda-mode)
10311 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10312 (org-open-at-point))
10314 (defvar org-window-config-before-follow-link nil
10315 "The window configuration before following a link.
10316 This is saved in case the need arises to restore it.")
10318 (defvar org-open-link-marker (make-marker)
10319 "Marker pointing to the location where `org-open-at-point' was called.")
10321 ;;;###autoload
10322 (defun org-open-at-point-global ()
10323 "Follow a link like Org-mode does.
10324 This command can be called in any mode to follow a link that has
10325 Org-mode syntax."
10326 (interactive)
10327 (org-run-like-in-org-mode 'org-open-at-point))
10329 ;;;###autoload
10330 (defun org-open-link-from-string (s &optional arg reference-buffer)
10331 "Open a link in the string S, as if it was in Org-mode."
10332 (interactive "sLink: \nP")
10333 (let ((reference-buffer (or reference-buffer (current-buffer))))
10334 (with-temp-buffer
10335 (let ((org-inhibit-startup (not reference-buffer)))
10336 (org-mode)
10337 (insert s)
10338 (goto-char (point-min))
10339 (when reference-buffer
10340 (setq org-link-abbrev-alist-local
10341 (with-current-buffer reference-buffer
10342 org-link-abbrev-alist-local)))
10343 (org-open-at-point arg reference-buffer)))))
10345 (defvar org-open-at-point-functions nil
10346 "Hook that is run when following a link at point.
10348 Functions in this hook must return t if they identify and follow
10349 a link at point. If they don't find anything interesting at point,
10350 they must return nil.")
10352 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10353 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10354 (defun org-open-at-point (&optional arg reference-buffer)
10355 "Open link at or after point.
10356 If there is no link at point, this function will search forward up to
10357 the end of the current line.
10358 Normally, files will be opened by an appropriate application. If the
10359 optional prefix argument ARG is non-nil, Emacs will visit the file.
10360 With a double prefix argument, try to open outside of Emacs, in the
10361 application the system uses for this file type."
10362 (interactive "P")
10363 ;; if in a code block, then open the block's results
10364 (unless (call-interactively #'org-babel-open-src-block-result)
10365 (org-load-modules-maybe)
10366 (move-marker org-open-link-marker (point))
10367 (setq org-window-config-before-follow-link (current-window-configuration))
10368 (org-remove-occur-highlights nil nil t)
10369 (cond
10370 ((and (org-at-heading-p)
10371 (not (org-at-timestamp-p t))
10372 (not (org-in-regexp
10373 (concat org-plain-link-re "\\|"
10374 org-bracket-link-regexp "\\|"
10375 org-angle-link-re "\\|"
10376 "[ \t]:[^ \t\n]+:[ \t]*$")))
10377 (not (get-text-property (point) 'org-linked-text)))
10378 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10379 (lk0 (car lkall))
10380 (lk (if (stringp lk0) (list lk0) lk0))
10381 (lkend (cdr lkall)))
10382 (mapcar (lambda(l)
10383 (search-forward l nil lkend)
10384 (goto-char (match-beginning 0))
10385 (org-open-at-point))
10386 lk))
10387 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10388 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10389 ((and (org-at-timestamp-p t)
10390 (not (org-in-regexp org-bracket-link-regexp)))
10391 (org-follow-timestamp-link))
10392 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10393 (not (org-in-regexp org-any-link-re)))
10394 (org-footnote-action))
10396 (let (type path link line search (pos (point)))
10397 (catch 'match
10398 (save-excursion
10399 (or (org-in-regexp org-plain-link-re)
10400 (skip-chars-forward "^]\n\r"))
10401 (when (org-in-regexp org-bracket-link-regexp 1)
10402 (setq link (org-extract-attributes
10403 (org-link-unescape (org-match-string-no-properties 1))))
10404 (while (string-match " *\n *" link)
10405 (setq link (replace-match " " t t link)))
10406 (setq link (org-link-expand-abbrev link))
10407 (cond
10408 ((or (file-name-absolute-p link)
10409 (string-match "^\\.\\.?/" link))
10410 (setq type "file" path link))
10411 ((string-match org-link-re-with-space3 link)
10412 (setq type (match-string 1 link) path (match-string 2 link)))
10413 ((string-match "^help:+\\(.+\\)" link)
10414 (setq type "help" path (match-string 1 link)))
10415 (t (setq type "thisfile" path link)))
10416 (throw 'match t)))
10418 (when (get-text-property (point) 'org-linked-text)
10419 (setq type "thisfile"
10420 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10421 (1+ (point)) (point))
10422 path (buffer-substring
10423 (or (previous-single-property-change pos 'org-linked-text)
10424 (point-min))
10425 (or (next-single-property-change pos 'org-linked-text)
10426 (point-max)))
10427 ;; Ensure we will search for a <<<radio>>> link, not
10428 ;; a simple reference like <<ref>>
10429 path (concat "<" path))
10430 (throw 'match t))
10432 (save-excursion
10433 (when (or (org-in-regexp org-angle-link-re)
10434 (let ((match (org-in-regexp org-plain-link-re)))
10435 ;; Check a plain link is not within a bracket link
10436 (and match
10437 (save-excursion
10438 (save-match-data
10439 (progn
10440 (goto-char (car match))
10441 (not (org-in-regexp org-bracket-link-regexp)))))))
10442 (let ((line_ending (save-excursion (end-of-line) (point))))
10443 ;; We are in a line before a plain or bracket link
10444 (or (re-search-forward org-plain-link-re line_ending t)
10445 (re-search-forward org-bracket-link-regexp line_ending t))))
10446 (setq type (match-string 1)
10447 path (org-link-unescape (match-string 2)))
10448 (throw 'match t)))
10449 (save-excursion
10450 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10451 (setq type "tags"
10452 path (match-string 1))
10453 (while (string-match ":" path)
10454 (setq path (replace-match "+" t t path)))
10455 (throw 'match t)))
10456 (when (org-in-regexp "<\\([^><\n]+\\)>")
10457 (setq type "tree-match"
10458 path (match-string 1))
10459 (throw 'match t)))
10460 (unless path
10461 (user-error "No link found"))
10463 ;; switch back to reference buffer
10464 ;; needed when if called in a temporary buffer through
10465 ;; org-open-link-from-string
10466 (with-current-buffer (or reference-buffer (current-buffer))
10468 ;; Remove any trailing spaces in path
10469 (if (string-match " +\\'" path)
10470 (setq path (replace-match "" t t path)))
10471 (if (and org-link-translation-function
10472 (fboundp org-link-translation-function))
10473 ;; Check if we need to translate the link
10474 (let ((tmp (funcall org-link-translation-function type path)))
10475 (setq type (car tmp) path (cdr tmp))))
10477 (cond
10479 ((assoc type org-link-protocols)
10480 (funcall (nth 1 (assoc type org-link-protocols)) path))
10482 ((equal type "help")
10483 (let ((f-or-v (intern path)))
10484 (cond ((fboundp f-or-v)
10485 (describe-function f-or-v))
10486 ((boundp f-or-v)
10487 (describe-variable f-or-v))
10488 (t (error "Not a known function or variable")))))
10490 ((equal type "mailto")
10491 (let ((cmd (car org-link-mailto-program))
10492 (args (cdr org-link-mailto-program)) args1
10493 (address path) (subject "") a)
10494 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10495 (setq address (match-string 1 path)
10496 subject (org-link-escape (match-string 2 path))))
10497 (while args
10498 (cond
10499 ((not (stringp (car args))) (push (pop args) args1))
10500 (t (setq a (pop args))
10501 (if (string-match "%a" a)
10502 (setq a (replace-match address t t a)))
10503 (if (string-match "%s" a)
10504 (setq a (replace-match subject t t a)))
10505 (push a args1))))
10506 (apply cmd (nreverse args1))))
10508 ((member type '("http" "https" "ftp" "news"))
10509 (browse-url
10510 (concat type ":"
10511 (if (org-string-match-p
10512 (concat "[[:nonascii:]"
10513 org-link-escape-chars-browser "]")
10514 path)
10515 (org-link-escape path org-link-escape-chars-browser)
10516 path))))
10518 ((string= type "doi")
10519 (browse-url
10520 (concat org-doi-server-url
10521 (if (org-string-match-p
10522 (concat "[[:nonascii:]"
10523 org-link-escape-chars-browser "]")
10524 path)
10525 (org-link-escape path org-link-escape-chars-browser)
10526 path))))
10528 ((member type '("message"))
10529 (browse-url (concat type ":" path)))
10531 ((string= type "tags")
10532 (org-tags-view arg path))
10534 ((string= type "tree-match")
10535 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10537 ((string= type "file")
10538 (if (string-match "::\\([0-9]+\\)\\'" path)
10539 (setq line (string-to-number (match-string 1 path))
10540 path (substring path 0 (match-beginning 0)))
10541 (if (string-match "::\\(.+\\)\\'" path)
10542 (setq search (match-string 1 path)
10543 path (substring path 0 (match-beginning 0)))))
10544 (if (string-match "[*?{]" (file-name-nondirectory path))
10545 (dired path)
10546 (org-open-file path arg line search)))
10548 ((string= type "shell")
10549 (let ((buf (generate-new-buffer "*Org Shell Output"))
10550 (cmd path))
10551 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10552 (string-match org-confirm-shell-link-not-regexp cmd))
10553 (not org-confirm-shell-link-function)
10554 (funcall org-confirm-shell-link-function
10555 (format "Execute \"%s\" in shell? "
10556 (org-add-props cmd nil
10557 'face 'org-warning))))
10558 (progn
10559 (message "Executing %s" cmd)
10560 (shell-command cmd buf)
10561 (if (featurep 'midnight)
10562 (setq clean-buffer-list-kill-buffer-names
10563 (cons buf clean-buffer-list-kill-buffer-names))))
10564 (error "Abort"))))
10566 ((string= type "elisp")
10567 (let ((cmd path))
10568 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10569 (string-match org-confirm-elisp-link-not-regexp cmd))
10570 (not org-confirm-elisp-link-function)
10571 (funcall org-confirm-elisp-link-function
10572 (format "Execute \"%s\" as elisp? "
10573 (org-add-props cmd nil
10574 'face 'org-warning))))
10575 (message "%s => %s" cmd
10576 (if (equal (string-to-char cmd) ?\()
10577 (eval (read cmd))
10578 (call-interactively (read cmd))))
10579 (error "Abort"))))
10581 ((and (string= type "thisfile")
10582 (or (run-hook-with-args-until-success
10583 'org-open-link-functions path)
10584 (and link
10585 (string-match "^id:" link)
10586 (or (featurep 'org-id) (require 'org-id))
10587 (progn
10588 (funcall (nth 1 (assoc "id" org-link-protocols))
10589 (substring path 3))
10590 t)))))
10592 ((string= type "thisfile")
10593 (if arg
10594 (switch-to-buffer-other-window
10595 (org-get-buffer-for-internal-link (current-buffer)))
10596 (org-mark-ring-push))
10597 (let ((cmd `(org-link-search
10598 ,path
10599 ,(cond ((equal arg '(4)) ''occur)
10600 ((equal arg '(16)) ''org-occur))
10601 ,pos)))
10602 (condition-case nil (let ((org-link-search-inhibit-query t))
10603 (eval cmd))
10604 (error (progn (widen) (eval cmd))))))
10606 (t (browse-url-at-point)))))))
10607 (move-marker org-open-link-marker nil)
10608 (run-hook-with-args 'org-follow-link-hook)))
10610 (defsubst org-uniquify (list)
10611 "Non-destructively remove duplicate elements from LIST."
10612 (let ((res (copy-sequence list))) (delete-dups res)))
10614 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10615 "Offer links in the current entry and return the selected link.
10616 If there is only one link, return it.
10617 If NTH is an integer, return the NTH link found.
10618 If ZERO is a string, check also this string for a link, and if
10619 there is one, return it."
10620 (with-current-buffer buffer
10621 (save-excursion
10622 (save-restriction
10623 (widen)
10624 (goto-char marker)
10625 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10626 "\\(" org-angle-link-re "\\)\\|"
10627 "\\(" org-plain-link-re "\\)"))
10628 (cnt ?0)
10629 (in-emacs (if (integerp nth) nil nth))
10630 have-zero end links link c)
10631 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10632 (push (match-string 0 zero) links)
10633 (setq cnt (1- cnt) have-zero t))
10634 (save-excursion
10635 (org-back-to-heading t)
10636 (setq end (save-excursion (outline-next-heading) (point)))
10637 (while (re-search-forward re end t)
10638 (push (match-string 0) links))
10639 (setq links (org-uniquify (reverse links))))
10640 (cond
10641 ((null links)
10642 (message "No links"))
10643 ((equal (length links) 1)
10644 (setq link (car links)))
10645 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10646 (setq link (nth (if have-zero nth (1- nth)) links)))
10647 (t ; we have to select a link
10648 (save-excursion
10649 (save-window-excursion
10650 (delete-other-windows)
10651 (with-output-to-temp-buffer "*Select Link*"
10652 (mapc (lambda (l)
10653 (if (not (string-match org-bracket-link-regexp l))
10654 (princ (format "[%c] %s\n" (incf cnt)
10655 (org-remove-angle-brackets l)))
10656 (if (match-end 3)
10657 (princ (format "[%c] %s (%s)\n" (incf cnt)
10658 (match-string 3 l) (match-string 1 l)))
10659 (princ (format "[%c] %s\n" (incf cnt)
10660 (match-string 1 l))))))
10661 links))
10662 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10663 (message "Select link to open, RET to open all:")
10664 (setq c (read-char-exclusive))
10665 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10666 (when (equal c ?q) (error "Abort"))
10667 (if (equal c ?\C-m)
10668 (setq link links)
10669 (setq nth (- c ?0))
10670 (if have-zero (setq nth (1+ nth)))
10671 (unless (and (integerp nth) (>= (length links) nth))
10672 (user-error "Invalid link selection"))
10673 (setq link (nth (1- nth) links)))))
10674 (cons link end))))))
10676 ;; Add special file links that specify the way of opening
10678 (org-add-link-type "file+sys" 'org-open-file-with-system)
10679 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10680 (defun org-open-file-with-system (path)
10681 "Open file at PATH using the system way of opening it."
10682 (org-open-file path 'system))
10683 (defun org-open-file-with-emacs (path)
10684 "Open file at PATH in Emacs."
10685 (org-open-file path 'emacs))
10688 ;;; File search
10690 (defvar org-create-file-search-functions nil
10691 "List of functions to construct the right search string for a file link.
10692 These functions are called in turn with point at the location to
10693 which the link should point.
10695 A function in the hook should first test if it would like to
10696 handle this file type, for example by checking the `major-mode'
10697 or the file extension. If it decides not to handle this file, it
10698 should just return nil to give other functions a chance. If it
10699 does handle the file, it must return the search string to be used
10700 when following the link. The search string will be part of the
10701 file link, given after a double colon, and `org-open-at-point'
10702 will automatically search for it. If special measures must be
10703 taken to make the search successful, another function should be
10704 added to the companion hook `org-execute-file-search-functions',
10705 which see.
10707 A function in this hook may also use `setq' to set the variable
10708 `description' to provide a suggestion for the descriptive text to
10709 be used for this link when it gets inserted into an Org-mode
10710 buffer with \\[org-insert-link].")
10712 (defvar org-execute-file-search-functions nil
10713 "List of functions to execute a file search triggered by a link.
10715 Functions added to this hook must accept a single argument, the
10716 search string that was part of the file link, the part after the
10717 double colon. The function must first check if it would like to
10718 handle this search, for example by checking the `major-mode' or
10719 the file extension. If it decides not to handle this search, it
10720 should just return nil to give other functions a chance. If it
10721 does handle the search, it must return a non-nil value to keep
10722 other functions from trying.
10724 Each function can access the current prefix argument through the
10725 variable `current-prefix-arg'. Note that a single prefix is used
10726 to force opening a link in Emacs, so it may be good to only use a
10727 numeric or double prefix to guide the search function.
10729 In case this is needed, a function in this hook can also restore
10730 the window configuration before `org-open-at-point' was called using:
10732 (set-window-configuration org-window-config-before-follow-link)")
10734 (defun org-link-search (s &optional type avoid-pos stealth)
10735 "Search for a link search option.
10736 If S is surrounded by forward slashes, it is interpreted as a
10737 regular expression. In org-mode files, this will create an `org-occur'
10738 sparse tree. In ordinary files, `occur' will be used to list matches.
10739 If the current buffer is in `dired-mode', grep will be used to search
10740 in all files. If AVOID-POS is given, ignore matches near that position.
10742 When optional argument STEALTH is non-nil, do not modify
10743 visibility around point, thus ignoring
10744 `org-show-hierarchy-above', `org-show-following-heading' and
10745 `org-show-siblings' variables."
10746 (let ((case-fold-search t)
10747 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10748 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10749 (append '(("") (" ") ("\t") ("\n"))
10750 org-emphasis-alist)
10751 "\\|") "\\)"))
10752 (pos (point))
10753 (pre nil) (post nil)
10754 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10755 (cond
10756 ;; First check if there are any special search functions
10757 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10758 ;; Now try the builtin stuff
10759 ((and (equal (string-to-char s0) ?#)
10760 (> (length s0) 1)
10761 (save-excursion
10762 (goto-char (point-min))
10763 (and
10764 (re-search-forward
10765 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10766 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10767 (setq type 'dedicated
10768 pos (match-beginning 0))))
10769 ;; There is an exact target for this
10770 (goto-char pos)
10771 (org-back-to-heading t)))
10772 ((save-excursion
10773 (goto-char (point-min))
10774 (and
10775 (re-search-forward
10776 (concat "<<" (regexp-quote s0) ">>") nil t)
10777 (setq type 'dedicated
10778 pos (match-beginning 0))))
10779 ;; There is an exact target for this
10780 (goto-char pos))
10781 ((save-excursion
10782 (goto-char (point-min))
10783 (and
10784 (re-search-forward
10785 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10786 (setq type 'dedicated pos (match-beginning 0))))
10787 ;; Found an element with a matching #+name affiliated keyword.
10788 (goto-char pos))
10789 ((and (string-match "^(\\(.*\\))$" s0)
10790 (save-excursion
10791 (goto-char (point-min))
10792 (and
10793 (re-search-forward
10794 (concat "[^[]" (regexp-quote
10795 (format org-coderef-label-format
10796 (match-string 1 s0))))
10797 nil t)
10798 (setq type 'dedicated
10799 pos (1+ (match-beginning 0))))))
10800 ;; There is a coderef target for this
10801 (goto-char pos))
10802 ((string-match "^/\\(.*\\)/$" s)
10803 ;; A regular expression
10804 (cond
10805 ((derived-mode-p 'org-mode)
10806 (org-occur (match-string 1 s)))
10807 (t (org-do-occur (match-string 1 s)))))
10808 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10809 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10810 (goto-char (point-min))
10811 (cond
10812 ((let (case-fold-search)
10813 (re-search-forward (format org-complex-heading-regexp-format
10814 (regexp-quote s))
10815 nil t))
10816 ;; OK, found a match
10817 (setq type 'dedicated)
10818 (goto-char (match-beginning 0)))
10819 ((and (not org-link-search-inhibit-query)
10820 (eq org-link-search-must-match-exact-headline 'query-to-create)
10821 (y-or-n-p "No match - create this as a new heading? "))
10822 (goto-char (point-max))
10823 (or (bolp) (newline))
10824 (insert "* " s "\n")
10825 (beginning-of-line 0))
10827 (goto-char pos)
10828 (error "No match"))))
10830 ;; A normal search string
10831 (when (equal (string-to-char s) ?*)
10832 ;; Anchor on headlines, post may include tags.
10833 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10834 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10835 s (substring s 1)))
10836 (remove-text-properties
10837 0 (length s)
10838 '(face nil mouse-face nil keymap nil fontified nil) s)
10839 ;; Make a series of regular expressions to find a match
10840 (setq words (org-split-string s "[ \n\r\t]+")
10842 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10843 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10844 "\\)" markers)
10845 re2a_ (concat "\\(" (mapconcat 'downcase words
10846 "[ \t\r\n]+") "\\)[ \t\r\n]")
10847 re2a (concat "[ \t\r\n]" re2a_)
10848 re4_ (concat "\\(" (mapconcat 'downcase words
10849 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10850 re4 (concat "[^a-zA-Z_]" re4_)
10852 re1 (concat pre re2 post)
10853 re3 (concat pre (if pre re4_ re4) post)
10854 re5 (concat pre ".*" re4)
10855 re2 (concat pre re2)
10856 re2a (concat pre (if pre re2a_ re2a))
10857 re4 (concat pre (if pre re4_ re4))
10858 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10859 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10860 re5 "\\)"))
10861 (cond
10862 ((eq type 'org-occur) (org-occur reall))
10863 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10864 (t (goto-char (point-min))
10865 (setq type 'fuzzy)
10866 (if (or (and (org-search-not-self 1 re0 nil t)
10867 (setq type 'dedicated))
10868 (org-search-not-self 1 re1 nil t)
10869 (org-search-not-self 1 re2 nil t)
10870 (org-search-not-self 1 re2a nil t)
10871 (org-search-not-self 1 re3 nil t)
10872 (org-search-not-self 1 re4 nil t)
10873 (org-search-not-self 1 re5 nil t))
10874 (goto-char (match-beginning 1))
10875 (goto-char pos)
10876 (error "No match"))))))
10877 (and (derived-mode-p 'org-mode)
10878 (not stealth)
10879 (org-show-context 'link-search))
10880 type))
10882 (defun org-search-not-self (group &rest args)
10883 "Execute `re-search-forward', but only accept matches that do not
10884 enclose the position of `org-open-link-marker'."
10885 (let ((m org-open-link-marker))
10886 (catch 'exit
10887 (while (apply 're-search-forward args)
10888 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10889 (goto-char (match-end group))
10890 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10891 (> (match-beginning 0) (marker-position m))
10892 (< (match-end 0) (marker-position m)))
10893 (save-match-data
10894 (or (not (org-in-regexp
10895 org-bracket-link-analytic-regexp 1))
10896 (not (match-end 4)) ; no description
10897 (and (<= (match-beginning 4) (point))
10898 (>= (match-end 4) (point))))))
10899 (throw 'exit (point))))))))
10901 (defun org-get-buffer-for-internal-link (buffer)
10902 "Return a buffer to be used for displaying the link target of internal links."
10903 (cond
10904 ((not org-display-internal-link-with-indirect-buffer)
10905 buffer)
10906 ((string-match "(Clone)$" (buffer-name buffer))
10907 (message "Buffer is already a clone, not making another one")
10908 ;; we also do not modify visibility in this case
10909 buffer)
10910 (t ; make a new indirect buffer for displaying the link
10911 (let* ((bn (buffer-name buffer))
10912 (ibn (concat bn "(Clone)"))
10913 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10914 (with-current-buffer ib (org-overview))
10915 ib))))
10917 (defun org-do-occur (regexp &optional cleanup)
10918 "Call the Emacs command `occur'.
10919 If CLEANUP is non-nil, remove the printout of the regular expression
10920 in the *Occur* buffer. This is useful if the regex is long and not useful
10921 to read."
10922 (occur regexp)
10923 (when cleanup
10924 (let ((cwin (selected-window)) win beg end)
10925 (when (setq win (get-buffer-window "*Occur*"))
10926 (select-window win))
10927 (goto-char (point-min))
10928 (when (re-search-forward "match[a-z]+" nil t)
10929 (setq beg (match-end 0))
10930 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10931 (setq end (1- (match-beginning 0)))))
10932 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10933 (goto-char (point-min))
10934 (select-window cwin))))
10936 ;;; The mark ring for links jumps
10938 (defvar org-mark-ring nil
10939 "Mark ring for positions before jumps in Org-mode.")
10940 (defvar org-mark-ring-last-goto nil
10941 "Last position in the mark ring used to go back.")
10942 ;; Fill and close the ring
10943 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10944 (loop for i from 1 to org-mark-ring-length do
10945 (push (make-marker) org-mark-ring))
10946 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10947 org-mark-ring)
10949 (defun org-mark-ring-push (&optional pos buffer)
10950 "Put the current position or POS into the mark ring and rotate it."
10951 (interactive)
10952 (setq pos (or pos (point)))
10953 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10954 (move-marker (car org-mark-ring)
10955 (or pos (point))
10956 (or buffer (current-buffer)))
10957 (message "%s"
10958 (substitute-command-keys
10959 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10961 (defun org-mark-ring-goto (&optional n)
10962 "Jump to the previous position in the mark ring.
10963 With prefix arg N, jump back that many stored positions. When
10964 called several times in succession, walk through the entire ring.
10965 Org-mode commands jumping to a different position in the current file,
10966 or to another Org-mode file, automatically push the old position
10967 onto the ring."
10968 (interactive "p")
10969 (let (p m)
10970 (if (eq last-command this-command)
10971 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10972 (setq p org-mark-ring))
10973 (setq org-mark-ring-last-goto p)
10974 (setq m (car p))
10975 (org-pop-to-buffer-same-window (marker-buffer m))
10976 (goto-char m)
10977 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10979 (defun org-remove-angle-brackets (s)
10980 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10981 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10983 (defun org-add-angle-brackets (s)
10984 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10985 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10987 (defun org-remove-double-quotes (s)
10988 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10989 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10992 ;;; Following specific links
10994 (defun org-follow-timestamp-link ()
10995 "Open an agenda view for the time-stamp date/range at point."
10996 (cond
10997 ((org-at-date-range-p t)
10998 (let ((org-agenda-start-on-weekday)
10999 (t1 (match-string 1))
11000 (t2 (match-string 2)) tt1 tt2)
11001 (setq tt1 (time-to-days (org-time-string-to-time t1))
11002 tt2 (time-to-days (org-time-string-to-time t2)))
11003 (let ((org-agenda-buffer-tmp-name
11004 (format "*Org Agenda(a:%s)"
11005 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11006 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11007 ((org-at-timestamp-p t)
11008 (let ((org-agenda-buffer-tmp-name
11009 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11010 (org-agenda-list nil (time-to-days (org-time-string-to-time
11011 (substring (match-string 1) 0 10)))
11012 1)))
11013 (t (error "This should not happen"))))
11016 ;;; Following file links
11017 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11018 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11019 (declare-function mailcap-mime-info
11020 "mailcap" (string &optional request no-decode))
11021 (defvar org-wait nil)
11022 (defun org-open-file (path &optional in-emacs line search)
11023 "Open the file at PATH.
11024 First, this expands any special file name abbreviations. Then the
11025 configuration variable `org-file-apps' is checked if it contains an
11026 entry for this file type, and if yes, the corresponding command is launched.
11028 If no application is found, Emacs simply visits the file.
11030 With optional prefix argument IN-EMACS, Emacs will visit the file.
11031 With a double \\[universal-argument] \\[universal-argument] \
11032 prefix arg, Org tries to avoid opening in Emacs
11033 and to use an external application to visit the file.
11035 Optional LINE specifies a line to go to, optional SEARCH a string
11036 to search for. If LINE or SEARCH is given, the file will be
11037 opened in Emacs, unless an entry from org-file-apps that makes
11038 use of groups in a regexp matches.
11040 If you want to change the way frames are used when following a
11041 link, please customize `org-link-frame-setup'.
11043 If the file does not exist, an error is thrown."
11044 (let* ((file (if (equal path "")
11045 buffer-file-name
11046 (substitute-in-file-name (expand-file-name path))))
11047 (file-apps (append org-file-apps (org-default-apps)))
11048 (apps (org-remove-if
11049 'org-file-apps-entry-match-against-dlink-p file-apps))
11050 (apps-dlink (org-remove-if-not
11051 'org-file-apps-entry-match-against-dlink-p file-apps))
11052 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11053 (dirp (if remp nil (file-directory-p file)))
11054 (file (if (and dirp org-open-directory-means-index-dot-org)
11055 (concat (file-name-as-directory file) "index.org")
11056 file))
11057 (a-m-a-p (assq 'auto-mode apps))
11058 (dfile (downcase file))
11059 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
11060 (link (cond ((and (eq line nil)
11061 (eq search nil))
11062 file)
11063 (line
11064 (concat file "::" (number-to-string line)))
11065 (search
11066 (concat file "::" search))))
11067 (dlink (downcase link))
11068 (old-buffer (current-buffer))
11069 (old-pos (point))
11070 (old-mode major-mode)
11071 ext cmd link-match-data)
11072 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11073 (setq ext (match-string 1 dfile))
11074 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11075 (setq ext (match-string 1 dfile))))
11076 (cond
11077 ((member in-emacs '((16) system))
11078 (setq cmd (cdr (assoc 'system apps))))
11079 (in-emacs (setq cmd 'emacs))
11081 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11082 (and dirp (cdr (assoc 'directory apps)))
11083 ; first, try matching against apps-dlink
11084 ; if we get a match here, store the match data for later
11085 (let ((match (assoc-default dlink apps-dlink
11086 'string-match)))
11087 (if match
11088 (progn (setq link-match-data (match-data))
11089 match)
11090 (progn (setq in-emacs (or in-emacs line search))
11091 nil))) ; if we have no match in apps-dlink,
11092 ; always open the file in emacs if line or search
11093 ; is given (for backwards compatibility)
11094 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11095 'string-match)
11096 (cdr (assoc ext apps))
11097 (cdr (assoc t apps))))))
11098 (when (eq cmd 'system)
11099 (setq cmd (cdr (assoc 'system apps))))
11100 (when (eq cmd 'default)
11101 (setq cmd (cdr (assoc t apps))))
11102 (when (eq cmd 'mailcap)
11103 (require 'mailcap)
11104 (mailcap-parse-mailcaps)
11105 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11106 (command (mailcap-mime-info mime-type)))
11107 (if (stringp command)
11108 (setq cmd command)
11109 (setq cmd 'emacs))))
11110 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11111 (not (file-exists-p file))
11112 (not org-open-non-existing-files))
11113 (user-error "No such file: %s" file))
11114 (cond
11115 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11116 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11117 (while (string-match "['\"]%s['\"]" cmd)
11118 (setq cmd (replace-match "%s" t t cmd)))
11119 (while (string-match "%s" cmd)
11120 (setq cmd (replace-match
11121 (save-match-data
11122 (shell-quote-argument
11123 (convert-standard-filename file)))
11124 t t cmd)))
11126 ;; Replace "%1", "%2" etc. in command with group matches from regex
11127 (save-match-data
11128 (let ((match-index 1)
11129 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11130 (set-match-data link-match-data)
11131 (while (<= match-index number-of-groups)
11132 (let ((regex (concat "%" (number-to-string match-index)))
11133 (replace-with (match-string match-index dlink)))
11134 (while (string-match regex cmd)
11135 (setq cmd (replace-match replace-with t t cmd))))
11136 (setq match-index (+ match-index 1)))))
11138 (save-window-excursion
11139 (message "Running %s...done" cmd)
11140 (start-process-shell-command cmd nil cmd)
11141 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11142 ((or (stringp cmd)
11143 (eq cmd 'emacs))
11144 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11145 (widen)
11146 (if line (org-goto-line line)
11147 (if search (org-link-search search))))
11148 ((consp cmd)
11149 (let ((file (convert-standard-filename file)))
11150 (save-match-data
11151 (set-match-data link-match-data)
11152 (eval cmd))))
11153 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11154 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11155 (or (not (equal old-buffer (current-buffer)))
11156 (not (equal old-pos (point))))
11157 (org-mark-ring-push old-pos old-buffer))))
11159 (defun org-file-apps-entry-match-against-dlink-p (entry)
11160 "This function returns non-nil if `entry' uses a regular
11161 expression which should be matched against the whole link by
11162 org-open-file.
11164 It assumes that is the case when the entry uses a regular
11165 expression which has at least one grouping construct and the
11166 action is either a lisp form or a command string containing
11167 '%1', i.e. using at least one subexpression match as a
11168 parameter."
11169 (let ((selector (car entry))
11170 (action (cdr entry)))
11171 (if (stringp selector)
11172 (and (> (regexp-opt-depth selector) 0)
11173 (or (and (stringp action)
11174 (string-match "%[0-9]" action))
11175 (consp action)))
11176 nil)))
11178 (defun org-default-apps ()
11179 "Return the default applications for this operating system."
11180 (cond
11181 ((eq system-type 'darwin)
11182 org-file-apps-defaults-macosx)
11183 ((eq system-type 'windows-nt)
11184 org-file-apps-defaults-windowsnt)
11185 (t org-file-apps-defaults-gnu)))
11187 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11188 "Convert extensions to regular expressions in the cars of LIST.
11189 Also, weed out any non-string entries, because the return value is used
11190 only for regexp matching.
11191 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11192 point to the symbol `emacs', indicating that the file should
11193 be opened in Emacs."
11194 (append
11195 (delq nil
11196 (mapcar (lambda (x)
11197 (if (not (stringp (car x)))
11199 (if (string-match "\\W" (car x))
11201 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11202 list))
11203 (if add-auto-mode
11204 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11206 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11207 (defun org-file-remote-p (file)
11208 "Test whether FILE specifies a location on a remote system.
11209 Return non-nil if the location is indeed remote.
11211 For example, the filename \"/user@host:/foo\" specifies a location
11212 on the system \"/user@host:\"."
11213 (cond ((fboundp 'file-remote-p)
11214 (file-remote-p file))
11215 ((fboundp 'tramp-handle-file-remote-p)
11216 (tramp-handle-file-remote-p file))
11217 ((and (boundp 'ange-ftp-name-format)
11218 (string-match (car ange-ftp-name-format) file))
11219 t)))
11222 ;;;; Refiling
11224 (defun org-get-org-file ()
11225 "Read a filename, with default directory `org-directory'."
11226 (let ((default (or org-default-notes-file remember-data-file)))
11227 (read-file-name (format "File name [%s]: " default)
11228 (file-name-as-directory org-directory)
11229 default)))
11231 (defun org-notes-order-reversed-p ()
11232 "Check if the current file should receive notes in reversed order."
11233 (cond
11234 ((not org-reverse-note-order) nil)
11235 ((eq t org-reverse-note-order) t)
11236 ((not (listp org-reverse-note-order)) nil)
11237 (t (catch 'exit
11238 (let ((all org-reverse-note-order)
11239 entry)
11240 (while (setq entry (pop all))
11241 (if (string-match (car entry) buffer-file-name)
11242 (throw 'exit (cdr entry))))
11243 nil)))))
11245 (defvar org-refile-target-table nil
11246 "The list of refile targets, created by `org-refile'.")
11248 (defvar org-agenda-new-buffers nil
11249 "Buffers created to visit agenda files.")
11251 (defvar org-refile-cache nil
11252 "Cache for refile targets.")
11254 (defvar org-refile-markers nil
11255 "All the markers used for caching refile locations.")
11257 (defun org-refile-marker (pos)
11258 "Get a new refile marker, but only if caching is in use."
11259 (if (not org-refile-use-cache)
11261 (let ((m (make-marker)))
11262 (move-marker m pos)
11263 (push m org-refile-markers)
11264 m)))
11266 (defun org-refile-cache-clear ()
11267 "Clear the refile cache and disable all the markers."
11268 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11269 (setq org-refile-markers nil)
11270 (setq org-refile-cache nil)
11271 (message "Refile cache has been cleared"))
11273 (defun org-refile-cache-check-set (set)
11274 "Check if all the markers in the cache still have live buffers."
11275 (let (marker)
11276 (catch 'exit
11277 (while (and set (setq marker (nth 3 (pop set))))
11278 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11279 (when (and marker (null (marker-buffer marker)))
11280 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11281 (sit-for 3)
11282 (throw 'exit nil)))
11283 t)))
11285 (defun org-refile-cache-put (set &rest identifiers)
11286 "Push the refile targets SET into the cache, under IDENTIFIERS."
11287 (let* ((key (sha1 (prin1-to-string identifiers)))
11288 (entry (assoc key org-refile-cache)))
11289 (if entry
11290 (setcdr entry set)
11291 (push (cons key set) org-refile-cache))))
11293 (defun org-refile-cache-get (&rest identifiers)
11294 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11295 (cond
11296 ((not org-refile-cache) nil)
11297 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11299 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11300 org-refile-cache))))
11301 (and set (org-refile-cache-check-set set) set)))))
11303 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11304 "Produce a table with refile targets."
11305 (let ((case-fold-search nil)
11306 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11307 (entries (or org-refile-targets '((nil . (:level . 1)))))
11308 targets tgs txt re files f desc descre fast-path-p level pos0)
11309 (message "Getting targets...")
11310 (with-current-buffer (or default-buffer (current-buffer))
11311 (while (setq entry (pop entries))
11312 (setq files (car entry) desc (cdr entry))
11313 (setq fast-path-p nil)
11314 (cond
11315 ((null files) (setq files (list (current-buffer))))
11316 ((eq files 'org-agenda-files)
11317 (setq files (org-agenda-files 'unrestricted)))
11318 ((and (symbolp files) (fboundp files))
11319 (setq files (funcall files)))
11320 ((and (symbolp files) (boundp files))
11321 (setq files (symbol-value files))))
11322 (if (stringp files) (setq files (list files)))
11323 (cond
11324 ((eq (car desc) :tag)
11325 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11326 ((eq (car desc) :todo)
11327 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11328 ((eq (car desc) :regexp)
11329 (setq descre (cdr desc)))
11330 ((eq (car desc) :level)
11331 (setq descre (concat "^\\*\\{" (number-to-string
11332 (if org-odd-levels-only
11333 (1- (* 2 (cdr desc)))
11334 (cdr desc)))
11335 "\\}[ \t]")))
11336 ((eq (car desc) :maxlevel)
11337 (setq fast-path-p t)
11338 (setq descre (concat "^\\*\\{1," (number-to-string
11339 (if org-odd-levels-only
11340 (1- (* 2 (cdr desc)))
11341 (cdr desc)))
11342 "\\}[ \t]")))
11343 (t (error "Bad refiling target description %s" desc)))
11344 (while (setq f (pop files))
11345 (with-current-buffer
11346 (if (bufferp f) f (org-get-agenda-file-buffer f))
11348 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11349 (progn
11350 (if (bufferp f) (setq f (buffer-file-name
11351 (buffer-base-buffer f))))
11352 (setq f (and f (expand-file-name f)))
11353 (if (eq org-refile-use-outline-path 'file)
11354 (push (list (file-name-nondirectory f) f nil nil) tgs))
11355 (save-excursion
11356 (save-restriction
11357 (widen)
11358 (goto-char (point-min))
11359 (while (re-search-forward descre nil t)
11360 (goto-char (setq pos0 (point-at-bol)))
11361 (catch 'next
11362 (when org-refile-target-verify-function
11363 (save-match-data
11364 (or (funcall org-refile-target-verify-function)
11365 (throw 'next t))))
11366 (when (and (looking-at org-complex-heading-regexp)
11367 (not (member (match-string 4) excluded-entries))
11368 (match-string 4))
11369 (setq level (org-reduced-level
11370 (- (match-end 1) (match-beginning 1)))
11371 txt (org-link-display-format (match-string 4))
11372 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11373 re (format org-complex-heading-regexp-format
11374 (regexp-quote (match-string 4))))
11375 (when org-refile-use-outline-path
11376 (setq txt (mapconcat
11377 'org-protect-slash
11378 (append
11379 (if (eq org-refile-use-outline-path
11380 'file)
11381 (list (file-name-nondirectory
11382 (buffer-file-name
11383 (buffer-base-buffer))))
11384 (if (eq org-refile-use-outline-path
11385 'full-file-path)
11386 (list (buffer-file-name
11387 (buffer-base-buffer)))))
11388 (org-get-outline-path fast-path-p
11389 level txt)
11390 (list txt))
11391 "/")))
11392 (push (list txt f re (org-refile-marker (point)))
11393 tgs)))
11394 (when (= (point) pos0)
11395 ;; verification function has not moved point
11396 (goto-char (point-at-eol))))))))
11397 (when org-refile-use-cache
11398 (org-refile-cache-put tgs (buffer-file-name) descre))
11399 (setq targets (append tgs targets))))))
11400 (message "Getting targets...done")
11401 (nreverse targets)))
11403 (defun org-protect-slash (s)
11404 (while (string-match "/" s)
11405 (setq s (replace-match "\\" t t s)))
11408 (defvar org-olpa (make-vector 20 nil))
11410 (defun org-get-outline-path (&optional fastp level heading)
11411 "Return the outline path to the current entry, as a list.
11413 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11414 routine which makes outline path derivations for an entire file,
11415 avoiding backtracing. Refile target collection makes use of that."
11416 (if fastp
11417 (progn
11418 (if (> level 19)
11419 (error "Outline path failure, more than 19 levels"))
11420 (loop for i from level upto 19 do
11421 (aset org-olpa i nil))
11422 (prog1
11423 (delq nil (append org-olpa nil))
11424 (aset org-olpa level heading)))
11425 (let (rtn case-fold-search)
11426 (save-excursion
11427 (save-restriction
11428 (widen)
11429 (while (org-up-heading-safe)
11430 (when (looking-at org-complex-heading-regexp)
11431 (push (org-trim
11432 (replace-regexp-in-string
11433 ;; Remove statistical/checkboxes cookies
11434 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11435 (org-match-string-no-properties 4)))
11436 rtn)))
11437 rtn)))))
11439 (defun org-format-outline-path (path &optional width prefix separator)
11440 "Format the outline path PATH for display.
11441 WIDTH is the maximum number of characters that is available.
11442 PREFIX is a prefix to be included in the returned string,
11443 such as the file name.
11444 SEPARATOR is inserted between the different parts of the path,
11445 the default is \"/\"."
11446 (setq width (or width 79))
11447 (if prefix (setq width (- width (length prefix))))
11448 (if (not path)
11449 (or prefix "")
11450 (let* ((nsteps (length path))
11451 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11452 (maxwidth (if (<= total-width width)
11453 10000 ;; everything fits
11454 ;; we need to shorten the level headings
11455 (/ (- width nsteps) nsteps)))
11456 (org-odd-levels-only nil)
11457 (n 0)
11458 (total (1+ (length prefix))))
11459 (setq maxwidth (max maxwidth 10))
11460 (concat prefix
11461 (if prefix (or separator "/"))
11462 (mapconcat
11463 (lambda (h)
11464 (setq n (1+ n))
11465 (if (and (= n nsteps) (< maxwidth 10000))
11466 (setq maxwidth (- total-width total)))
11467 (if (< (length h) maxwidth)
11468 (progn (setq total (+ total (length h) 1)) h)
11469 (setq h (substring h 0 (- maxwidth 2))
11470 total (+ total maxwidth 1))
11471 (if (string-match "[ \t]+\\'" h)
11472 (setq h (substring h 0 (match-beginning 0))))
11473 (setq h (concat h "..")))
11474 (org-add-props h nil 'face
11475 (nth (% (1- n) org-n-level-faces)
11476 org-level-faces))
11478 path (or separator "/"))))))
11480 (defun org-display-outline-path (&optional file current separator just-return-string)
11481 "Display the current outline path in the echo area.
11483 If FILE is non-nil, prepend the output with the file name.
11484 If CURRENT is non-nil, append the current heading to the output.
11485 SEPARATOR is passed through to `org-format-outline-path'. It separates
11486 the different parts of the path and defaults to \"/\".
11487 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11488 (interactive "P")
11489 (let* (case-fold-search
11490 (bfn (buffer-file-name (buffer-base-buffer)))
11491 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11492 res)
11493 (if current (setq path (append path
11494 (save-excursion
11495 (org-back-to-heading t)
11496 (if (looking-at org-complex-heading-regexp)
11497 (list (match-string 4)))))))
11498 (setq res
11499 (org-format-outline-path
11500 path
11501 (1- (frame-width))
11502 (and file bfn (concat (file-name-nondirectory bfn) separator))
11503 separator))
11504 (if just-return-string
11505 (org-no-properties res)
11506 (org-unlogged-message "%s" res))))
11508 (defvar org-refile-history nil
11509 "History for refiling operations.")
11511 (defvar org-after-refile-insert-hook nil
11512 "Hook run after `org-refile' has inserted its stuff at the new location.
11513 Note that this is still *before* the stuff will be removed from
11514 the *old* location.")
11516 (defvar org-capture-last-stored-marker)
11517 (defvar org-refile-keep nil
11518 "Non-nil means `org-refile' will copy instead of refile.")
11520 (defun org-copy ()
11521 "Like `org-refile', but copy."
11522 (interactive)
11523 (let ((org-refile-keep t))
11524 (funcall 'org-refile nil nil nil "Copy")))
11526 (defun org-refile (&optional goto default-buffer rfloc msg)
11527 "Move the entry or entries at point to another heading.
11528 The list of target headings is compiled using the information in
11529 `org-refile-targets', which see.
11531 At the target location, the entry is filed as a subitem of the target
11532 heading. Depending on `org-reverse-note-order', the new subitem will
11533 either be the first or the last subitem.
11535 If there is an active region, all entries in that region will be moved.
11536 However, the region must fulfill the requirement that the first heading
11537 is the first one sets the top-level of the moved text - at most siblings
11538 below it are allowed.
11540 With prefix arg GOTO, the command will only visit the target location
11541 and not actually move anything.
11543 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11544 go to the location where the last refiling operation has put the subtree.
11546 With a numeric prefix argument of `2', refile to the running clock.
11548 With a numeric prefix argument of `3', emulate `org-refile-keep'
11549 being set to `t' and copy to the target location, don't move it.
11550 Beware that keeping refiled entries may result in duplicated ID
11551 properties.
11553 RFLOC can be a refile location obtained in a different way.
11555 MSG is a string to replace \"Refile\" in the default prompt with
11556 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11558 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11560 If you are using target caching (see `org-refile-use-cache'),
11561 you have to clear the target cache in order to find new targets.
11562 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11563 prefix argument (`C-u C-u C-u C-c C-w')."
11565 (interactive "P")
11566 (if (member goto '(0 (64)))
11567 (org-refile-cache-clear)
11568 (let* ((actionmsg (cond (msg msg)
11569 ((equal goto 3) "Refile (and keep)")
11570 (t "Refile")))
11571 (cbuf (current-buffer))
11572 (regionp (org-region-active-p))
11573 (region-start (and regionp (region-beginning)))
11574 (region-end (and regionp (region-end)))
11575 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11576 (org-refile-keep (if (equal goto 3) t org-refile-keep))
11577 pos it nbuf file re level reversed)
11578 (setq last-command nil)
11579 (when regionp
11580 (goto-char region-start)
11581 (or (bolp) (goto-char (point-at-bol)))
11582 (setq region-start (point))
11583 (unless (or (org-kill-is-subtree-p
11584 (buffer-substring region-start region-end))
11585 (prog1 org-refile-active-region-within-subtree
11586 (let ((s (point-at-eol)))
11587 (org-toggle-heading)
11588 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11589 (user-error "The region is not a (sequence of) subtree(s)")))
11590 (if (equal goto '(16))
11591 (org-refile-goto-last-stored)
11592 (when (or
11593 (and (equal goto 2)
11594 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11595 (prog1
11596 (setq it (list (or org-clock-heading "running clock")
11597 (buffer-file-name
11598 (marker-buffer org-clock-hd-marker))
11600 (marker-position org-clock-hd-marker)))
11601 (setq goto nil)))
11602 (setq it (or rfloc
11603 (let (heading-text)
11604 (save-excursion
11605 (unless (and goto (listp goto))
11606 (org-back-to-heading t)
11607 (setq heading-text
11608 (nth 4 (org-heading-components))))
11610 (org-refile-get-location
11611 (cond ((and goto (listp goto)) "Goto")
11612 (regionp (concat actionmsg " region to"))
11613 (t (concat actionmsg " subtree \""
11614 heading-text "\" to")))
11615 default-buffer
11616 (and (not (equal '(4) goto))
11617 org-refile-allow-creating-parent-nodes)
11618 goto))))))
11619 (setq file (nth 1 it)
11620 re (nth 2 it)
11621 pos (nth 3 it))
11622 (if (and (not goto)
11624 (equal (buffer-file-name) file)
11625 (if regionp
11626 (and (>= pos region-start)
11627 (<= pos region-end))
11628 (and (>= pos (point))
11629 (< pos (save-excursion
11630 (org-end-of-subtree t t))))))
11631 (error "Cannot refile to position inside the tree or region"))
11633 (setq nbuf (or (find-buffer-visiting file)
11634 (find-file-noselect file)))
11635 (if (and goto (not (equal goto 3)))
11636 (progn
11637 (org-pop-to-buffer-same-window nbuf)
11638 (goto-char pos)
11639 (org-show-context 'org-goto))
11640 (if regionp
11641 (progn
11642 (org-kill-new (buffer-substring region-start region-end))
11643 (org-save-markers-in-region region-start region-end))
11644 (org-copy-subtree 1 nil t))
11645 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11646 (find-file-noselect file)))
11647 (setq reversed (org-notes-order-reversed-p))
11648 (save-excursion
11649 (save-restriction
11650 (widen)
11651 (if pos
11652 (progn
11653 (goto-char pos)
11654 (looking-at org-outline-regexp)
11655 (setq level (org-get-valid-level (funcall outline-level) 1))
11656 (goto-char
11657 (if reversed
11658 (or (outline-next-heading) (point-max))
11659 (or (save-excursion (org-get-next-sibling))
11660 (org-end-of-subtree t t)
11661 (point-max)))))
11662 (setq level 1)
11663 (if (not reversed)
11664 (goto-char (point-max))
11665 (goto-char (point-min))
11666 (or (outline-next-heading) (goto-char (point-max)))))
11667 (if (not (bolp)) (newline))
11668 (org-paste-subtree level)
11669 (when org-log-refile
11670 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11671 (unless (eq org-log-refile 'note)
11672 (save-excursion (org-add-log-note))))
11673 (and org-auto-align-tags
11674 (let ((org-loop-over-headlines-in-active-region nil))
11675 (org-set-tags nil t)))
11676 (let ((bookmark-name (plist-get org-bookmark-names-plist
11677 :last-refile)))
11678 (when bookmark-name
11679 (with-demoted-errors
11680 (bookmark-set bookmark-name))))
11681 ;; If we are refiling for capture, make sure that the
11682 ;; last-capture pointers point here
11683 (when (org-bound-and-true-p org-refile-for-capture)
11684 (let ((bookmark-name (plist-get org-bookmark-names-plist
11685 :last-capture-marker)))
11686 (when bookmark-name
11687 (with-demoted-errors
11688 (bookmark-set bookmark-name))))
11689 (move-marker org-capture-last-stored-marker (point)))
11690 (if (fboundp 'deactivate-mark) (deactivate-mark))
11691 (run-hooks 'org-after-refile-insert-hook))))
11692 (unless org-refile-keep
11693 (if regionp
11694 (delete-region (point) (+ (point) (- region-end region-start)))
11695 (delete-region
11696 (and (org-back-to-heading t) (point))
11697 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11698 (when (featurep 'org-inlinetask)
11699 (org-inlinetask-remove-END-maybe))
11700 (setq org-markers-to-move nil)
11701 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11703 (defun org-refile-goto-last-stored ()
11704 "Go to the location where the last refile was stored."
11705 (interactive)
11706 (bookmark-jump "org-refile-last-stored")
11707 (message "This is the location of the last refile"))
11709 (defun org-refile--get-location (refloc tbl)
11710 "When user refile to REFLOC, find the associated target in TBL.
11711 Also check `org-refile-target-table'."
11712 (car (delq
11714 (mapcar
11715 (lambda (r) (or (assoc r tbl)
11716 (assoc r org-refile-target-table)))
11717 (list (replace-regexp-in-string "/$" "" refloc)
11718 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11720 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11721 no-exclude)
11722 "Prompt the user for a refile location, using PROMPT.
11723 PROMPT should not be suffixed with a colon and a space, because
11724 this function appends the default value from
11725 `org-refile-history' automatically, if that is not empty.
11726 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11727 this is used for the GOTO interface."
11728 (let ((org-refile-targets org-refile-targets)
11729 (org-refile-use-outline-path org-refile-use-outline-path)
11730 excluded-entries)
11731 (when (and (derived-mode-p 'org-mode)
11732 (not org-refile-use-cache)
11733 (not no-exclude))
11734 (org-map-tree
11735 (lambda()
11736 (setq excluded-entries
11737 (append excluded-entries (list (org-get-heading t t)))))))
11738 (setq org-refile-target-table
11739 (org-refile-get-targets default-buffer excluded-entries)))
11740 (unless org-refile-target-table
11741 (user-error "No refile targets"))
11742 (let* ((cbuf (current-buffer))
11743 (partial-completion-mode nil)
11744 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11745 (cfunc (if (and org-refile-use-outline-path
11746 org-outline-path-complete-in-steps)
11747 'org-olpath-completing-read
11748 'org-icompleting-read))
11749 (extra (if org-refile-use-outline-path "/" ""))
11750 (cbnex (concat (buffer-name) extra))
11751 (filename (and cfn (expand-file-name cfn)))
11752 (tbl (mapcar
11753 (lambda (x)
11754 (if (and (not (member org-refile-use-outline-path
11755 '(file full-file-path)))
11756 (not (equal filename (nth 1 x))))
11757 (cons (concat (car x) extra " ("
11758 (file-name-nondirectory (nth 1 x)) ")")
11759 (cdr x))
11760 (cons (concat (car x) extra) (cdr x))))
11761 org-refile-target-table))
11762 (completion-ignore-case t)
11763 cdef
11764 (prompt (concat prompt
11765 (or (and (car org-refile-history)
11766 (concat " (default " (car org-refile-history) ")"))
11767 (and (assoc cbnex tbl) (setq cdef cbnex)
11768 (concat " (default " cbnex ")"))) ": "))
11769 pa answ parent-target child parent old-hist)
11770 (setq old-hist org-refile-history)
11771 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11772 nil 'org-refile-history (or cdef (car org-refile-history))))
11773 (if (setq pa (org-refile--get-location answ tbl))
11774 (progn
11775 (org-refile-check-position pa)
11776 (when (or (not org-refile-history)
11777 (not (eq old-hist org-refile-history))
11778 (not (equal (car pa) (car org-refile-history))))
11779 (setq org-refile-history
11780 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11781 org-refile-history
11782 (cdr org-refile-history))))
11783 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11784 (pop org-refile-history)))
11786 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11787 (progn
11788 (setq parent (match-string 1 answ)
11789 child (match-string 2 answ))
11790 (setq parent-target (org-refile--get-location parent tbl))
11791 (when (and parent-target
11792 (or (eq new-nodes t)
11793 (and (eq new-nodes 'confirm)
11794 (y-or-n-p (format "Create new node \"%s\"? "
11795 child)))))
11796 (org-refile-new-child parent-target child)))
11797 (user-error "Invalid target location")))))
11799 (declare-function org-string-nw-p "org-macs" (s))
11800 (defun org-refile-check-position (refile-pointer)
11801 "Check if the refile pointer matches the headline to which it points."
11802 (let* ((file (nth 1 refile-pointer))
11803 (re (nth 2 refile-pointer))
11804 (pos (nth 3 refile-pointer))
11805 buffer)
11806 (if (and (not (markerp pos)) (not file))
11807 (user-error "Please save the buffer to a file before refiling")
11808 (when (org-string-nw-p re)
11809 (setq buffer (if (markerp pos)
11810 (marker-buffer pos)
11811 (or (find-buffer-visiting file)
11812 (find-file-noselect file))))
11813 (with-current-buffer buffer
11814 (save-excursion
11815 (save-restriction
11816 (widen)
11817 (goto-char pos)
11818 (beginning-of-line 1)
11819 (unless (org-looking-at-p re)
11820 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11822 (defun org-refile-new-child (parent-target child)
11823 "Use refile target PARENT-TARGET to add new CHILD below it."
11824 (unless parent-target
11825 (error "Cannot find parent for new node"))
11826 (let ((file (nth 1 parent-target))
11827 (pos (nth 3 parent-target))
11828 level)
11829 (with-current-buffer (or (find-buffer-visiting file)
11830 (find-file-noselect file))
11831 (save-excursion
11832 (save-restriction
11833 (widen)
11834 (if pos
11835 (goto-char pos)
11836 (goto-char (point-max))
11837 (if (not (bolp)) (newline)))
11838 (when (looking-at org-outline-regexp)
11839 (setq level (funcall outline-level))
11840 (org-end-of-subtree t t))
11841 (org-back-over-empty-lines)
11842 (insert "\n" (make-string
11843 (if pos (org-get-valid-level level 1) 1) ?*)
11844 " " child "\n")
11845 (beginning-of-line 0)
11846 (list (concat (car parent-target) "/" child) file "" (point)))))))
11848 (defun org-olpath-completing-read (prompt collection &rest args)
11849 "Read an outline path like a file name."
11850 (let ((thetable collection)
11851 (org-completion-use-ido nil) ; does not work with ido.
11852 (org-completion-use-iswitchb nil)) ; or iswitchb
11853 (apply
11854 'org-icompleting-read prompt
11855 (lambda (string predicate &optional flag)
11856 (let (rtn r f (l (length string)))
11857 (cond
11858 ((eq flag nil)
11859 ;; try completion
11860 (try-completion string thetable))
11861 ((eq flag t)
11862 ;; all-completions
11863 (setq rtn (all-completions string thetable predicate))
11864 (mapcar
11865 (lambda (x)
11866 (setq r (substring x l))
11867 (if (string-match " ([^)]*)$" x)
11868 (setq f (match-string 0 x))
11869 (setq f ""))
11870 (if (string-match "/" r)
11871 (concat string (substring r 0 (match-end 0)) f)
11873 rtn))
11874 ((eq flag 'lambda)
11875 ;; exact match?
11876 (assoc string thetable)))))
11877 args)))
11879 ;;;; Dynamic blocks
11881 (defun org-find-dblock (name)
11882 "Find the first dynamic block with name NAME in the buffer.
11883 If not found, stay at current position and return nil."
11884 (let ((case-fold-search t) pos)
11885 (save-excursion
11886 (goto-char (point-min))
11887 (setq pos (and (re-search-forward
11888 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11889 (match-beginning 0))))
11890 (if pos (goto-char pos))
11891 pos))
11893 (defconst org-dblock-start-re
11894 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11895 "Matches the start line of a dynamic block, with parameters.")
11897 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11898 "Matches the end of a dynamic block.")
11900 (defun org-create-dblock (plist)
11901 "Create a dynamic block section, with parameters taken from PLIST.
11902 PLIST must contain a :name entry which is used as name of the block."
11903 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11904 (end-of-line 1)
11905 (newline))
11906 (let ((col (current-column))
11907 (name (plist-get plist :name)))
11908 (insert "#+BEGIN: " name)
11909 (while plist
11910 (if (eq (car plist) :name)
11911 (setq plist (cddr plist))
11912 (insert " " (prin1-to-string (pop plist)))))
11913 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11914 (beginning-of-line -2)))
11916 (defun org-prepare-dblock ()
11917 "Prepare dynamic block for refresh.
11918 This empties the block, puts the cursor at the insert position and returns
11919 the property list including an extra property :name with the block name."
11920 (unless (looking-at org-dblock-start-re)
11921 (user-error "Not at a dynamic block"))
11922 (let* ((begdel (1+ (match-end 0)))
11923 (name (org-no-properties (match-string 1)))
11924 (params (append (list :name name)
11925 (read (concat "(" (match-string 3) ")")))))
11926 (save-excursion
11927 (beginning-of-line 1)
11928 (skip-chars-forward " \t")
11929 (setq params (plist-put params :indentation-column (current-column))))
11930 (unless (re-search-forward org-dblock-end-re nil t)
11931 (error "Dynamic block not terminated"))
11932 (setq params
11933 (append params
11934 (list :content (buffer-substring
11935 begdel (match-beginning 0)))))
11936 (delete-region begdel (match-beginning 0))
11937 (goto-char begdel)
11938 (open-line 1)
11939 params))
11941 (defun org-map-dblocks (&optional command)
11942 "Apply COMMAND to all dynamic blocks in the current buffer.
11943 If COMMAND is not given, use `org-update-dblock'."
11944 (let ((cmd (or command 'org-update-dblock)))
11945 (save-excursion
11946 (goto-char (point-min))
11947 (while (re-search-forward org-dblock-start-re nil t)
11948 (goto-char (match-beginning 0))
11949 (save-excursion
11950 (condition-case nil
11951 (funcall cmd)
11952 (error (message "Error during update of dynamic block"))))
11953 (unless (re-search-forward org-dblock-end-re nil t)
11954 (error "Dynamic block not terminated"))))))
11956 (defun org-dblock-update (&optional arg)
11957 "User command for updating dynamic blocks.
11958 Update the dynamic block at point. With prefix ARG, update all dynamic
11959 blocks in the buffer."
11960 (interactive "P")
11961 (if arg
11962 (org-update-all-dblocks)
11963 (or (looking-at org-dblock-start-re)
11964 (org-beginning-of-dblock))
11965 (org-update-dblock)))
11967 (defun org-update-dblock ()
11968 "Update the dynamic block at point.
11969 This means to empty the block, parse for parameters and then call
11970 the correct writing function."
11971 (interactive)
11972 (save-excursion
11973 (let* ((win (selected-window))
11974 (pos (point))
11975 (line (org-current-line))
11976 (params (org-prepare-dblock))
11977 (name (plist-get params :name))
11978 (indent (plist-get params :indentation-column))
11979 (cmd (intern (concat "org-dblock-write:" name))))
11980 (message "Updating dynamic block `%s' at line %d..." name line)
11981 (funcall cmd params)
11982 (message "Updating dynamic block `%s' at line %d...done" name line)
11983 (goto-char pos)
11984 (when (and indent (> indent 0))
11985 (setq indent (make-string indent ?\ ))
11986 (save-excursion
11987 (select-window win)
11988 (org-beginning-of-dblock)
11989 (forward-line 1)
11990 (while (not (looking-at org-dblock-end-re))
11991 (insert indent)
11992 (beginning-of-line 2))
11993 (when (looking-at org-dblock-end-re)
11994 (and (looking-at "[ \t]+")
11995 (replace-match ""))
11996 (insert indent)))))))
11998 (defun org-beginning-of-dblock ()
11999 "Find the beginning of the dynamic block at point.
12000 Error if there is no such block at point."
12001 (let ((pos (point))
12002 beg)
12003 (end-of-line 1)
12004 (if (and (re-search-backward org-dblock-start-re nil t)
12005 (setq beg (match-beginning 0))
12006 (re-search-forward org-dblock-end-re nil t)
12007 (> (match-end 0) pos))
12008 (goto-char beg)
12009 (goto-char pos)
12010 (error "Not in a dynamic block"))))
12012 (defun org-update-all-dblocks ()
12013 "Update all dynamic blocks in the buffer.
12014 This function can be used in a hook."
12015 (interactive)
12016 (when (derived-mode-p 'org-mode)
12017 (org-map-dblocks 'org-update-dblock)))
12020 ;;;; Completion
12022 (declare-function org-export-backend-name "org-export" (cl-x))
12023 (declare-function org-export-backend-options "org-export" (cl-x))
12024 (defun org-get-export-keywords ()
12025 "Return a list of all currently understood export keywords.
12026 Export keywords include options, block names, attributes and
12027 keywords relative to each registered export back-end."
12028 (let (keywords)
12029 (dolist (backend
12030 (org-bound-and-true-p org-export--registered-backends)
12031 (delq nil keywords))
12032 ;; Back-end name (for keywords, like #+LATEX:)
12033 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12034 (dolist (option-entry (org-export-backend-options backend))
12035 ;; Back-end options.
12036 (push (nth 1 option-entry) keywords)))))
12038 (defconst org-options-keywords
12039 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12040 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12041 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12042 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12043 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12045 (defcustom org-structure-template-alist
12046 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC" "<src lang=\"?\">\n\n</src>")
12047 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE" "<example>\n?\n</example>")
12048 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE" "<quote>\n?\n</quote>")
12049 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE" "<verse>\n?\n</verse>")
12050 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM" "<verbatim>\n?\n</verbatim>")
12051 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER" "<center>\n?\n</center>")
12052 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
12053 "<literal style=\"latex\">\n?\n</literal>")
12054 ("L" "#+LaTeX: " "<literal style=\"latex\">?</literal>")
12055 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
12056 "<literal style=\"html\">\n?\n</literal>")
12057 ("H" "#+HTML: " "<literal style=\"html\">?</literal>")
12058 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII" "")
12059 ("A" "#+ASCII: " "")
12060 ("i" "#+INDEX: ?" "#+INDEX: ?")
12061 ("I" "#+INCLUDE: %file ?"
12062 "<include file=%file markup=\"?\">"))
12063 "Structure completion elements.
12064 This is a list of abbreviation keys and values. The value gets inserted
12065 if you type `<' followed by the key and then press the completion key,
12066 usually `M-TAB'. %file will be replaced by a file name after prompting
12067 for the file using completion. The cursor will be placed at the position
12068 of the `?` in the template.
12069 There are two templates for each key, the first uses the original Org syntax,
12070 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12071 the default when the /org-mtags.el/ module has been loaded. See also the
12072 variable `org-mtags-prefer-muse-templates'."
12073 :group 'org-completion
12074 :type '(repeat
12075 (list
12076 (string :tag "Key")
12077 (string :tag "Template")
12078 (string :tag "Muse Template"))))
12080 (defun org-try-structure-completion ()
12081 "Try to complete a structure template before point.
12082 This looks for strings like \"<e\" on an otherwise empty line and
12083 expands them."
12084 (let ((l (buffer-substring (point-at-bol) (point)))
12086 (when (and (looking-at "[ \t]*$")
12087 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12088 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12089 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12090 (match-beginning 1)) a)
12091 t)))
12093 (defun org-complete-expand-structure-template (start cell)
12094 "Expand a structure template."
12095 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
12096 (rpl (nth (if musep 2 1) cell))
12097 (ind ""))
12098 (delete-region start (point))
12099 (when (string-match "\\`#\\+" rpl)
12100 (cond
12101 ((bolp))
12102 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12103 (setq ind (buffer-substring (point-at-bol) (point))))
12104 (t (newline))))
12105 (setq start (point))
12106 (if (string-match "%file" rpl)
12107 (setq rpl (replace-match
12108 (concat
12109 "\""
12110 (save-match-data
12111 (abbreviate-file-name (read-file-name "Include file: ")))
12112 "\"")
12113 t t rpl)))
12114 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12115 (concat "\n" ind)))
12116 (insert rpl)
12117 (if (re-search-backward "\\?" start t) (delete-char 1))))
12119 ;;;; TODO, DEADLINE, Comments
12121 (defun org-toggle-comment ()
12122 "Change the COMMENT state of an entry."
12123 (interactive)
12124 (save-excursion
12125 (org-back-to-heading)
12126 (let (case-fold-search)
12127 (cond
12128 ((looking-at (format org-heading-keyword-regexp-format
12129 org-comment-string))
12130 (goto-char (match-end 1))
12131 (looking-at (concat " +" org-comment-string))
12132 (replace-match "" t t)
12133 (when (eolp) (insert " ")))
12134 ((looking-at org-outline-regexp)
12135 (goto-char (match-end 0))
12136 (insert org-comment-string " "))))))
12138 (defvar org-last-todo-state-is-todo nil
12139 "This is non-nil when the last TODO state change led to a TODO state.
12140 If the last change removed the TODO tag or switched to DONE, then
12141 this is nil.")
12143 (defvar org-setting-tags nil) ; dynamically skipped
12145 (defvar org-todo-setup-filter-hook nil
12146 "Hook for functions that pre-filter todo specs.
12147 Each function takes a todo spec and returns either nil or the spec
12148 transformed into canonical form." )
12150 (defvar org-todo-get-default-hook nil
12151 "Hook for functions that get a default item for todo.
12152 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12153 nil or a string to be used for the todo mark." )
12155 (defvar org-agenda-headline-snapshot-before-repeat)
12157 (defun org-current-effective-time ()
12158 "Return current time adjusted for `org-extend-today-until' variable."
12159 (let* ((ct (org-current-time))
12160 (dct (decode-time ct))
12161 (ct1
12162 (cond
12163 (org-use-last-clock-out-time-as-effective-time
12164 (or (org-clock-get-last-clock-out-time) ct))
12165 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12166 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12167 (t ct))))
12168 ct1))
12170 (defun org-todo-yesterday (&optional arg)
12171 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12172 (interactive "P")
12173 (if (eq major-mode 'org-agenda-mode)
12174 (apply 'org-agenda-todo-yesterday arg)
12175 (let* ((hour (third (decode-time
12176 (org-current-time))))
12177 (org-extend-today-until (1+ hour)))
12178 (org-todo arg))))
12180 (defvar org-block-entry-blocking ""
12181 "First entry preventing the TODO state change.")
12183 (defun org-todo (&optional arg)
12184 "Change the TODO state of an item.
12185 The state of an item is given by a keyword at the start of the heading,
12186 like
12187 *** TODO Write paper
12188 *** DONE Call mom
12190 The different keywords are specified in the variable `org-todo-keywords'.
12191 By default the available states are \"TODO\" and \"DONE\".
12192 So for this example: when the item starts with TODO, it is changed to DONE.
12193 When it starts with DONE, the DONE is removed. And when neither TODO nor
12194 DONE are present, add TODO at the beginning of the heading.
12196 With \\[universal-argument] prefix arg, use completion to determine the new \
12197 state.
12198 With numeric prefix arg, switch to that state.
12199 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12200 keywords (nextset).
12201 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12202 With a numeric prefix arg of 0, inhibit note taking for the change.
12204 For calling through lisp, arg is also interpreted in the following way:
12205 'none -> empty state
12206 \"\"(empty string) -> switch to empty state
12207 'done -> switch to DONE
12208 'nextset -> switch to the next set of keywords
12209 'previousset -> switch to the previous set of keywords
12210 \"WAITING\" -> switch to the specified keyword, but only if it
12211 really is a member of `org-todo-keywords'."
12212 (interactive "P")
12213 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12214 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12215 'region-start-level 'region))
12216 org-loop-over-headlines-in-active-region)
12217 (org-map-entries
12218 `(org-todo ,arg)
12219 org-loop-over-headlines-in-active-region
12220 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12221 (if (equal arg '(16)) (setq arg 'nextset))
12222 (let ((org-blocker-hook org-blocker-hook)
12223 commentp
12224 case-fold-search)
12225 (when (equal arg '(64))
12226 (setq arg nil org-blocker-hook nil))
12227 (when (and org-blocker-hook
12228 (or org-inhibit-blocking
12229 (org-entry-get nil "NOBLOCKING")))
12230 (setq org-blocker-hook nil))
12231 (save-excursion
12232 (catch 'exit
12233 (org-back-to-heading t)
12234 (when (looking-at (concat "^\\*+ " org-comment-string))
12235 (org-toggle-comment)
12236 (setq commentp t))
12237 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12238 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12239 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12240 (let* ((match-data (match-data))
12241 (startpos (point-at-bol))
12242 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12243 (org-log-done org-log-done)
12244 (org-log-repeat org-log-repeat)
12245 (org-todo-log-states org-todo-log-states)
12246 (org-inhibit-logging
12247 (if (equal arg 0)
12248 (progn (setq arg nil) 'note) org-inhibit-logging))
12249 (this (match-string 1))
12250 (hl-pos (match-beginning 0))
12251 (head (org-get-todo-sequence-head this))
12252 (ass (assoc head org-todo-kwd-alist))
12253 (interpret (nth 1 ass))
12254 (done-word (nth 3 ass))
12255 (final-done-word (nth 4 ass))
12256 (org-last-state (or this ""))
12257 (completion-ignore-case t)
12258 (member (member this org-todo-keywords-1))
12259 (tail (cdr member))
12260 (org-state (cond
12261 ((and org-todo-key-trigger
12262 (or (and (equal arg '(4))
12263 (eq org-use-fast-todo-selection 'prefix))
12264 (and (not arg) org-use-fast-todo-selection
12265 (not (eq org-use-fast-todo-selection
12266 'prefix)))))
12267 ;; Use fast selection
12268 (org-fast-todo-selection))
12269 ((and (equal arg '(4))
12270 (or (not org-use-fast-todo-selection)
12271 (not org-todo-key-trigger)))
12272 ;; Read a state with completion
12273 (org-icompleting-read
12274 "State: " (mapcar 'list org-todo-keywords-1)
12275 nil t))
12276 ((eq arg 'right)
12277 (if this
12278 (if tail (car tail) nil)
12279 (car org-todo-keywords-1)))
12280 ((eq arg 'left)
12281 (if (equal member org-todo-keywords-1)
12283 (if this
12284 (nth (- (length org-todo-keywords-1)
12285 (length tail) 2)
12286 org-todo-keywords-1)
12287 (org-last org-todo-keywords-1))))
12288 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12289 (setq arg nil))) ; hack to fall back to cycling
12290 (arg
12291 ;; user or caller requests a specific state
12292 (cond
12293 ((equal arg "") nil)
12294 ((eq arg 'none) nil)
12295 ((eq arg 'done) (or done-word (car org-done-keywords)))
12296 ((eq arg 'nextset)
12297 (or (car (cdr (member head org-todo-heads)))
12298 (car org-todo-heads)))
12299 ((eq arg 'previousset)
12300 (let ((org-todo-heads (reverse org-todo-heads)))
12301 (or (car (cdr (member head org-todo-heads)))
12302 (car org-todo-heads))))
12303 ((car (member arg org-todo-keywords-1)))
12304 ((stringp arg)
12305 (user-error "State `%s' not valid in this file" arg))
12306 ((nth (1- (prefix-numeric-value arg))
12307 org-todo-keywords-1))))
12308 ((null member) (or head (car org-todo-keywords-1)))
12309 ((equal this final-done-word) nil) ;; -> make empty
12310 ((null tail) nil) ;; -> first entry
12311 ((memq interpret '(type priority))
12312 (if (eq this-command last-command)
12313 (car tail)
12314 (if (> (length tail) 0)
12315 (or done-word (car org-done-keywords))
12316 nil)))
12318 (car tail))))
12319 (org-state (or
12320 (run-hook-with-args-until-success
12321 'org-todo-get-default-hook org-state org-last-state)
12322 org-state))
12323 (next (if org-state (concat " " org-state " ") " "))
12324 (change-plist (list :type 'todo-state-change :from this :to org-state
12325 :position startpos))
12326 dolog now-done-p)
12327 (when org-blocker-hook
12328 (setq org-last-todo-state-is-todo
12329 (not (member this org-done-keywords)))
12330 (unless (save-excursion
12331 (save-match-data
12332 (org-with-wide-buffer
12333 (run-hook-with-args-until-failure
12334 'org-blocker-hook change-plist))))
12335 (if (org-called-interactively-p 'interactive)
12336 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12337 this org-state org-block-entry-blocking)
12338 ;; fail silently
12339 (message "TODO state change from %s to %s blocked (by \"%s\")"
12340 this org-state org-block-entry-blocking)
12341 (throw 'exit nil))))
12342 (store-match-data match-data)
12343 (replace-match next t t)
12344 (unless (pos-visible-in-window-p hl-pos)
12345 (message "TODO state changed to %s" (org-trim next)))
12346 (unless head
12347 (setq head (org-get-todo-sequence-head org-state)
12348 ass (assoc head org-todo-kwd-alist)
12349 interpret (nth 1 ass)
12350 done-word (nth 3 ass)
12351 final-done-word (nth 4 ass)))
12352 (when (memq arg '(nextset previousset))
12353 (message "Keyword-Set %d/%d: %s"
12354 (- (length org-todo-sets) -1
12355 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12356 (length org-todo-sets)
12357 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12358 (setq org-last-todo-state-is-todo
12359 (not (member org-state org-done-keywords)))
12360 (setq now-done-p (and (member org-state org-done-keywords)
12361 (not (member this org-done-keywords))))
12362 (and logging (org-local-logging logging))
12363 (when (and (or org-todo-log-states org-log-done)
12364 (not (eq org-inhibit-logging t))
12365 (not (memq arg '(nextset previousset))))
12366 ;; we need to look at recording a time and note
12367 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12368 (nth 2 (assoc this org-todo-log-states))))
12369 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12370 (setq dolog 'time))
12371 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12372 (and org-state
12373 (member org-state org-not-done-keywords)
12374 (not (member this org-not-done-keywords))))
12375 ;; This is now a todo state and was not one before
12376 ;; If there was a CLOSED time stamp, get rid of it.
12377 (org-add-planning-info nil nil 'closed))
12378 (when (and now-done-p org-log-done)
12379 ;; It is now done, and it was not done before
12380 (org-add-planning-info 'closed (org-current-effective-time))
12381 (if (and (not dolog) (eq 'note org-log-done))
12382 (org-add-log-setup 'done org-state this 'findpos 'note)))
12383 (when (and org-state dolog)
12384 ;; This is a non-nil state, and we need to log it
12385 (org-add-log-setup 'state org-state this 'findpos dolog)))
12386 ;; Fixup tag positioning
12387 (org-todo-trigger-tag-changes org-state)
12388 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12389 (when org-provide-todo-statistics
12390 (org-update-parent-todo-statistics))
12391 (run-hooks 'org-after-todo-state-change-hook)
12392 (if (and arg (not (member org-state org-done-keywords)))
12393 (setq head (org-get-todo-sequence-head org-state)))
12394 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12395 ;; Do we need to trigger a repeat?
12396 (when now-done-p
12397 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12398 ;; This is for the agenda, take a snapshot of the headline.
12399 (save-match-data
12400 (setq org-agenda-headline-snapshot-before-repeat
12401 (org-get-heading))))
12402 (org-auto-repeat-maybe org-state))
12403 ;; Fixup cursor location if close to the keyword
12404 (if (and (outline-on-heading-p)
12405 (not (bolp))
12406 (save-excursion (beginning-of-line 1)
12407 (looking-at org-todo-line-regexp))
12408 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12409 (progn
12410 (goto-char (or (match-end 2) (match-end 1)))
12411 (and (looking-at " ") (just-one-space))))
12412 (when org-trigger-hook
12413 (save-excursion
12414 (run-hook-with-args 'org-trigger-hook change-plist)))
12415 (when commentp (org-toggle-comment))))))))
12417 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12418 "Block turning an entry into a TODO, using the hierarchy.
12419 This checks whether the current task should be blocked from state
12420 changes. Such blocking occurs when:
12422 1. The task has children which are not all in a completed state.
12424 2. A task has a parent with the property :ORDERED:, and there
12425 are siblings prior to the current task with incomplete
12426 status.
12428 3. The parent of the task is blocked because it has siblings that should
12429 be done first, or is child of a block grandparent TODO entry."
12431 (if (not org-enforce-todo-dependencies)
12432 t ; if locally turned off don't block
12433 (catch 'dont-block
12434 ;; If this is not a todo state change, or if this entry is already DONE,
12435 ;; do not block
12436 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12437 (member (plist-get change-plist :from)
12438 (cons 'done org-done-keywords))
12439 (member (plist-get change-plist :to)
12440 (cons 'todo org-not-done-keywords))
12441 (not (plist-get change-plist :to)))
12442 (throw 'dont-block t))
12443 ;; If this task has children, and any are undone, it's blocked
12444 (save-excursion
12445 (org-back-to-heading t)
12446 (let ((this-level (funcall outline-level)))
12447 (outline-next-heading)
12448 (let ((child-level (funcall outline-level)))
12449 (while (and (not (eobp))
12450 (> child-level this-level))
12451 ;; this todo has children, check whether they are all
12452 ;; completed
12453 (if (and (not (org-entry-is-done-p))
12454 (org-entry-is-todo-p))
12455 (progn (setq org-block-entry-blocking (org-get-heading))
12456 (throw 'dont-block nil)))
12457 (outline-next-heading)
12458 (setq child-level (funcall outline-level))))))
12459 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12460 ;; any previous siblings are undone, it's blocked
12461 (save-excursion
12462 (org-back-to-heading t)
12463 (let* ((pos (point))
12464 (parent-pos (and (org-up-heading-safe) (point))))
12465 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12466 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12467 (forward-line 1)
12468 (re-search-forward org-not-done-heading-regexp pos t))
12469 (setq org-block-entry-blocking (match-string 0))
12470 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12471 ;; Search further up the hierarchy, to see if an ancestor is blocked
12472 (while t
12473 (goto-char parent-pos)
12474 (if (not (looking-at org-not-done-heading-regexp))
12475 (throw 'dont-block t)) ; do not block, parent is not a TODO
12476 (setq pos (point))
12477 (setq parent-pos (and (org-up-heading-safe) (point)))
12478 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12479 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12480 (forward-line 1)
12481 (re-search-forward org-not-done-heading-regexp pos t)
12482 (setq org-block-entry-blocking (org-get-heading)))
12483 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12485 (defcustom org-track-ordered-property-with-tag nil
12486 "Should the ORDERED property also be shown as a tag?
12487 The ORDERED property decides if an entry should require subtasks to be
12488 completed in sequence. Since a property is not very visible, setting
12489 this option means that toggling the ORDERED property with the command
12490 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12491 not relevant for the behavior, but it makes things more visible.
12493 Note that toggling the tag with tags commands will not change the property
12494 and therefore not influence behavior!
12496 This can be t, meaning the tag ORDERED should be used, It can also be a
12497 string to select a different tag for this task."
12498 :group 'org-todo
12499 :type '(choice
12500 (const :tag "No tracking" nil)
12501 (const :tag "Track with ORDERED tag" t)
12502 (string :tag "Use other tag")))
12504 (defun org-toggle-ordered-property ()
12505 "Toggle the ORDERED property of the current entry.
12506 For better visibility, you can track the value of this property with a tag.
12507 See variable `org-track-ordered-property-with-tag'."
12508 (interactive)
12509 (let* ((t1 org-track-ordered-property-with-tag)
12510 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12511 (save-excursion
12512 (org-back-to-heading)
12513 (if (org-entry-get nil "ORDERED")
12514 (progn
12515 (org-delete-property "ORDERED" "PROPERTIES")
12516 (and tag (org-toggle-tag tag 'off))
12517 (message "Subtasks can be completed in arbitrary order"))
12518 (org-entry-put nil "ORDERED" "t")
12519 (and tag (org-toggle-tag tag 'on))
12520 (message "Subtasks must be completed in sequence")))))
12522 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12523 (defun org-block-todo-from-checkboxes (change-plist)
12524 "Block turning an entry into a TODO, using checkboxes.
12525 This checks whether the current task should be blocked from state
12526 changes because there are unchecked boxes in this entry."
12527 (if (not org-enforce-todo-checkbox-dependencies)
12528 t ; if locally turned off don't block
12529 (catch 'dont-block
12530 ;; If this is not a todo state change, or if this entry is already DONE,
12531 ;; do not block
12532 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12533 (member (plist-get change-plist :from)
12534 (cons 'done org-done-keywords))
12535 (member (plist-get change-plist :to)
12536 (cons 'todo org-not-done-keywords))
12537 (not (plist-get change-plist :to)))
12538 (throw 'dont-block t))
12539 ;; If this task has checkboxes that are not checked, it's blocked
12540 (save-excursion
12541 (org-back-to-heading t)
12542 (let ((beg (point)) end)
12543 (outline-next-heading)
12544 (setq end (point))
12545 (goto-char beg)
12546 (if (org-list-search-forward
12547 (concat (org-item-beginning-re)
12548 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12549 "\\[[- ]\\]")
12550 end t)
12551 (progn
12552 (if (boundp 'org-blocked-by-checkboxes)
12553 (setq org-blocked-by-checkboxes t))
12554 (throw 'dont-block nil)))))
12555 t))) ; do not block
12557 (defun org-entry-blocked-p ()
12558 "Is the current entry blocked?"
12559 (org-with-silent-modifications
12560 (if (org-entry-get nil "NOBLOCKING")
12561 nil ;; Never block this entry
12562 (not (run-hook-with-args-until-failure
12563 'org-blocker-hook
12564 (list :type 'todo-state-change
12565 :position (point)
12566 :from 'todo
12567 :to 'done))))))
12569 (defun org-update-statistics-cookies (all)
12570 "Update the statistics cookie, either from TODO or from checkboxes.
12571 This should be called with the cursor in a line with a statistics cookie."
12572 (interactive "P")
12573 (if all
12574 (progn
12575 (org-update-checkbox-count 'all)
12576 (org-map-entries 'org-update-parent-todo-statistics))
12577 (if (not (org-at-heading-p))
12578 (org-update-checkbox-count)
12579 (let ((pos (point-marker))
12580 end l1 l2)
12581 (ignore-errors (org-back-to-heading t))
12582 (if (not (org-at-heading-p))
12583 (org-update-checkbox-count)
12584 (setq l1 (org-outline-level))
12585 (setq end (save-excursion
12586 (outline-next-heading)
12587 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12588 (point)))
12589 (if (and (save-excursion
12590 (re-search-forward
12591 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12592 (not (save-excursion (re-search-forward
12593 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12594 (org-update-checkbox-count)
12595 (if (and l2 (> l2 l1))
12596 (progn
12597 (goto-char end)
12598 (org-update-parent-todo-statistics))
12599 (goto-char pos)
12600 (beginning-of-line 1)
12601 (while (re-search-forward
12602 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12603 (point-at-eol) t)
12604 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12605 (goto-char pos)
12606 (move-marker pos nil)))))
12608 (defvar org-entry-property-inherited-from) ;; defined below
12609 (defun org-update-parent-todo-statistics ()
12610 "Update any statistics cookie in the parent of the current headline.
12611 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12612 the entire subtree and this will travel up the hierarchy and update
12613 statistics everywhere."
12614 (let* ((prop (save-excursion (org-up-heading-safe)
12615 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12616 (recursive (or (not org-hierarchical-todo-statistics)
12617 (and prop (string-match "\\<recursive\\>" prop))))
12618 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12620 (first t)
12621 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12622 level ltoggle l1 new ndel
12623 (cnt-all 0) (cnt-done 0) is-percent kwd
12624 checkbox-beg ov ovs ove cookie-present)
12625 (catch 'exit
12626 (save-excursion
12627 (beginning-of-line 1)
12628 (setq ltoggle (funcall outline-level))
12629 ;; Three situations are to consider:
12631 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12632 ;; to the top-level ancestor on the headline;
12634 ;; 2. If parent has "recursive" property, repeat up to the
12635 ;; headline setting that property, taking inheritance into
12636 ;; account;
12638 ;; 3. Else, move up to direct parent and proceed only once.
12639 (while (and (setq level (org-up-heading-safe))
12640 (or recursive first)
12641 (>= (point) lim))
12642 (setq first nil cookie-present nil)
12643 (unless (and level
12644 (not (string-match
12645 "\\<checkbox\\>"
12646 (downcase (or (org-entry-get nil "COOKIE_DATA")
12647 "")))))
12648 (throw 'exit nil))
12649 (while (re-search-forward box-re (point-at-eol) t)
12650 (setq cnt-all 0 cnt-done 0 cookie-present t)
12651 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12652 (save-match-data
12653 (unless (outline-next-heading) (throw 'exit nil))
12654 (while (and (looking-at org-complex-heading-regexp)
12655 (> (setq l1 (length (match-string 1))) level))
12656 (setq kwd (and (or recursive (= l1 ltoggle))
12657 (match-string 2)))
12658 (if (or (eq org-provide-todo-statistics 'all-headlines)
12659 (and (listp org-provide-todo-statistics)
12660 (or (member kwd org-provide-todo-statistics)
12661 (member kwd org-done-keywords))))
12662 (setq cnt-all (1+ cnt-all))
12663 (if (eq org-provide-todo-statistics t)
12664 (and kwd (setq cnt-all (1+ cnt-all)))))
12665 (and (member kwd org-done-keywords)
12666 (setq cnt-done (1+ cnt-done)))
12667 (outline-next-heading)))
12668 (setq new
12669 (if is-percent
12670 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12671 (format "[%d/%d]" cnt-done cnt-all))
12672 ndel (- (match-end 0) checkbox-beg))
12673 ;; handle overlays when updating cookie from column view
12674 (when (setq ov (car (overlays-at checkbox-beg)))
12675 (setq ovs (overlay-start ov) ove (overlay-end ov))
12676 (delete-overlay ov))
12677 (goto-char checkbox-beg)
12678 (insert new)
12679 (delete-region (point) (+ (point) ndel))
12680 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12681 (when ov (move-overlay ov ovs ove)))
12682 (when cookie-present
12683 (run-hook-with-args 'org-after-todo-statistics-hook
12684 cnt-done (- cnt-all cnt-done))))))
12685 (run-hooks 'org-todo-statistics-hook)))
12687 (defvar org-after-todo-statistics-hook nil
12688 "Hook that is called after a TODO statistics cookie has been updated.
12689 Each function is called with two arguments: the number of not-done entries
12690 and the number of done entries.
12692 For example, the following function, when added to this hook, will switch
12693 an entry to DONE when all children are done, and back to TODO when new
12694 entries are set to a TODO status. Note that this hook is only called
12695 when there is a statistics cookie in the headline!
12697 (defun org-summary-todo (n-done n-not-done)
12698 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12699 (let (org-log-done org-log-states) ; turn off logging
12700 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12703 (defvar org-todo-statistics-hook nil
12704 "Hook that is run whenever Org thinks TODO statistics should be updated.
12705 This hook runs even if there is no statistics cookie present, in which case
12706 `org-after-todo-statistics-hook' would not run.")
12708 (defun org-todo-trigger-tag-changes (state)
12709 "Apply the changes defined in `org-todo-state-tags-triggers'."
12710 (let ((l org-todo-state-tags-triggers)
12711 changes)
12712 (when (or (not state) (equal state ""))
12713 (setq changes (append changes (cdr (assoc "" l)))))
12714 (when (and (stringp state) (> (length state) 0))
12715 (setq changes (append changes (cdr (assoc state l)))))
12716 (when (member state org-not-done-keywords)
12717 (setq changes (append changes (cdr (assoc 'todo l)))))
12718 (when (member state org-done-keywords)
12719 (setq changes (append changes (cdr (assoc 'done l)))))
12720 (dolist (c changes)
12721 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12723 (defun org-local-logging (value)
12724 "Get logging settings from a property VALUE."
12725 (let* (words w a)
12726 ;; directly set the variables, they are already local.
12727 (setq org-log-done nil
12728 org-log-repeat nil
12729 org-todo-log-states nil)
12730 (setq words (org-split-string value))
12731 (while (setq w (pop words))
12732 (cond
12733 ((setq a (assoc w org-startup-options))
12734 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12735 (set (nth 1 a) (nth 2 a))))
12736 ((setq a (org-extract-log-state-settings w))
12737 (and (member (car a) org-todo-keywords-1)
12738 (push a org-todo-log-states)))))))
12740 (defun org-get-todo-sequence-head (kwd)
12741 "Return the head of the TODO sequence to which KWD belongs.
12742 If KWD is not set, check if there is a text property remembering the
12743 right sequence."
12744 (let (p)
12745 (cond
12746 ((not kwd)
12747 (or (get-text-property (point-at-bol) 'org-todo-head)
12748 (progn
12749 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12750 nil (point-at-eol)))
12751 (get-text-property p 'org-todo-head))))
12752 ((not (member kwd org-todo-keywords-1))
12753 (car org-todo-keywords-1))
12754 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12756 (defun org-fast-todo-selection ()
12757 "Fast TODO keyword selection with single keys.
12758 Returns the new TODO keyword, or nil if no state change should occur."
12759 (let* ((fulltable org-todo-key-alist)
12760 (done-keywords org-done-keywords) ;; needed for the faces.
12761 (maxlen (apply 'max (mapcar
12762 (lambda (x)
12763 (if (stringp (car x)) (string-width (car x)) 0))
12764 fulltable)))
12765 (expert nil)
12766 (fwidth (+ maxlen 3 1 3))
12767 (ncol (/ (- (window-width) 4) fwidth))
12768 tg cnt e c tbl
12769 groups ingroup)
12770 (save-excursion
12771 (save-window-excursion
12772 (if expert
12773 (set-buffer (get-buffer-create " *Org todo*"))
12774 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12775 (erase-buffer)
12776 (org-set-local 'org-done-keywords done-keywords)
12777 (setq tbl fulltable cnt 0)
12778 (while (setq e (pop tbl))
12779 (cond
12780 ((equal e '(:startgroup))
12781 (push '() groups) (setq ingroup t)
12782 (when (not (= cnt 0))
12783 (setq cnt 0)
12784 (insert "\n"))
12785 (insert "{ "))
12786 ((equal e '(:endgroup))
12787 (setq ingroup nil cnt 0)
12788 (insert "}\n"))
12789 ((equal e '(:newline))
12790 (when (not (= cnt 0))
12791 (setq cnt 0)
12792 (insert "\n")
12793 (setq e (car tbl))
12794 (while (equal (car tbl) '(:newline))
12795 (insert "\n")
12796 (setq tbl (cdr tbl)))))
12798 (setq tg (car e) c (cdr e))
12799 (if ingroup (push tg (car groups)))
12800 (setq tg (org-add-props tg nil 'face
12801 (org-get-todo-face tg)))
12802 (if (and (= cnt 0) (not ingroup)) (insert " "))
12803 (insert "[" c "] " tg (make-string
12804 (- fwidth 4 (length tg)) ?\ ))
12805 (when (= (setq cnt (1+ cnt)) ncol)
12806 (insert "\n")
12807 (if ingroup (insert " "))
12808 (setq cnt 0)))))
12809 (insert "\n")
12810 (goto-char (point-min))
12811 (if (not expert) (org-fit-window-to-buffer))
12812 (message "[a-z..]:Set [SPC]:clear")
12813 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12814 (cond
12815 ((or (= c ?\C-g)
12816 (and (= c ?q) (not (rassoc c fulltable))))
12817 (setq quit-flag t))
12818 ((= c ?\ ) nil)
12819 ((setq e (rassoc c fulltable) tg (car e))
12821 (t (setq quit-flag t)))))))
12823 (defun org-entry-is-todo-p ()
12824 (member (org-get-todo-state) org-not-done-keywords))
12826 (defun org-entry-is-done-p ()
12827 (member (org-get-todo-state) org-done-keywords))
12829 (defun org-get-todo-state ()
12830 "Return the TODO keyword of the current subtree."
12831 (save-excursion
12832 (org-back-to-heading t)
12833 (and (looking-at org-todo-line-regexp)
12834 (match-end 2)
12835 (match-string 2))))
12837 (defun org-at-date-range-p (&optional inactive-ok)
12838 "Is the cursor inside a date range?"
12839 (interactive)
12840 (save-excursion
12841 (catch 'exit
12842 (let ((pos (point)))
12843 (skip-chars-backward "^[<\r\n")
12844 (skip-chars-backward "<[")
12845 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12846 (>= (match-end 0) pos)
12847 (throw 'exit t))
12848 (skip-chars-backward "^<[\r\n")
12849 (skip-chars-backward "<[")
12850 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12851 (>= (match-end 0) pos)
12852 (throw 'exit t)))
12853 nil)))
12855 (defun org-get-repeat (&optional tagline)
12856 "Check if there is a deadline/schedule with repeater in this entry."
12857 (save-match-data
12858 (save-excursion
12859 (org-back-to-heading t)
12860 (and (re-search-forward (if tagline
12861 (concat tagline "\\s-*" org-repeat-re)
12862 org-repeat-re)
12863 (org-entry-end-position) t)
12864 (match-string-no-properties 1)))))
12866 (defvar org-last-changed-timestamp)
12867 (defvar org-last-inserted-timestamp)
12868 (defvar org-log-post-message)
12869 (defvar org-log-note-purpose)
12870 (defvar org-log-note-how)
12871 (defvar org-log-note-extra)
12872 (defun org-auto-repeat-maybe (done-word)
12873 "Check if the current headline contains a repeated deadline/schedule.
12874 If yes, set TODO state back to what it was and change the base date
12875 of repeating deadline/scheduled time stamps to new date.
12876 This function is run automatically after each state change to a DONE state."
12877 ;; last-state is dynamically scoped into this function
12878 (let* ((repeat (org-get-repeat))
12879 (aa (assoc org-last-state org-todo-kwd-alist))
12880 (interpret (nth 1 aa))
12881 (head (nth 2 aa))
12882 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12883 (msg "Entry repeats: ")
12884 (org-log-done nil)
12885 (org-todo-log-states nil)
12886 re type n what ts time to-state)
12887 (when repeat
12888 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12889 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12890 org-todo-repeat-to-state))
12891 (unless (and to-state (member to-state org-todo-keywords-1))
12892 (setq to-state (if (eq interpret 'type) org-last-state head)))
12893 (org-todo to-state)
12894 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12895 (org-entry-put nil "LAST_REPEAT" (format-time-string
12896 (org-time-stamp-format t t))))
12897 (when org-log-repeat
12898 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12899 (memq 'org-add-log-note post-command-hook))
12900 ;; OK, we are already setup for some record
12901 (if (eq org-log-repeat 'note)
12902 ;; make sure we take a note, not only a time stamp
12903 (setq org-log-note-how 'note))
12904 ;; Set up for taking a record
12905 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12906 org-last-state
12907 'findpos org-log-repeat)))
12908 (org-back-to-heading t)
12909 (org-add-planning-info nil nil 'closed)
12910 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12911 org-deadline-time-regexp "\\)\\|\\("
12912 org-ts-regexp "\\)"))
12913 (while (re-search-forward
12914 re (save-excursion (outline-next-heading) (point)) t)
12915 (setq type (if (match-end 1) org-scheduled-string
12916 (if (match-end 3) org-deadline-string "Plain:"))
12917 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12918 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12919 (setq n (string-to-number (match-string 2 ts))
12920 what (match-string 3 ts))
12921 (if (equal what "w") (setq n (* n 7) what "d"))
12922 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12923 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12924 ;; Preparation, see if we need to modify the start date for the change
12925 (when (match-end 1)
12926 (setq time (save-match-data (org-time-string-to-time ts)))
12927 (cond
12928 ((equal (match-string 1 ts) ".")
12929 ;; Shift starting date to today
12930 (org-timestamp-change
12931 (- (org-today) (time-to-days time))
12932 'day))
12933 ((equal (match-string 1 ts) "+")
12934 (let ((nshiftmax 10) (nshift 0))
12935 (while (or (= nshift 0)
12936 (<= (time-to-days time)
12937 (time-to-days (current-time))))
12938 (when (= (incf nshift) nshiftmax)
12939 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12940 (error "Abort")))
12941 (org-timestamp-change n (cdr (assoc what whata)))
12942 (org-at-timestamp-p t)
12943 (setq ts (match-string 1))
12944 (setq time (save-match-data (org-time-string-to-time ts)))))
12945 (org-timestamp-change (- n) (cdr (assoc what whata)))
12946 ;; rematch, so that we have everything in place for the real shift
12947 (org-at-timestamp-p t)
12948 (setq ts (match-string 1))
12949 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12950 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12951 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12952 (setq org-log-post-message msg)
12953 (message "%s" msg))))
12955 (defun org-show-todo-tree (arg)
12956 "Make a compact tree which shows all headlines marked with TODO.
12957 The tree will show the lines where the regexp matches, and all higher
12958 headlines above the match.
12959 With a \\[universal-argument] prefix, prompt for a regexp to match.
12960 With a numeric prefix N, construct a sparse tree for the Nth element
12961 of `org-todo-keywords-1'."
12962 (interactive "P")
12963 (let ((case-fold-search nil)
12964 (kwd-re
12965 (cond ((null arg) org-not-done-regexp)
12966 ((equal arg '(4))
12967 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12968 (mapcar 'list org-todo-keywords-1))))
12969 (concat "\\("
12970 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12971 "\\)\\>")))
12972 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12973 (regexp-quote (nth (1- (prefix-numeric-value arg))
12974 org-todo-keywords-1)))
12975 (t (user-error "Invalid prefix argument: %s" arg)))))
12976 (message "%d TODO entries found"
12977 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12979 (defun org-deadline (arg &optional time)
12980 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12981 With one universal prefix argument, remove any deadline from the item.
12982 With two universal prefix arguments, prompt for a warning delay.
12983 With argument TIME, set the deadline at the corresponding date. TIME
12984 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12985 (interactive "P")
12986 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12987 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12988 'region-start-level 'region))
12989 org-loop-over-headlines-in-active-region)
12990 (org-map-entries
12991 `(org-deadline ',arg ,time)
12992 org-loop-over-headlines-in-active-region
12993 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12994 (let* ((old-date (org-entry-get nil "DEADLINE"))
12995 (old-date-time (if old-date (org-time-string-to-time old-date)))
12996 (repeater (and old-date
12997 (string-match
12998 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12999 old-date)
13000 (match-string 1 old-date))))
13001 (cond
13002 ((equal arg '(4))
13003 (when (and old-date org-log-redeadline)
13004 (org-add-log-setup 'deldeadline nil old-date 'findpos
13005 org-log-redeadline))
13006 (org-remove-timestamp-with-keyword org-deadline-string)
13007 (message "Item no longer has a deadline."))
13008 ((equal arg '(16))
13009 (save-excursion
13010 (org-back-to-heading t)
13011 (if (re-search-forward
13012 org-deadline-time-regexp
13013 (save-excursion (outline-next-heading) (point)) t)
13014 (let* ((rpl0 (match-string 1))
13015 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13016 (replace-match
13017 (concat org-deadline-string
13018 " <" rpl
13019 (format " -%dd"
13020 (abs
13021 (- (time-to-days
13022 (save-match-data
13023 (org-read-date nil t nil "Warn starting from" old-date-time)))
13024 (time-to-days old-date-time))))
13025 ">") t t))
13026 (user-error "No deadline information to update"))))
13028 (org-add-planning-info 'deadline time 'closed)
13029 (when (and old-date org-log-redeadline
13030 (not (equal old-date
13031 (substring org-last-inserted-timestamp 1 -1))))
13032 (org-add-log-setup 'redeadline nil old-date 'findpos
13033 org-log-redeadline))
13034 (when repeater
13035 (save-excursion
13036 (org-back-to-heading t)
13037 (when (re-search-forward (concat org-deadline-string " "
13038 org-last-inserted-timestamp)
13039 (save-excursion
13040 (outline-next-heading) (point)) t)
13041 (goto-char (1- (match-end 0)))
13042 (insert " " repeater)
13043 (setq org-last-inserted-timestamp
13044 (concat (substring org-last-inserted-timestamp 0 -1)
13045 " " repeater
13046 (substring org-last-inserted-timestamp -1))))))
13047 (message "Deadline on %s" org-last-inserted-timestamp))))))
13049 (defun org-schedule (arg &optional time)
13050 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13051 With one universal prefix argument, remove any scheduling date from the item.
13052 With two universal prefix arguments, prompt for a delay cookie.
13053 With argument TIME, scheduled at the corresponding date. TIME can
13054 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13055 (interactive "P")
13056 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13057 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13058 'region-start-level 'region))
13059 org-loop-over-headlines-in-active-region)
13060 (org-map-entries
13061 `(org-schedule ',arg ,time)
13062 org-loop-over-headlines-in-active-region
13063 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13064 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13065 (old-date-time (if old-date (org-time-string-to-time old-date)))
13066 (repeater (and old-date
13067 (string-match
13068 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13069 old-date)
13070 (match-string 1 old-date))))
13071 (cond
13072 ((equal arg '(4))
13073 (progn
13074 (when (and old-date org-log-reschedule)
13075 (org-add-log-setup 'delschedule nil old-date 'findpos
13076 org-log-reschedule))
13077 (org-remove-timestamp-with-keyword org-scheduled-string)
13078 (message "Item is no longer scheduled.")))
13079 ((equal arg '(16))
13080 (save-excursion
13081 (org-back-to-heading t)
13082 (if (re-search-forward
13083 org-scheduled-time-regexp
13084 (save-excursion (outline-next-heading) (point)) t)
13085 (let* ((rpl0 (match-string 1))
13086 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13087 (replace-match
13088 (concat org-scheduled-string
13089 " <" rpl
13090 (format " -%dd"
13091 (abs
13092 (- (time-to-days
13093 (save-match-data
13094 (org-read-date nil t nil "Delay until" old-date-time)))
13095 (time-to-days old-date-time))))
13096 ">") t t))
13097 (user-error "No scheduled information to update"))))
13099 (org-add-planning-info 'scheduled time 'closed)
13100 (when (and old-date org-log-reschedule
13101 (not (equal old-date
13102 (substring org-last-inserted-timestamp 1 -1))))
13103 (org-add-log-setup 'reschedule nil old-date 'findpos
13104 org-log-reschedule))
13105 (when repeater
13106 (save-excursion
13107 (org-back-to-heading t)
13108 (when (re-search-forward (concat org-scheduled-string " "
13109 org-last-inserted-timestamp)
13110 (save-excursion
13111 (outline-next-heading) (point)) t)
13112 (goto-char (1- (match-end 0)))
13113 (insert " " repeater)
13114 (setq org-last-inserted-timestamp
13115 (concat (substring org-last-inserted-timestamp 0 -1)
13116 " " repeater
13117 (substring org-last-inserted-timestamp -1))))))
13118 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13120 (defun org-get-scheduled-time (pom &optional inherit)
13121 "Get the scheduled time as a time tuple, of a format suitable
13122 for calling org-schedule with, or if there is no scheduling,
13123 returns nil."
13124 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13125 (when time
13126 (apply 'encode-time (org-parse-time-string time)))))
13128 (defun org-get-deadline-time (pom &optional inherit)
13129 "Get the deadline as a time tuple, of a format suitable for
13130 calling org-deadline with, or if there is no scheduling, returns
13131 nil."
13132 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13133 (when time
13134 (apply 'encode-time (org-parse-time-string time)))))
13136 (defun org-remove-timestamp-with-keyword (keyword)
13137 "Remove all time stamps with KEYWORD in the current entry."
13138 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13139 beg)
13140 (save-excursion
13141 (org-back-to-heading t)
13142 (setq beg (point))
13143 (outline-next-heading)
13144 (while (re-search-backward re beg t)
13145 (replace-match "")
13146 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13147 (equal (char-before) ?\ ))
13148 (backward-delete-char 1)
13149 (if (string-match "^[ \t]*$" (buffer-substring
13150 (point-at-bol) (point-at-eol)))
13151 (delete-region (point-at-bol)
13152 (min (point-max) (1+ (point-at-eol))))))))))
13154 (defvar org-time-was-given) ; dynamically scoped parameter
13155 (defvar org-end-time-was-given) ; dynamically scoped parameter
13157 (defun org-add-planning-info (what &optional time &rest remove)
13158 "Insert new timestamp with keyword in the line directly after the headline.
13159 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13160 If non is given, the user is prompted for a date.
13161 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13162 be removed."
13163 (interactive)
13164 (let (org-time-was-given org-end-time-was-given ts
13165 end default-time default-input)
13167 (catch 'exit
13168 (when (and (memq what '(scheduled deadline))
13169 (or (not time)
13170 (and (stringp time)
13171 (string-match "^[-+]+[0-9]" time))))
13172 ;; Try to get a default date/time from existing timestamp
13173 (save-excursion
13174 (org-back-to-heading t)
13175 (setq end (save-excursion (outline-next-heading) (point)))
13176 (when (re-search-forward (if (eq what 'scheduled)
13177 org-scheduled-time-regexp
13178 org-deadline-time-regexp)
13179 end t)
13180 (setq ts (match-string 1)
13181 default-time
13182 (apply 'encode-time (org-parse-time-string ts))
13183 default-input (and ts (org-get-compact-tod ts))))))
13184 (when what
13185 (setq time
13186 (if (stringp time)
13187 ;; This is a string (relative or absolute), set proper date
13188 (apply 'encode-time
13189 (org-read-date-analyze
13190 time default-time (decode-time default-time)))
13191 ;; If necessary, get the time from the user
13192 (or time (org-read-date nil 'to-time nil nil
13193 default-time default-input)))))
13195 (when (and org-insert-labeled-timestamps-at-point
13196 (member what '(scheduled deadline)))
13197 (insert
13198 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13199 (org-insert-time-stamp time org-time-was-given
13200 nil nil nil (list org-end-time-was-given))
13201 (setq what nil))
13202 (save-excursion
13203 (save-restriction
13204 (let (col list elt ts buffer-invisibility-spec)
13205 (org-back-to-heading t)
13206 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13207 (goto-char (match-end 1))
13208 (setq col (current-column))
13209 (goto-char (match-end 0))
13210 (if (eobp) (insert "\n") (forward-char 1))
13211 (when (and (not what)
13212 (not (looking-at
13213 (concat "[ \t]*"
13214 org-keyword-time-not-clock-regexp))))
13215 ;; Nothing to add, nothing to remove...... :-)
13216 (throw 'exit nil))
13217 (if (and (not (looking-at org-outline-regexp))
13218 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13219 "[^\r\n]*"))
13220 (not (equal (match-string 1) org-clock-string)))
13221 (narrow-to-region (match-beginning 0) (match-end 0))
13222 (insert-before-markers "\n")
13223 (backward-char 1)
13224 (narrow-to-region (point) (point))
13225 (and org-adapt-indentation (org-indent-to-column col)))
13226 ;; Check if we have to remove something.
13227 (setq list (cons what remove))
13228 (while list
13229 (setq elt (pop list))
13230 (when (or (and (eq elt 'scheduled)
13231 (re-search-forward org-scheduled-time-regexp nil t))
13232 (and (eq elt 'deadline)
13233 (re-search-forward org-deadline-time-regexp nil t))
13234 (and (eq elt 'closed)
13235 (re-search-forward org-closed-time-regexp nil t)))
13236 (replace-match "")
13237 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13238 (and (looking-at "[ \t]+") (replace-match ""))
13239 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13240 (when what
13241 (insert
13242 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13243 (cond ((eq what 'scheduled) org-scheduled-string)
13244 ((eq what 'deadline) org-deadline-string)
13245 ((eq what 'closed) org-closed-string))
13246 " ")
13247 (setq ts (org-insert-time-stamp
13248 time
13249 (or org-time-was-given
13250 (and (eq what 'closed) org-log-done-with-time))
13251 (eq what 'closed)
13252 nil nil (list org-end-time-was-given)))
13253 (insert
13254 (if (not (or (bolp) (eq (char-before) ?\ )
13255 (memq (char-after) '(32 10))
13256 (eobp))) " " ""))
13257 (end-of-line 1))
13258 (goto-char (point-min))
13259 (widen)
13260 (if (and (looking-at "[ \t]*\n")
13261 (equal (char-before) ?\n))
13262 (delete-region (1- (point)) (point-at-eol)))
13263 ts))))))
13265 (defvar org-log-note-marker (make-marker))
13266 (defvar org-log-note-purpose nil)
13267 (defvar org-log-note-state nil)
13268 (defvar org-log-note-previous-state nil)
13269 (defvar org-log-note-how nil)
13270 (defvar org-log-note-extra nil)
13271 (defvar org-log-note-window-configuration nil)
13272 (defvar org-log-note-return-to (make-marker))
13273 (defvar org-log-note-effective-time nil
13274 "Remembered current time so that dynamically scoped
13275 `org-extend-today-until' affects tha timestamps in state change
13276 log")
13278 (defvar org-log-post-message nil
13279 "Message to be displayed after a log note has been stored.
13280 The auto-repeater uses this.")
13282 (defun org-add-note ()
13283 "Add a note to the current entry.
13284 This is done in the same way as adding a state change note."
13285 (interactive)
13286 (org-add-log-setup 'note nil nil 'findpos nil))
13288 (defvar org-property-end-re)
13289 (defun org-add-log-setup (&optional purpose state prev-state
13290 findpos how extra)
13291 "Set up the post command hook to take a note.
13292 If this is about to TODO state change, the new state is expected in STATE.
13293 When FINDPOS is non-nil, find the correct position for the note in
13294 the current entry. If not, assume that it can be inserted at point.
13295 HOW is an indicator what kind of note should be created.
13296 EXTRA is additional text that will be inserted into the notes buffer."
13297 (let* ((org-log-into-drawer (org-log-into-drawer))
13298 (drawer (cond ((stringp org-log-into-drawer)
13299 org-log-into-drawer)
13300 (org-log-into-drawer "LOGBOOK"))))
13301 (save-restriction
13302 (save-excursion
13303 (when findpos
13304 (org-back-to-heading t)
13305 (narrow-to-region (point) (save-excursion
13306 (outline-next-heading) (point)))
13307 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13308 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13309 "[^\r\n]*\\)?"))
13310 (goto-char (match-end 0))
13311 (cond
13312 (drawer
13313 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13314 nil t)
13315 (progn
13316 (goto-char (match-end 0))
13317 (or org-log-states-order-reversed
13318 (and (re-search-forward org-property-end-re nil t)
13319 (goto-char (1- (match-beginning 0))))))
13320 (insert "\n:" drawer ":\n:END:")
13321 (beginning-of-line 0)
13322 (org-indent-line)
13323 (beginning-of-line 2)
13324 (org-indent-line)
13325 (end-of-line 0)))
13326 ((and org-log-state-notes-insert-after-drawers
13327 (save-excursion
13328 (forward-line) (looking-at org-drawer-regexp)))
13329 (forward-line)
13330 (while (looking-at org-drawer-regexp)
13331 (goto-char (match-end 0))
13332 (re-search-forward org-property-end-re (point-max) t)
13333 (forward-line))
13334 (forward-line -1)))
13335 (unless org-log-states-order-reversed
13336 (and (= (char-after) ?\n) (forward-char 1))
13337 (org-skip-over-state-notes)
13338 (skip-chars-backward " \t\n\r")))
13339 (move-marker org-log-note-marker (point))
13340 (setq org-log-note-purpose purpose
13341 org-log-note-state state
13342 org-log-note-previous-state prev-state
13343 org-log-note-how how
13344 org-log-note-extra extra
13345 org-log-note-effective-time (org-current-effective-time))
13346 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13348 (defun org-skip-over-state-notes ()
13349 "Skip past the list of State notes in an entry."
13350 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13351 (when (ignore-errors (goto-char (org-in-item-p)))
13352 (let* ((struct (org-list-struct))
13353 (prevs (org-list-prevs-alist struct)))
13354 (while (looking-at "[ \t]*- State")
13355 (goto-char (or (org-list-get-next-item (point) struct prevs)
13356 (org-list-get-item-end (point) struct)))))))
13358 (defun org-add-log-note (&optional purpose)
13359 "Pop up a window for taking a note, and add this note later at point."
13360 (remove-hook 'post-command-hook 'org-add-log-note)
13361 (setq org-log-note-window-configuration (current-window-configuration))
13362 (delete-other-windows)
13363 (move-marker org-log-note-return-to (point))
13364 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13365 (goto-char org-log-note-marker)
13366 (org-switch-to-buffer-other-window "*Org Note*")
13367 (erase-buffer)
13368 (if (memq org-log-note-how '(time state))
13369 (let (current-prefix-arg) (org-store-log-note))
13370 (let ((org-inhibit-startup t)) (org-mode))
13371 (insert (format "# Insert note for %s.
13372 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13373 (cond
13374 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13375 ((eq org-log-note-purpose 'done) "closed todo item")
13376 ((eq org-log-note-purpose 'state)
13377 (format "state change from \"%s\" to \"%s\""
13378 (or org-log-note-previous-state "")
13379 (or org-log-note-state "")))
13380 ((eq org-log-note-purpose 'reschedule)
13381 "rescheduling")
13382 ((eq org-log-note-purpose 'delschedule)
13383 "no longer scheduled")
13384 ((eq org-log-note-purpose 'redeadline)
13385 "changing deadline")
13386 ((eq org-log-note-purpose 'deldeadline)
13387 "removing deadline")
13388 ((eq org-log-note-purpose 'refile)
13389 "refiling")
13390 ((eq org-log-note-purpose 'note)
13391 "this entry")
13392 (t (error "This should not happen")))))
13393 (if org-log-note-extra (insert org-log-note-extra))
13394 (org-set-local 'org-finish-function 'org-store-log-note)
13395 (run-hooks 'org-log-buffer-setup-hook)))
13397 (defvar org-note-abort nil) ; dynamically scoped
13398 (defun org-store-log-note ()
13399 "Finish taking a log note, and insert it to where it belongs."
13400 (let ((txt (buffer-string)))
13401 (kill-buffer (current-buffer))
13402 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13403 lines ind bul)
13404 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13405 (setq txt (replace-match "" t t txt)))
13406 (if (string-match "\\s-+\\'" txt)
13407 (setq txt (replace-match "" t t txt)))
13408 (setq lines (org-split-string txt "\n"))
13409 (when (and note (string-match "\\S-" note))
13410 (setq note
13411 (org-replace-escapes
13412 note
13413 (list (cons "%u" (user-login-name))
13414 (cons "%U" user-full-name)
13415 (cons "%t" (format-time-string
13416 (org-time-stamp-format 'long 'inactive)
13417 org-log-note-effective-time))
13418 (cons "%T" (format-time-string
13419 (org-time-stamp-format 'long nil)
13420 org-log-note-effective-time))
13421 (cons "%d" (format-time-string
13422 (org-time-stamp-format nil 'inactive)
13423 org-log-note-effective-time))
13424 (cons "%D" (format-time-string
13425 (org-time-stamp-format nil nil)
13426 org-log-note-effective-time))
13427 (cons "%s" (if org-log-note-state
13428 (concat "\"" org-log-note-state "\"")
13429 ""))
13430 (cons "%S" (if org-log-note-previous-state
13431 (concat "\"" org-log-note-previous-state "\"")
13432 "\"\"")))))
13433 (if lines (setq note (concat note " \\\\")))
13434 (push note lines))
13435 (when (or current-prefix-arg org-note-abort)
13436 (when org-log-into-drawer
13437 (org-remove-empty-drawer-at
13438 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
13439 org-log-note-marker))
13440 (setq lines nil))
13441 (when lines
13442 (with-current-buffer (marker-buffer org-log-note-marker)
13443 (save-excursion
13444 (goto-char org-log-note-marker)
13445 (move-marker org-log-note-marker nil)
13446 (end-of-line 1)
13447 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13448 (setq ind (save-excursion
13449 (if (ignore-errors (goto-char (org-in-item-p)))
13450 (let ((struct (org-list-struct)))
13451 (org-list-get-ind
13452 (org-list-get-top-point struct) struct))
13453 (skip-chars-backward " \r\t\n")
13454 (cond
13455 ((and (org-at-heading-p)
13456 org-adapt-indentation)
13457 (1+ (org-current-level)))
13458 ((org-at-heading-p) 0)
13459 (t (org-get-indentation))))))
13460 (setq bul (org-list-bullet-string "-"))
13461 (org-indent-line-to ind)
13462 (insert bul (pop lines))
13463 (let ((ind-body (+ (length bul) ind)))
13464 (while lines
13465 (insert "\n")
13466 (org-indent-line-to ind-body)
13467 (insert (pop lines))))
13468 (message "Note stored")
13469 (org-back-to-heading t)
13470 (org-cycle-hide-drawers 'children))
13471 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13472 ;; from within `org-add-log-note' because `buffer-undo-list'
13473 ;; is then modified outside of `org-with-remote-undo'.
13474 (when (eq this-command 'org-agenda-todo)
13475 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13476 ;; Don't add undo information when called from `org-agenda-todo'
13477 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13478 (set-window-configuration org-log-note-window-configuration)
13479 (with-current-buffer (marker-buffer org-log-note-return-to)
13480 (goto-char org-log-note-return-to))
13481 (move-marker org-log-note-return-to nil)
13482 (and org-log-post-message (message "%s" org-log-post-message))))
13484 (defun org-remove-empty-drawer-at (drawer pos)
13485 "Remove an empty drawer DRAWER at position POS.
13486 POS may also be a marker."
13487 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13488 (save-excursion
13489 (save-restriction
13490 (widen)
13491 (goto-char pos)
13492 (if (org-in-regexp
13493 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13494 (replace-match ""))))))
13496 (defvar org-ts-type nil)
13497 (defun org-sparse-tree (&optional arg type)
13498 "Create a sparse tree, prompt for the details.
13499 This command can create sparse trees. You first need to select the type
13500 of match used to create the tree:
13502 t Show all TODO entries.
13503 T Show entries with a specific TODO keyword.
13504 m Show entries selected by a tags/property match.
13505 p Enter a property name and its value (both with completion on existing
13506 names/values) and show entries with that property.
13507 r Show entries matching a regular expression (`/' can be used as well).
13508 b Show deadlines and scheduled items before a date.
13509 a Show deadlines and scheduled items after a date.
13510 d Show deadlines due within `org-deadline-warning-days'.
13511 D Show deadlines and scheduled items between a date range."
13512 (interactive "P")
13513 (setq type (or type org-sparse-tree-default-date-type))
13514 (setq org-ts-type type)
13515 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty
13516 [d]eadlines [b]efore-date [a]fter-date [D]ates range
13517 [c]ycle through date types: %s"
13518 (case type
13519 (all "all timestamps")
13520 (scheduled "only scheduled")
13521 (deadline "only deadline")
13522 (active "only active timestamps")
13523 (inactive "only inactive timestamps")
13524 (scheduled-or-deadline "scheduled/deadline")
13525 (closed "with a closed time-stamp")
13526 (otherwise "scheduled/deadline")))
13527 (let ((answer (read-char-exclusive)))
13528 (case answer
13530 (org-sparse-tree
13532 (cadr (memq type '(scheduled-or-deadline all scheduled deadline active
13533 inactive closed)))))
13534 (?d (call-interactively #'org-check-deadlines))
13535 (?b (call-interactively #'org-check-before-date))
13536 (?a (call-interactively #'org-check-after-date))
13537 (?D (call-interactively #'org-check-dates-range))
13538 (?t (call-interactively #'org-show-todo-tree))
13539 (?T (org-show-todo-tree '(4)))
13540 (?m (call-interactively #'org-match-sparse-tree))
13541 ((?p ?P)
13542 (let* ((kwd (org-icompleting-read
13543 "Property: " (mapcar #'list (org-buffer-property-keys))))
13544 (value (org-icompleting-read
13545 "Value: " (mapcar #'list (org-property-values kwd)))))
13546 (unless (string-match "\\`{.*}\\'" value)
13547 (setq value (concat "\"" value "\"")))
13548 (org-match-sparse-tree arg (concat kwd "=" value))))
13549 ((?r ?R ?/) (call-interactively #'org-occur))
13550 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13552 (defvar org-occur-highlights nil
13553 "List of overlays used for occur matches.")
13554 (make-variable-buffer-local 'org-occur-highlights)
13555 (defvar org-occur-parameters nil
13556 "Parameters of the active org-occur calls.
13557 This is a list, each call to org-occur pushes as cons cell,
13558 containing the regular expression and the callback, onto the list.
13559 The list can contain several entries if `org-occur' has been called
13560 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13561 will only contain one set of parameters. When the highlights are
13562 removed (for example with `C-c C-c', or with the next edit (depending
13563 on `org-remove-highlights-with-change'), this variable is emptied
13564 as well.")
13565 (make-variable-buffer-local 'org-occur-parameters)
13567 (defun org-occur (regexp &optional keep-previous callback)
13568 "Make a compact tree which shows all matches of REGEXP.
13569 The tree will show the lines where the regexp matches, and all higher
13570 headlines above the match. It will also show the heading after the match,
13571 to make sure editing the matching entry is easy.
13572 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13573 call to `org-occur' will be kept, to allow stacking of calls to this
13574 command.
13575 If CALLBACK is non-nil, it is a function which is called to confirm
13576 that the match should indeed be shown."
13577 (interactive "sRegexp: \nP")
13578 (when (equal regexp "")
13579 (user-error "Regexp cannot be empty"))
13580 (unless keep-previous
13581 (org-remove-occur-highlights nil nil t))
13582 (push (cons regexp callback) org-occur-parameters)
13583 (let ((cnt 0))
13584 (save-excursion
13585 (goto-char (point-min))
13586 (if (or (not keep-previous) ; do not want to keep
13587 (not org-occur-highlights)) ; no previous matches
13588 ;; hide everything
13589 (org-overview))
13590 (while (re-search-forward regexp nil t)
13591 (when (or (not callback)
13592 (save-match-data (funcall callback)))
13593 (setq cnt (1+ cnt))
13594 (when org-highlight-sparse-tree-matches
13595 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13596 (org-show-context 'occur-tree))))
13597 (when org-remove-highlights-with-change
13598 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13599 nil 'local))
13600 (unless org-sparse-tree-open-archived-trees
13601 (org-hide-archived-subtrees (point-min) (point-max)))
13602 (run-hooks 'org-occur-hook)
13603 (if (org-called-interactively-p 'interactive)
13604 (message "%d match(es) for regexp %s" cnt regexp))
13605 cnt))
13607 (defun org-occur-next-match (&optional n reset)
13608 "Function for `next-error-function' to find sparse tree matches.
13609 N is the number of matches to move, when negative move backwards.
13610 RESET is entirely ignored - this function always goes back to the
13611 starting point when no match is found."
13612 (let* ((limit (if (< n 0) (point-min) (point-max)))
13613 (search-func (if (< n 0)
13614 'previous-single-char-property-change
13615 'next-single-char-property-change))
13616 (n (abs n))
13617 (pos (point))
13619 (catch 'exit
13620 (while (setq p1 (funcall search-func (point) 'org-type))
13621 (when (equal p1 limit)
13622 (goto-char pos)
13623 (error "No more matches"))
13624 (when (equal (get-char-property p1 'org-type) 'org-occur)
13625 (setq n (1- n))
13626 (when (= n 0)
13627 (goto-char p1)
13628 (throw 'exit (point))))
13629 (goto-char p1))
13630 (goto-char p1)
13631 (error "No more matches"))))
13633 (defun org-show-context (&optional key)
13634 "Make sure point and context are visible.
13635 How much context is shown depends upon the variables
13636 `org-show-hierarchy-above', `org-show-following-heading',
13637 `org-show-entry-below' and `org-show-siblings'."
13638 (let ((heading-p (org-at-heading-p t))
13639 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13640 (following-p (org-get-alist-option org-show-following-heading key))
13641 (entry-p (org-get-alist-option org-show-entry-below key))
13642 (siblings-p (org-get-alist-option org-show-siblings key)))
13643 ;; Show heading or entry text
13644 (if (and heading-p (not entry-p))
13645 (org-flag-heading nil) ; only show the heading
13646 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13647 (org-show-hidden-entry))) ; show entire entry
13648 (when following-p
13649 ;; Show next sibling, or heading below text
13650 (save-excursion
13651 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13652 (org-flag-heading nil))))
13653 (when siblings-p (org-show-siblings))
13654 (when hierarchy-p
13655 ;; show all higher headings, possibly with siblings
13656 (save-excursion
13657 (while (and (condition-case nil
13658 (progn (org-up-heading-all 1) t)
13659 (error nil))
13660 (not (bobp)))
13661 (org-flag-heading nil)
13662 (when siblings-p (org-show-siblings)))))))
13664 (defvar org-reveal-start-hook nil
13665 "Hook run before revealing a location.")
13667 (defun org-reveal (&optional siblings)
13668 "Show current entry, hierarchy above it, and the following headline.
13669 This can be used to show a consistent set of context around locations
13670 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13671 not t for the search context.
13673 With optional argument SIBLINGS, on each level of the hierarchy all
13674 siblings are shown. This repairs the tree structure to what it would
13675 look like when opened with hierarchical calls to `org-cycle'.
13676 With double optional argument \\[universal-argument] \\[universal-argument], \
13677 go to the parent and show the
13678 entire tree."
13679 (interactive "P")
13680 (run-hooks 'org-reveal-start-hook)
13681 (let ((org-show-hierarchy-above t)
13682 (org-show-following-heading t)
13683 (org-show-siblings (if siblings t org-show-siblings)))
13684 (org-show-context nil))
13685 (when (equal siblings '(16))
13686 (save-excursion
13687 (when (org-up-heading-safe)
13688 (org-show-subtree)
13689 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13691 (defun org-highlight-new-match (beg end)
13692 "Highlight from BEG to END and mark the highlight is an occur headline."
13693 (let ((ov (make-overlay beg end)))
13694 (overlay-put ov 'face 'secondary-selection)
13695 (overlay-put ov 'org-type 'org-occur)
13696 (push ov org-occur-highlights)))
13698 (defun org-remove-occur-highlights (&optional beg end noremove)
13699 "Remove the occur highlights from the buffer.
13700 BEG and END are ignored. If NOREMOVE is nil, remove this function
13701 from the `before-change-functions' in the current buffer."
13702 (interactive)
13703 (unless org-inhibit-highlight-removal
13704 (mapc 'delete-overlay org-occur-highlights)
13705 (setq org-occur-highlights nil)
13706 (setq org-occur-parameters nil)
13707 (unless noremove
13708 (remove-hook 'before-change-functions
13709 'org-remove-occur-highlights 'local))))
13711 ;;;; Priorities
13713 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13714 "Regular expression matching the priority indicator.")
13716 (defvar org-remove-priority-next-time nil)
13718 (defun org-priority-up ()
13719 "Increase the priority of the current item."
13720 (interactive)
13721 (org-priority 'up))
13723 (defun org-priority-down ()
13724 "Decrease the priority of the current item."
13725 (interactive)
13726 (org-priority 'down))
13728 (defun org-priority (&optional action show)
13729 "Change the priority of an item.
13730 ACTION can be `set', `up', `down', or a character."
13731 (interactive "P")
13732 (if (equal action '(4))
13733 (org-show-priority)
13734 (unless org-enable-priority-commands
13735 (user-error "Priority commands are disabled"))
13736 (setq action (or action 'set))
13737 (let (current new news have remove)
13738 (save-excursion
13739 (org-back-to-heading t)
13740 (if (looking-at org-priority-regexp)
13741 (setq current (string-to-char (match-string 2))
13742 have t))
13743 (cond
13744 ((eq action 'remove)
13745 (setq remove t new ?\ ))
13746 ((or (eq action 'set)
13747 (if (featurep 'xemacs) (characterp action) (integerp action)))
13748 (if (not (eq action 'set))
13749 (setq new action)
13750 (message "Priority %c-%c, SPC to remove: "
13751 org-highest-priority org-lowest-priority)
13752 (save-match-data
13753 (setq new (read-char-exclusive))))
13754 (if (and (= (upcase org-highest-priority) org-highest-priority)
13755 (= (upcase org-lowest-priority) org-lowest-priority))
13756 (setq new (upcase new)))
13757 (cond ((equal new ?\ ) (setq remove t))
13758 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13759 (user-error "Priority must be between `%c' and `%c'"
13760 org-highest-priority org-lowest-priority))))
13761 ((eq action 'up)
13762 (setq new (if have
13763 (1- current) ; normal cycling
13764 ;; last priority was empty
13765 (if (eq last-command this-command)
13766 org-lowest-priority ; wrap around empty to lowest
13767 ;; default
13768 (if org-priority-start-cycle-with-default
13769 org-default-priority
13770 (1- org-default-priority))))))
13771 ((eq action 'down)
13772 (setq new (if have
13773 (1+ current) ; normal cycling
13774 ;; last priority was empty
13775 (if (eq last-command this-command)
13776 org-highest-priority ; wrap around empty to highest
13777 ;; default
13778 (if org-priority-start-cycle-with-default
13779 org-default-priority
13780 (1+ org-default-priority))))))
13781 (t (user-error "Invalid action")))
13782 (if (or (< (upcase new) org-highest-priority)
13783 (> (upcase new) org-lowest-priority))
13784 (if (and (memq action '(up down))
13785 (not have) (not (eq last-command this-command)))
13786 ;; `new' is from default priority
13787 (error
13788 "The default can not be set, see `org-default-priority' why")
13789 ;; normal cycling: `new' is beyond highest/lowest priority
13790 ;; and is wrapped around to the empty priority
13791 (setq remove t)))
13792 (setq news (format "%c" new))
13793 (if have
13794 (if remove
13795 (replace-match "" t t nil 1)
13796 (replace-match news t t nil 2))
13797 (if remove
13798 (user-error "No priority cookie found in line")
13799 (let ((case-fold-search nil))
13800 (looking-at org-todo-line-regexp))
13801 (if (match-end 2)
13802 (progn
13803 (goto-char (match-end 2))
13804 (insert " [#" news "]"))
13805 (goto-char (match-beginning 3))
13806 (insert "[#" news "] "))))
13807 (org-preserve-lc (org-set-tags nil 'align)))
13808 (if remove
13809 (message "Priority removed")
13810 (message "Priority of current item set to %s" news)))))
13812 (defun org-show-priority ()
13813 "Show the priority of the current item.
13814 This priority is composed of the main priority given with the [#A] cookies,
13815 and by additional input from the age of a schedules or deadline entry."
13816 (interactive)
13817 (let ((pri (if (eq major-mode 'org-agenda-mode)
13818 (org-get-at-bol 'priority)
13819 (save-excursion
13820 (save-match-data
13821 (beginning-of-line)
13822 (and (looking-at org-heading-regexp)
13823 (org-get-priority (match-string 0))))))))
13824 (message "Priority is %d" (if pri pri -1000))))
13826 (defun org-get-priority (s)
13827 "Find priority cookie and return priority."
13828 (save-match-data
13829 (if (functionp org-get-priority-function)
13830 (funcall org-get-priority-function)
13831 (if (not (string-match org-priority-regexp s))
13832 (* 1000 (- org-lowest-priority org-default-priority))
13833 (* 1000 (- org-lowest-priority
13834 (string-to-char (match-string 2 s))))))))
13836 ;;;; Tags
13838 (defvar org-agenda-archives-mode)
13839 (defvar org-map-continue-from nil
13840 "Position from where mapping should continue.
13841 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13843 (defvar org-scanner-tags nil
13844 "The current tag list while the tags scanner is running.")
13845 (defvar org-trust-scanner-tags nil
13846 "Should `org-get-tags-at' use the tags for the scanner.
13847 This is for internal dynamical scoping only.
13848 When this is non-nil, the function `org-get-tags-at' will return the value
13849 of `org-scanner-tags' instead of building the list by itself. This
13850 can lead to large speed-ups when the tags scanner is used in a file with
13851 many entries, and when the list of tags is retrieved, for example to
13852 obtain a list of properties. Building the tags list for each entry in such
13853 a file becomes an N^2 operation - but with this variable set, it scales
13854 as N.")
13856 (defun org-scan-tags (action matcher todo-only &optional start-level)
13857 "Scan headline tags with inheritance and produce output ACTION.
13859 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13860 or `agenda' to produce an entry list for an agenda view. It can also be
13861 a Lisp form or a function that should be called at each matched headline, in
13862 this case the return value is a list of all return values from these calls.
13864 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13865 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13866 only lines with a not-done TODO keyword are included in the output.
13867 This should be the same variable that was scoped into
13868 and set by `org-make-tags-matcher' when it constructed MATCHER.
13870 START-LEVEL can be a string with asterisks, reducing the scope to
13871 headlines matching this string."
13872 (require 'org-agenda)
13873 (let* ((re (concat "^"
13874 (if start-level
13875 ;; Get the correct level to match
13876 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13877 org-outline-regexp)
13878 " *\\(\\<\\("
13879 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13880 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13881 (props (list 'face 'default
13882 'done-face 'org-agenda-done
13883 'undone-face 'default
13884 'mouse-face 'highlight
13885 'org-not-done-regexp org-not-done-regexp
13886 'org-todo-regexp org-todo-regexp
13887 'org-complex-heading-regexp org-complex-heading-regexp
13888 'help-echo
13889 (format "mouse-2 or RET jump to org file %s"
13890 (abbreviate-file-name
13891 (or (buffer-file-name (buffer-base-buffer))
13892 (buffer-name (buffer-base-buffer)))))))
13893 (org-map-continue-from nil)
13894 lspos tags tags-list
13895 (tags-alist (list (cons 0 org-file-tags)))
13896 (llast 0) rtn rtn1 level category i txt
13897 todo marker entry priority)
13898 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13899 (setq action (list 'lambda nil action)))
13900 (save-excursion
13901 (goto-char (point-min))
13902 (when (eq action 'sparse-tree)
13903 (org-overview)
13904 (org-remove-occur-highlights))
13905 (while (let (case-fold-search)
13906 (re-search-forward re nil t))
13907 (setq org-map-continue-from nil)
13908 (catch :skip
13909 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13910 tags (if (match-end 4) (org-match-string-no-properties 4)))
13911 (goto-char (setq lspos (match-beginning 0)))
13912 (setq level (org-reduced-level (org-outline-level))
13913 category (org-get-category))
13914 (setq i llast llast level)
13915 ;; remove tag lists from same and sublevels
13916 (while (>= i level)
13917 (when (setq entry (assoc i tags-alist))
13918 (setq tags-alist (delete entry tags-alist)))
13919 (setq i (1- i)))
13920 ;; add the next tags
13921 (when tags
13922 (setq tags (org-split-string tags ":")
13923 tags-alist
13924 (cons (cons level tags) tags-alist)))
13925 ;; compile tags for current headline
13926 (setq tags-list
13927 (if org-use-tag-inheritance
13928 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13929 tags)
13930 org-scanner-tags tags-list)
13931 (when org-use-tag-inheritance
13932 (setcdr (car tags-alist)
13933 (mapcar (lambda (x)
13934 (setq x (copy-sequence x))
13935 (org-add-prop-inherited x))
13936 (cdar tags-alist))))
13937 (when (and tags org-use-tag-inheritance
13938 (or (not (eq t org-use-tag-inheritance))
13939 org-tags-exclude-from-inheritance))
13940 ;; selective inheritance, remove uninherited ones
13941 (setcdr (car tags-alist)
13942 (org-remove-uninherited-tags (cdar tags-alist))))
13943 (when (and
13945 ;; eval matcher only when the todo condition is OK
13946 (and (or (not todo-only) (member todo org-not-done-keywords))
13947 (let ((case-fold-search t) (org-trust-scanner-tags t))
13948 (eval matcher)))
13950 ;; Call the skipper, but return t if it does not skip,
13951 ;; so that the `and' form continues evaluating
13952 (progn
13953 (unless (eq action 'sparse-tree) (org-agenda-skip))
13956 ;; Check if timestamps are deselecting this entry
13957 (or (not todo-only)
13958 (and (member todo org-not-done-keywords)
13959 (or (not org-agenda-tags-todo-honor-ignore-options)
13960 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13962 ;; select this headline
13963 (cond
13964 ((eq action 'sparse-tree)
13965 (and org-highlight-sparse-tree-matches
13966 (org-get-heading) (match-end 0)
13967 (org-highlight-new-match
13968 (match-beginning 1) (match-end 1)))
13969 (org-show-context 'tags-tree))
13970 ((eq action 'agenda)
13971 (setq txt (org-agenda-format-item
13973 (concat
13974 (if (eq org-tags-match-list-sublevels 'indented)
13975 (make-string (1- level) ?.) "")
13976 (org-get-heading))
13977 level category
13978 tags-list)
13979 priority (org-get-priority txt))
13980 (goto-char lspos)
13981 (setq marker (org-agenda-new-marker))
13982 (org-add-props txt props
13983 'org-marker marker 'org-hd-marker marker 'org-category category
13984 'todo-state todo
13985 'priority priority 'type "tagsmatch")
13986 (push txt rtn))
13987 ((functionp action)
13988 (setq org-map-continue-from nil)
13989 (save-excursion
13990 (setq rtn1 (funcall action))
13991 (push rtn1 rtn)))
13992 (t (user-error "Invalid action")))
13994 ;; if we are to skip sublevels, jump to end of subtree
13995 (unless org-tags-match-list-sublevels
13996 (org-end-of-subtree t)
13997 (backward-char 1))))
13998 ;; Get the correct position from where to continue
13999 (if org-map-continue-from
14000 (goto-char org-map-continue-from)
14001 (and (= (point) lspos) (end-of-line 1)))))
14002 (when (and (eq action 'sparse-tree)
14003 (not org-sparse-tree-open-archived-trees))
14004 (org-hide-archived-subtrees (point-min) (point-max)))
14005 (nreverse rtn)))
14007 (defun org-remove-uninherited-tags (tags)
14008 "Remove all tags that are not inherited from the list TAGS."
14009 (cond
14010 ((eq org-use-tag-inheritance t)
14011 (if org-tags-exclude-from-inheritance
14012 (org-delete-all org-tags-exclude-from-inheritance tags)
14013 tags))
14014 ((not org-use-tag-inheritance) nil)
14015 ((stringp org-use-tag-inheritance)
14016 (delq nil (mapcar
14017 (lambda (x)
14018 (if (and (string-match org-use-tag-inheritance x)
14019 (not (member x org-tags-exclude-from-inheritance)))
14020 x nil))
14021 tags)))
14022 ((listp org-use-tag-inheritance)
14023 (delq nil (mapcar
14024 (lambda (x)
14025 (if (member x org-use-tag-inheritance) x nil))
14026 tags)))))
14028 (defun org-match-sparse-tree (&optional todo-only match)
14029 "Create a sparse tree according to tags string MATCH.
14030 MATCH can contain positive and negative selection of tags, like
14031 \"+WORK+URGENT-WITHBOSS\".
14032 If optional argument TODO-ONLY is non-nil, only select lines that are
14033 also TODO lines."
14034 (interactive "P")
14035 (org-agenda-prepare-buffers (list (current-buffer)))
14036 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
14038 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14040 (defvar org-cached-props nil)
14041 (defun org-cached-entry-get (pom property)
14042 (if (or (eq t org-use-property-inheritance)
14043 (and (stringp org-use-property-inheritance)
14044 (string-match org-use-property-inheritance property))
14045 (and (listp org-use-property-inheritance)
14046 (member property org-use-property-inheritance)))
14047 ;; Caching is not possible, check it directly
14048 (org-entry-get pom property 'inherit)
14049 ;; Get all properties, so that we can do complicated checks easily
14050 (cdr (assoc property (or org-cached-props
14051 (setq org-cached-props
14052 (org-entry-properties pom)))))))
14054 (defun org-global-tags-completion-table (&optional files)
14055 "Return the list of all tags in all agenda buffer/files.
14056 Optional FILES argument is a list of files which can be used
14057 instead of the agenda files."
14058 (save-excursion
14059 (org-uniquify
14060 (delq nil
14061 (apply 'append
14062 (mapcar
14063 (lambda (file)
14064 (set-buffer (find-file-noselect file))
14065 (append (org-get-buffer-tags)
14066 (mapcar (lambda (x) (if (stringp (car-safe x))
14067 (list (car-safe x)) nil))
14068 org-tag-alist)))
14069 (if (and files (car files))
14070 files
14071 (org-agenda-files))))))))
14073 (defun org-make-tags-matcher (match)
14074 "Create the TAGS/TODO matcher form for the selection string MATCH.
14076 The variable `todo-only' is scoped dynamically into this function.
14077 It will be set to t if the matcher restricts matching to TODO entries,
14078 otherwise will not be touched.
14080 Returns a cons of the selection string MATCH and the constructed
14081 lisp form implementing the matcher. The matcher is to be evaluated
14082 at an Org entry, with point on the headline, and returns t if the
14083 entry matches the selection string MATCH. The returned lisp form
14084 references two variables with information about the entry, which
14085 must be bound around the form's evaluation: todo, the TODO keyword
14086 at the entry (or nil of none); and tags-list, the list of all tags
14087 at the entry including inherited ones. Additionally, the category
14088 of the entry (if any) must be specified as the text property
14089 'org-category on the headline.
14091 See also `org-scan-tags'.
14093 (declare (special todo-only))
14094 (unless (boundp 'todo-only)
14095 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14096 (unless match
14097 ;; Get a new match request, with completion against the global
14098 ;; tags table and the local tags in current buffer
14099 (let ((org-last-tags-completion-table
14100 (org-uniquify
14101 (delq nil (append (org-get-buffer-tags)
14102 (org-global-tags-completion-table))))))
14103 (setq match (org-completing-read-no-i
14104 "Match: " 'org-tags-completion-function nil nil nil
14105 'org-tags-history))))
14107 ;; Parse the string and create a lisp form
14108 (let ((match0 match)
14109 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14110 minus tag mm
14111 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14112 orterms term orlist re-p str-p level-p level-op time-p
14113 prop-p pn pv po gv rest (start 0) (ss 0))
14114 ;; Expand group tags
14115 (setq match (org-tags-expand match))
14117 ;; Check if there is a TODO part of this match, which would be the
14118 ;; part after a "/". TO make sure that this slash is not part of
14119 ;; a property value to be matched against, we also check that there
14120 ;; is no " after that slash.
14121 ;; First, find the last slash
14122 (while (string-match "/+" match ss)
14123 (setq start (match-beginning 0) ss (match-end 0)))
14124 (if (and (string-match "/+" match start)
14125 (not (save-match-data (string-match "\"" match start))))
14126 ;; match contains also a todo-matching request
14127 (progn
14128 (setq tagsmatch (substring match 0 (match-beginning 0))
14129 todomatch (substring match (match-end 0)))
14130 (if (string-match "^!" todomatch)
14131 (setq todo-only t todomatch (substring todomatch 1)))
14132 (if (string-match "^\\s-*$" todomatch)
14133 (setq todomatch nil)))
14134 ;; only matching tags
14135 (setq tagsmatch match todomatch nil))
14137 ;; Make the tags matcher
14138 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14139 (setq tagsmatcher t)
14140 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14141 (while (setq term (pop orterms))
14142 (while (and (equal (substring term -1) "\\") orterms)
14143 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14144 (while (string-match re term)
14145 (setq rest (substring term (match-end 0))
14146 minus (and (match-end 1)
14147 (equal (match-string 1 term) "-"))
14148 tag (save-match-data (replace-regexp-in-string
14149 "\\\\-" "-"
14150 (match-string 2 term)))
14151 re-p (equal (string-to-char tag) ?{)
14152 level-p (match-end 4)
14153 prop-p (match-end 5)
14154 mm (cond
14155 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14156 (level-p
14157 (setq level-op (org-op-to-function (match-string 3 term)))
14158 `(,level-op level ,(string-to-number
14159 (match-string 4 term))))
14160 (prop-p
14161 (setq pn (match-string 5 term)
14162 po (match-string 6 term)
14163 pv (match-string 7 term)
14164 re-p (equal (string-to-char pv) ?{)
14165 str-p (equal (string-to-char pv) ?\")
14166 time-p (save-match-data
14167 (string-match "^\"[[<].*[]>]\"$" pv))
14168 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14169 (if time-p (setq pv (org-matcher-time pv)))
14170 (setq po (org-op-to-function po (if time-p 'time str-p)))
14171 (cond
14172 ((equal pn "CATEGORY")
14173 (setq gv '(get-text-property (point) 'org-category)))
14174 ((equal pn "TODO")
14175 (setq gv 'todo))
14177 (setq gv `(org-cached-entry-get nil ,pn))))
14178 (if re-p
14179 (if (eq po 'org<>)
14180 `(not (string-match ,pv (or ,gv "")))
14181 `(string-match ,pv (or ,gv "")))
14182 (if str-p
14183 `(,po (or ,gv "") ,pv)
14184 `(,po (string-to-number (or ,gv ""))
14185 ,(string-to-number pv) ))))
14186 (t `(member ,tag tags-list)))
14187 mm (if minus (list 'not mm) mm)
14188 term rest)
14189 (push mm tagsmatcher))
14190 (push (if (> (length tagsmatcher) 1)
14191 (cons 'and tagsmatcher)
14192 (car tagsmatcher))
14193 orlist)
14194 (setq tagsmatcher nil))
14195 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14196 (setq tagsmatcher
14197 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14198 ;; Make the todo matcher
14199 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14200 (setq todomatcher t)
14201 (setq orterms (org-split-string todomatch "|") orlist nil)
14202 (while (setq term (pop orterms))
14203 (while (string-match re term)
14204 (setq minus (and (match-end 1)
14205 (equal (match-string 1 term) "-"))
14206 kwd (match-string 2 term)
14207 re-p (equal (string-to-char kwd) ?{)
14208 term (substring term (match-end 0))
14209 mm (if re-p
14210 `(string-match ,(substring kwd 1 -1) todo)
14211 (list 'equal 'todo kwd))
14212 mm (if minus (list 'not mm) mm))
14213 (push mm todomatcher))
14214 (push (if (> (length todomatcher) 1)
14215 (cons 'and todomatcher)
14216 (car todomatcher))
14217 orlist)
14218 (setq todomatcher nil))
14219 (setq todomatcher (if (> (length orlist) 1)
14220 (cons 'or orlist) (car orlist))))
14222 ;; Return the string and lisp forms of the matcher
14223 (setq matcher (if todomatcher
14224 (list 'and tagsmatcher todomatcher)
14225 tagsmatcher))
14226 (when todo-only
14227 (setq matcher (list 'and '(member todo org-not-done-keywords)
14228 matcher)))
14229 (cons match0 matcher)))
14231 (defun org-tags-expand (match &optional single-as-list downcased)
14232 "Expand group tags in MATCH.
14234 This replaces every group tag in MATCH with a regexp tag search.
14235 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14236 will be replaced like this:
14238 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14239 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14240 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14242 Replacing by a regexp preserves the structure of the match.
14243 E.g., this expansion
14245 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14247 will match anything tagged with \"Lab\" and \"Home\", or tagged
14248 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14250 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14251 assumed to be a single group tag, and the function will return
14252 the list of tags in this group.
14254 When DOWNCASE is non-nil, expand downcased TAGS."
14255 (if org-group-tags
14256 (let* ((case-fold-search t)
14257 (stable org-mode-syntax-table)
14258 (tal (or org-tag-groups-alist-for-agenda
14259 org-tag-groups-alist))
14260 (tal (if downcased
14261 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14262 (tml (mapcar 'car tal))
14263 (rtnmatch match) rpl)
14264 ;; @ and _ are allowed as word-components in tags
14265 (modify-syntax-entry ?@ "w" stable)
14266 (modify-syntax-entry ?_ "w" stable)
14267 (while (and tml
14268 (with-syntax-table stable
14269 (string-match
14270 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14271 (regexp-opt tml) "\\>\\)") rtnmatch)))
14272 (let* ((dir (match-string 1 rtnmatch))
14273 (tag (match-string 2 rtnmatch))
14274 (tag (if downcased (downcase tag) tag)))
14275 (setq tml (delete tag tml))
14276 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14277 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14278 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14279 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14280 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14281 (if single-as-list
14282 (or (reverse rpl) (list rtnmatch))
14283 rtnmatch))
14284 (if single-as-list (list (if downcased (downcase match) match))
14285 match)))
14287 (defun org-op-to-function (op &optional stringp)
14288 "Turn an operator into the appropriate function."
14289 (setq op
14290 (cond
14291 ((equal op "<" ) '(< string< org-time<))
14292 ((equal op ">" ) '(> org-string> org-time>))
14293 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14294 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14295 ((member op '("=" "==")) '(= string= org-time=))
14296 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14297 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14299 (defun org<> (a b) (not (= a b)))
14300 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14301 (defun org-string>= (a b) (not (string< a b)))
14302 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14303 (defun org-string<> (a b) (not (string= a b)))
14304 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14305 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14306 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14307 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14308 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14309 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14310 (defun org-2ft (s)
14311 "Convert S to a floating point time.
14312 If S is already a number, just return it. If it is a string, parse
14313 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14314 (cond
14315 ((numberp s) s)
14316 ((stringp s)
14317 (condition-case nil
14318 (float-time (apply 'encode-time (org-parse-time-string s)))
14319 (error 0.)))
14320 (t 0.)))
14322 (defun org-time-today ()
14323 "Time in seconds today at 0:00.
14324 Returns the float number of seconds since the beginning of the
14325 epoch to the beginning of today (00:00)."
14326 (float-time (apply 'encode-time
14327 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14329 (defun org-matcher-time (s)
14330 "Interpret a time comparison value."
14331 (save-match-data
14332 (cond
14333 ((string= s "<now>") (float-time))
14334 ((string= s "<today>") (org-time-today))
14335 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14336 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14337 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14338 (+ (org-time-today)
14339 (* (string-to-number (match-string 1 s))
14340 (cdr (assoc (match-string 2 s)
14341 '(("d" . 86400.0) ("w" . 604800.0)
14342 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14343 (t (org-2ft s)))))
14345 (defun org-match-any-p (re list)
14346 "Does re match any element of list?"
14347 (setq list (mapcar (lambda (x) (string-match re x)) list))
14348 (delq nil list))
14350 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14351 (defvar org-tags-overlay (make-overlay 1 1))
14352 (org-detach-overlay org-tags-overlay)
14354 (defun org-get-local-tags-at (&optional pos)
14355 "Get a list of tags defined in the current headline."
14356 (org-get-tags-at pos 'local))
14358 (defun org-get-local-tags ()
14359 "Get a list of tags defined in the current headline."
14360 (org-get-tags-at nil 'local))
14362 (defun org-get-tags-at (&optional pos local)
14363 "Get a list of all headline tags applicable at POS.
14364 POS defaults to point. If tags are inherited, the list contains
14365 the targets in the same sequence as the headlines appear, i.e.
14366 the tags of the current headline come last.
14367 When LOCAL is non-nil, only return tags from the current headline,
14368 ignore inherited ones."
14369 (interactive)
14370 (if (and org-trust-scanner-tags
14371 (or (not pos) (equal pos (point)))
14372 (not local))
14373 org-scanner-tags
14374 (let (tags ltags lastpos parent)
14375 (save-excursion
14376 (save-restriction
14377 (widen)
14378 (goto-char (or pos (point)))
14379 (save-match-data
14380 (catch 'done
14381 (condition-case nil
14382 (progn
14383 (org-back-to-heading t)
14384 (while (not (equal lastpos (point)))
14385 (setq lastpos (point))
14386 (when (looking-at
14387 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14388 (setq ltags (org-split-string
14389 (org-match-string-no-properties 1) ":"))
14390 (when parent
14391 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14392 (setq tags (append
14393 (if parent
14394 (org-remove-uninherited-tags ltags)
14395 ltags)
14396 tags)))
14397 (or org-use-tag-inheritance (throw 'done t))
14398 (if local (throw 'done t))
14399 (or (org-up-heading-safe) (error nil))
14400 (setq parent t)))
14401 (error nil)))))
14402 (if local
14403 tags
14404 (reverse (delete-dups
14405 (reverse (append
14406 (org-remove-uninherited-tags
14407 org-file-tags) tags)))))))))
14409 (defun org-add-prop-inherited (s)
14410 (add-text-properties 0 (length s) '(inherited t) s)
14413 (defun org-toggle-tag (tag &optional onoff)
14414 "Toggle the tag TAG for the current line.
14415 If ONOFF is `on' or `off', don't toggle but set to this state."
14416 (let (res current)
14417 (save-excursion
14418 (org-back-to-heading t)
14419 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14420 (point-at-eol) t)
14421 (progn
14422 (setq current (match-string 1))
14423 (replace-match ""))
14424 (setq current ""))
14425 (setq current (nreverse (org-split-string current ":")))
14426 (cond
14427 ((eq onoff 'on)
14428 (setq res t)
14429 (or (member tag current) (push tag current)))
14430 ((eq onoff 'off)
14431 (or (not (member tag current)) (setq current (delete tag current))))
14432 (t (if (member tag current)
14433 (setq current (delete tag current))
14434 (setq res t)
14435 (push tag current))))
14436 (end-of-line 1)
14437 (if current
14438 (progn
14439 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14440 (org-set-tags nil t))
14441 (delete-horizontal-space))
14442 (run-hooks 'org-after-tags-change-hook))
14443 res))
14445 (defun org-align-tags-here (to-col)
14446 ;; Assumes that this is a headline
14447 "Align tags on the current headline to TO-COL."
14448 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14449 (beginning-of-line 1)
14450 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14451 (< pos (match-beginning 2)))
14452 (progn
14453 (setq tags-l (- (match-end 2) (match-beginning 2)))
14454 (goto-char (match-beginning 1))
14455 (insert " ")
14456 (delete-region (point) (1+ (match-beginning 2)))
14457 (setq ncol (max (current-column)
14458 (1+ col)
14459 (if (> to-col 0)
14460 to-col
14461 (- (abs to-col) tags-l))))
14462 (setq p (point))
14463 (insert (make-string (- ncol (current-column)) ?\ ))
14464 (setq ncol (current-column))
14465 (when indent-tabs-mode (tabify p (point-at-eol)))
14466 (org-move-to-column (min ncol col)))
14467 (goto-char pos))))
14469 (defun org-set-tags-command (&optional arg just-align)
14470 "Call the set-tags command for the current entry."
14471 (interactive "P")
14472 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14473 (org-set-tags arg just-align)
14474 (save-excursion
14475 (unless (and (org-region-active-p)
14476 org-loop-over-headlines-in-active-region)
14477 (org-back-to-heading t))
14478 (org-set-tags arg just-align))))
14480 (defun org-set-tags-to (data)
14481 "Set the tags of the current entry to DATA, replacing the current tags.
14482 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14483 If DATA is nil or the empty string, any tags will be removed."
14484 (interactive "sTags: ")
14485 (setq data
14486 (cond
14487 ((eq data nil) "")
14488 ((equal data "") "")
14489 ((stringp data)
14490 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14491 ":"))
14492 ((listp data)
14493 (concat ":" (mapconcat 'identity data ":") ":"))))
14494 (when data
14495 (save-excursion
14496 (org-back-to-heading t)
14497 (when (looking-at org-complex-heading-regexp)
14498 (if (match-end 5)
14499 (progn
14500 (goto-char (match-beginning 5))
14501 (insert data)
14502 (delete-region (point) (point-at-eol))
14503 (org-set-tags nil 'align))
14504 (goto-char (point-at-eol))
14505 (insert " " data)
14506 (org-set-tags nil 'align)))
14507 (beginning-of-line 1)
14508 (if (looking-at ".*?\\([ \t]+\\)$")
14509 (delete-region (match-beginning 1) (match-end 1))))))
14511 (defun org-align-all-tags ()
14512 "Align the tags i all headings."
14513 (interactive)
14514 (save-excursion
14515 (or (ignore-errors (org-back-to-heading t))
14516 (outline-next-heading))
14517 (if (org-at-heading-p)
14518 (org-set-tags t)
14519 (message "No headings"))))
14521 (defvar org-indent-indentation-per-level)
14522 (defun org-set-tags (&optional arg just-align)
14523 "Set the tags for the current headline.
14524 With prefix ARG, realign all tags in headings in the current buffer.
14525 When JUST-ALIGN is non-nil, only align tags."
14526 (interactive "P")
14527 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14528 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14529 'region-start-level 'region))
14530 org-loop-over-headlines-in-active-region)
14531 (org-map-entries
14532 ;; We don't use ARG and JUST-ALIGN here because these args
14533 ;; are not useful when looping over headlines.
14534 `(org-set-tags)
14535 org-loop-over-headlines-in-active-region
14536 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14537 (let* ((re org-outline-regexp-bol)
14538 (current (unless arg (org-get-tags-string)))
14539 (col (current-column))
14540 (org-setting-tags t)
14541 table current-tags inherited-tags ; computed below when needed
14542 tags p0 c0 c1 rpl di tc level)
14543 (if arg
14544 (save-excursion
14545 (goto-char (point-min))
14546 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14547 (while (re-search-forward re nil t)
14548 (org-set-tags nil t)
14549 (end-of-line 1)))
14550 (message "All tags realigned to column %d" org-tags-column))
14551 (if just-align
14552 (setq tags current)
14553 ;; Get a new set of tags from the user
14554 (save-excursion
14555 (setq table (append org-tag-persistent-alist
14556 (or org-tag-alist (org-get-buffer-tags))
14557 (and
14558 org-complete-tags-always-offer-all-agenda-tags
14559 (org-global-tags-completion-table
14560 (org-agenda-files))))
14561 org-last-tags-completion-table table
14562 current-tags (org-split-string current ":")
14563 inherited-tags (nreverse
14564 (nthcdr (length current-tags)
14565 (nreverse (org-get-tags-at))))
14566 tags
14567 (if (or (eq t org-use-fast-tag-selection)
14568 (and org-use-fast-tag-selection
14569 (delq nil (mapcar 'cdr table))))
14570 (org-fast-tag-selection
14571 current-tags inherited-tags table
14572 (if org-fast-tag-selection-include-todo
14573 org-todo-key-alist))
14574 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14575 (org-trim
14576 (org-icompleting-read "Tags: "
14577 'org-tags-completion-function
14578 nil nil current 'org-tags-history))))))
14579 (while (string-match "[-+&]+" tags)
14580 ;; No boolean logic, just a list
14581 (setq tags (replace-match ":" t t tags))))
14583 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14585 (if org-tags-sort-function
14586 (setq tags (mapconcat 'identity
14587 (sort (org-split-string
14588 tags (org-re "[^[:alnum:]_@#%]+"))
14589 org-tags-sort-function) ":")))
14591 (if (string-match "\\`[\t ]*\\'" tags)
14592 (setq tags "")
14593 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14594 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14596 ;; Insert new tags at the correct column
14597 (beginning-of-line 1)
14598 (setq level (or (and (looking-at org-outline-regexp)
14599 (- (match-end 0) (point) 1))
14601 (cond
14602 ((and (equal current "") (equal tags "")))
14603 ((re-search-forward
14604 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14605 (point-at-eol) t)
14606 (if (equal tags "")
14607 (setq rpl "")
14608 (goto-char (match-beginning 0))
14609 (setq c0 (current-column)
14610 ;; compute offset for the case of org-indent-mode active
14611 di (if (org-bound-and-true-p org-indent-mode)
14612 (* (1- org-indent-indentation-per-level) (1- level))
14614 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14615 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14616 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14617 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14618 (replace-match rpl t t)
14619 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14620 tags)
14621 (t (error "Tags alignment failed")))
14622 (org-move-to-column col)
14623 (unless just-align
14624 (run-hooks 'org-after-tags-change-hook))))))
14626 (defun org-change-tag-in-region (beg end tag off)
14627 "Add or remove TAG for each entry in the region.
14628 This works in the agenda, and also in an org-mode buffer."
14629 (interactive
14630 (list (region-beginning) (region-end)
14631 (let ((org-last-tags-completion-table
14632 (if (derived-mode-p 'org-mode)
14633 (org-uniquify
14634 (delq nil (append (org-get-buffer-tags)
14635 (org-global-tags-completion-table))))
14636 (org-global-tags-completion-table))))
14637 (org-icompleting-read
14638 "Tag: " 'org-tags-completion-function nil nil nil
14639 'org-tags-history))
14640 (progn
14641 (message "[s]et or [r]emove? ")
14642 (equal (read-char-exclusive) ?r))))
14643 (if (fboundp 'deactivate-mark) (deactivate-mark))
14644 (let ((agendap (equal major-mode 'org-agenda-mode))
14645 l1 l2 m buf pos newhead (cnt 0))
14646 (goto-char end)
14647 (setq l2 (1- (org-current-line)))
14648 (goto-char beg)
14649 (setq l1 (org-current-line))
14650 (loop for l from l1 to l2 do
14651 (org-goto-line l)
14652 (setq m (get-text-property (point) 'org-hd-marker))
14653 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14654 (and agendap m))
14655 (setq buf (if agendap (marker-buffer m) (current-buffer))
14656 pos (if agendap m (point)))
14657 (with-current-buffer buf
14658 (save-excursion
14659 (save-restriction
14660 (goto-char pos)
14661 (setq cnt (1+ cnt))
14662 (org-toggle-tag tag (if off 'off 'on))
14663 (setq newhead (org-get-heading)))))
14664 (and agendap (org-agenda-change-all-lines newhead m))))
14665 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14667 (defun org-tags-completion-function (string predicate &optional flag)
14668 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14669 (confirm (lambda (x) (stringp (car x)))))
14670 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14671 (setq s1 (match-string 1 string)
14672 s2 (match-string 2 string))
14673 (setq s1 "" s2 string))
14674 (cond
14675 ((eq flag nil)
14676 ;; try completion
14677 (setq rtn (try-completion s2 ctable confirm))
14678 (if (stringp rtn)
14679 (setq rtn
14680 (concat s1 s2 (substring rtn (length s2))
14681 (if (and org-add-colon-after-tag-completion
14682 (assoc rtn ctable))
14683 ":" ""))))
14684 rtn)
14685 ((eq flag t)
14686 ;; all-completions
14687 (all-completions s2 ctable confirm))
14688 ((eq flag 'lambda)
14689 ;; exact match?
14690 (assoc s2 ctable)))))
14692 (defun org-fast-tag-insert (kwd tags face &optional end)
14693 "Insert KDW, and the TAGS, the latter with face FACE.
14694 Also insert END."
14695 (insert (format "%-12s" (concat kwd ":"))
14696 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14697 (or end "")))
14699 (defun org-fast-tag-show-exit (flag)
14700 (save-excursion
14701 (org-goto-line 3)
14702 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14703 (replace-match ""))
14704 (when flag
14705 (end-of-line 1)
14706 (org-move-to-column (- (window-width) 19) t)
14707 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14709 (defun org-set-current-tags-overlay (current prefix)
14710 "Add an overlay to CURRENT tag with PREFIX."
14711 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14712 (if (featurep 'xemacs)
14713 (org-overlay-display org-tags-overlay (concat prefix s)
14714 'secondary-selection)
14715 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14716 (org-overlay-display org-tags-overlay (concat prefix s)))))
14718 (defvar org-last-tag-selection-key nil)
14719 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14720 "Fast tag selection with single keys.
14721 CURRENT is the current list of tags in the headline, INHERITED is the
14722 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14723 possibly with grouping information. TODO-TABLE is a similar table with
14724 TODO keywords, should these have keys assigned to them.
14725 If the keys are nil, a-z are automatically assigned.
14726 Returns the new tags string, or nil to not change the current settings."
14727 (let* ((fulltable (append table todo-table))
14728 (maxlen (apply 'max (mapcar
14729 (lambda (x)
14730 (if (stringp (car x)) (string-width (car x)) 0))
14731 fulltable)))
14732 (buf (current-buffer))
14733 (expert (eq org-fast-tag-selection-single-key 'expert))
14734 (buffer-tags nil)
14735 (fwidth (+ maxlen 3 1 3))
14736 (ncol (/ (- (window-width) 4) fwidth))
14737 (i-face 'org-done)
14738 (c-face 'org-todo)
14739 tg cnt e c char c1 c2 ntable tbl rtn
14740 ov-start ov-end ov-prefix
14741 (exit-after-next org-fast-tag-selection-single-key)
14742 (done-keywords org-done-keywords)
14743 groups ingroup)
14744 (save-excursion
14745 (beginning-of-line 1)
14746 (if (looking-at
14747 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14748 (setq ov-start (match-beginning 1)
14749 ov-end (match-end 1)
14750 ov-prefix "")
14751 (setq ov-start (1- (point-at-eol))
14752 ov-end (1+ ov-start))
14753 (skip-chars-forward "^\n\r")
14754 (setq ov-prefix
14755 (concat
14756 (buffer-substring (1- (point)) (point))
14757 (if (> (current-column) org-tags-column)
14759 (make-string (- org-tags-column (current-column)) ?\ ))))))
14760 (move-overlay org-tags-overlay ov-start ov-end)
14761 (save-window-excursion
14762 (if expert
14763 (set-buffer (get-buffer-create " *Org tags*"))
14764 (delete-other-windows)
14765 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
14766 (org-switch-to-buffer-other-window " *Org tags*"))
14767 (erase-buffer)
14768 (org-set-local 'org-done-keywords done-keywords)
14769 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14770 (org-fast-tag-insert "Current" current c-face "\n\n")
14771 (org-fast-tag-show-exit exit-after-next)
14772 (org-set-current-tags-overlay current ov-prefix)
14773 (setq tbl fulltable char ?a cnt 0)
14774 (while (setq e (pop tbl))
14775 (cond
14776 ((equal (car e) :startgroup)
14777 (push '() groups) (setq ingroup t)
14778 (when (not (= cnt 0))
14779 (setq cnt 0)
14780 (insert "\n"))
14781 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14782 ((equal (car e) :endgroup)
14783 (setq ingroup nil cnt 0)
14784 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14785 ((equal e '(:newline))
14786 (when (not (= cnt 0))
14787 (setq cnt 0)
14788 (insert "\n")
14789 (setq e (car tbl))
14790 (while (equal (car tbl) '(:newline))
14791 (insert "\n")
14792 (setq tbl (cdr tbl)))))
14793 ((equal e '(:grouptags)) nil)
14795 (setq tg (copy-sequence (car e)) c2 nil)
14796 (if (cdr e)
14797 (setq c (cdr e))
14798 ;; automatically assign a character.
14799 (setq c1 (string-to-char
14800 (downcase (substring
14801 tg (if (= (string-to-char tg) ?@) 1 0)))))
14802 (if (or (rassoc c1 ntable) (rassoc c1 table))
14803 (while (or (rassoc char ntable) (rassoc char table))
14804 (setq char (1+ char)))
14805 (setq c2 c1))
14806 (setq c (or c2 char)))
14807 (if ingroup (push tg (car groups)))
14808 (setq tg (org-add-props tg nil 'face
14809 (cond
14810 ((not (assoc tg table))
14811 (org-get-todo-face tg))
14812 ((member tg current) c-face)
14813 ((member tg inherited) i-face))))
14814 (if (equal (caar tbl) :grouptags)
14815 (org-add-props tg nil 'face 'org-tag-group))
14816 (if (and (= cnt 0) (not ingroup)) (insert " "))
14817 (insert "[" c "] " tg (make-string
14818 (- fwidth 4 (length tg)) ?\ ))
14819 (push (cons tg c) ntable)
14820 (when (= (setq cnt (1+ cnt)) ncol)
14821 (insert "\n")
14822 (if ingroup (insert " "))
14823 (setq cnt 0)))))
14824 (setq ntable (nreverse ntable))
14825 (insert "\n")
14826 (goto-char (point-min))
14827 (if (not expert) (org-fit-window-to-buffer))
14828 (setq rtn
14829 (catch 'exit
14830 (while t
14831 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14832 (if (not groups) "no " "")
14833 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14834 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14835 (setq org-last-tag-selection-key c)
14836 (cond
14837 ((= c ?\r) (throw 'exit t))
14838 ((= c ?!)
14839 (setq groups (not groups))
14840 (goto-char (point-min))
14841 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14842 ((= c ?\C-c)
14843 (if (not expert)
14844 (org-fast-tag-show-exit
14845 (setq exit-after-next (not exit-after-next)))
14846 (setq expert nil)
14847 (delete-other-windows)
14848 (set-window-buffer (split-window-vertically) " *Org tags*")
14849 (org-switch-to-buffer-other-window " *Org tags*")
14850 (org-fit-window-to-buffer)))
14851 ((or (= c ?\C-g)
14852 (and (= c ?q) (not (rassoc c ntable))))
14853 (org-detach-overlay org-tags-overlay)
14854 (setq quit-flag t))
14855 ((= c ?\ )
14856 (setq current nil)
14857 (if exit-after-next (setq exit-after-next 'now)))
14858 ((= c ?\t)
14859 (condition-case nil
14860 (setq tg (org-icompleting-read
14861 "Tag: "
14862 (or buffer-tags
14863 (with-current-buffer buf
14864 (org-get-buffer-tags)))))
14865 (quit (setq tg "")))
14866 (when (string-match "\\S-" tg)
14867 (add-to-list 'buffer-tags (list tg))
14868 (if (member tg current)
14869 (setq current (delete tg current))
14870 (push tg current)))
14871 (if exit-after-next (setq exit-after-next 'now)))
14872 ((setq e (rassoc c todo-table) tg (car e))
14873 (with-current-buffer buf
14874 (save-excursion (org-todo tg)))
14875 (if exit-after-next (setq exit-after-next 'now)))
14876 ((setq e (rassoc c ntable) tg (car e))
14877 (if (member tg current)
14878 (setq current (delete tg current))
14879 (loop for g in groups do
14880 (if (member tg g)
14881 (mapc (lambda (x)
14882 (setq current (delete x current)))
14883 g)))
14884 (push tg current))
14885 (if exit-after-next (setq exit-after-next 'now))))
14887 ;; Create a sorted list
14888 (setq current
14889 (sort current
14890 (lambda (a b)
14891 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14892 (if (eq exit-after-next 'now) (throw 'exit t))
14893 (goto-char (point-min))
14894 (beginning-of-line 2)
14895 (delete-region (point) (point-at-eol))
14896 (org-fast-tag-insert "Current" current c-face)
14897 (org-set-current-tags-overlay current ov-prefix)
14898 (while (re-search-forward
14899 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14900 (setq tg (match-string 1))
14901 (add-text-properties
14902 (match-beginning 1) (match-end 1)
14903 (list 'face
14904 (cond
14905 ((member tg current) c-face)
14906 ((member tg inherited) i-face)
14907 (t (get-text-property (match-beginning 1) 'face))))))
14908 (goto-char (point-min)))))
14909 (org-detach-overlay org-tags-overlay)
14910 (if rtn
14911 (mapconcat 'identity current ":")
14912 nil))))
14914 (defun org-get-tags-string ()
14915 "Get the TAGS string in the current headline."
14916 (unless (org-at-heading-p t)
14917 (user-error "Not on a heading"))
14918 (save-excursion
14919 (beginning-of-line 1)
14920 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14921 (org-match-string-no-properties 1)
14922 "")))
14924 (defun org-get-tags ()
14925 "Get the list of tags specified in the current headline."
14926 (org-split-string (org-get-tags-string) ":"))
14928 (defun org-get-buffer-tags ()
14929 "Get a table of all tags used in the buffer, for completion."
14930 (let (tags)
14931 (save-excursion
14932 (goto-char (point-min))
14933 (while (re-search-forward
14934 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14935 (when (equal (char-after (point-at-bol 0)) ?*)
14936 (mapc (lambda (x) (add-to-list 'tags x))
14937 (org-split-string (org-match-string-no-properties 1) ":")))))
14938 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14939 (mapcar 'list tags)))
14941 ;;;; The mapping API
14943 (defun org-map-entries (func &optional match scope &rest skip)
14944 "Call FUNC at each headline selected by MATCH in SCOPE.
14946 FUNC is a function or a lisp form. The function will be called without
14947 arguments, with the cursor positioned at the beginning of the headline.
14948 The return values of all calls to the function will be collected and
14949 returned as a list.
14951 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14952 does not need to preserve point. After evaluation, the cursor will be
14953 moved to the end of the line (presumably of the headline of the
14954 processed entry) and search continues from there. Under some
14955 circumstances, this may not produce the wanted results. For example,
14956 if you have removed (e.g. archived) the current (sub)tree it could
14957 mean that the next entry will be skipped entirely. In such cases, you
14958 can specify the position from where search should continue by making
14959 FUNC set the variable `org-map-continue-from' to the desired buffer
14960 position.
14962 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14963 Only headlines that are matched by this query will be considered during
14964 the iteration. When MATCH is nil or t, all headlines will be
14965 visited by the iteration.
14967 SCOPE determines the scope of this command. It can be any of:
14969 nil The current buffer, respecting the restriction if any
14970 tree The subtree started with the entry at point
14971 region The entries within the active region, if any
14972 region-start-level
14973 The entries within the active region, but only those at
14974 the same level than the first one.
14975 file The current buffer, without restriction
14976 file-with-archives
14977 The current buffer, and any archives associated with it
14978 agenda All agenda files
14979 agenda-with-archives
14980 All agenda files with any archive files associated with them
14981 \(file1 file2 ...)
14982 If this is a list, all files in the list will be scanned
14984 The remaining args are treated as settings for the skipping facilities of
14985 the scanner. The following items can be given here:
14987 archive skip trees with the archive tag
14988 comment skip trees with the COMMENT keyword
14989 function or Emacs Lisp form:
14990 will be used as value for `org-agenda-skip-function', so
14991 whenever the function returns a position, FUNC will not be
14992 called for that entry and search will continue from the
14993 position returned
14995 If your function needs to retrieve the tags including inherited tags
14996 at the *current* entry, you can use the value of the variable
14997 `org-scanner-tags' which will be much faster than getting the value
14998 with `org-get-tags-at'. If your function gets properties with
14999 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15000 to t around the call to `org-entry-properties' to get the same speedup.
15001 Note that if your function moves around to retrieve tags and properties at
15002 a *different* entry, you cannot use these techniques."
15003 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15004 (not (org-region-active-p)))
15005 (let* ((org-agenda-archives-mode nil) ; just to make sure
15006 (org-agenda-skip-archived-trees (memq 'archive skip))
15007 (org-agenda-skip-comment-trees (memq 'comment skip))
15008 (org-agenda-skip-function
15009 (car (org-delete-all '(comment archive) skip)))
15010 (org-tags-match-list-sublevels t)
15011 (start-level (eq scope 'region-start-level))
15012 matcher file res
15013 org-todo-keywords-for-agenda
15014 org-done-keywords-for-agenda
15015 org-todo-keyword-alist-for-agenda
15016 org-drawers-for-agenda
15017 org-tag-alist-for-agenda
15018 todo-only)
15020 (cond
15021 ((eq match t) (setq matcher t))
15022 ((eq match nil) (setq matcher t))
15023 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15025 (save-excursion
15026 (save-restriction
15027 (cond ((eq scope 'tree)
15028 (org-back-to-heading t)
15029 (org-narrow-to-subtree)
15030 (setq scope nil))
15031 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15032 (org-region-active-p))
15033 ;; If needed, set start-level to a string like "2"
15034 (when start-level
15035 (save-excursion
15036 (goto-char (region-beginning))
15037 (unless (org-at-heading-p) (outline-next-heading))
15038 (setq start-level (org-current-level))))
15039 (narrow-to-region (region-beginning)
15040 (save-excursion
15041 (goto-char (region-end))
15042 (unless (and (bolp) (org-at-heading-p))
15043 (outline-next-heading))
15044 (point)))
15045 (setq scope nil)))
15047 (if (not scope)
15048 (progn
15049 (org-agenda-prepare-buffers
15050 (list (buffer-file-name (current-buffer))))
15051 (setq res (org-scan-tags func matcher todo-only start-level)))
15052 ;; Get the right scope
15053 (cond
15054 ((and scope (listp scope) (symbolp (car scope)))
15055 (setq scope (eval scope)))
15056 ((eq scope 'agenda)
15057 (setq scope (org-agenda-files t)))
15058 ((eq scope 'agenda-with-archives)
15059 (setq scope (org-agenda-files t))
15060 (setq scope (org-add-archive-files scope)))
15061 ((eq scope 'file)
15062 (setq scope (list (buffer-file-name))))
15063 ((eq scope 'file-with-archives)
15064 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15065 (org-agenda-prepare-buffers scope)
15066 (while (setq file (pop scope))
15067 (with-current-buffer (org-find-base-buffer-visiting file)
15068 (save-excursion
15069 (save-restriction
15070 (widen)
15071 (goto-char (point-min))
15072 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
15073 res)))
15075 ;;;; Properties
15077 ;;; Setting and retrieving properties
15079 (defconst org-special-properties
15080 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
15081 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
15082 "The special properties valid in Org-mode.
15084 These are properties that are not defined in the property drawer,
15085 but in some other way.")
15087 (defconst org-default-properties
15088 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15089 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15090 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15091 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15092 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
15093 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15094 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15095 "Some properties that are used by Org-mode for various purposes.
15096 Being in this list makes sure that they are offered for completion.")
15098 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
15099 "Regular expression matching the first line of a property drawer.")
15101 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
15102 "Regular expression matching the last line of a property drawer.")
15104 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
15105 "Regular expression matching the first line of a property drawer.")
15107 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
15108 "Regular expression matching the first line of a property drawer.")
15110 (defconst org-property-drawer-re
15111 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
15112 org-property-end-re "\\)\n?")
15113 "Matches an entire property drawer.")
15115 (defconst org-clock-drawer-re
15116 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
15117 org-property-end-re "\\)\n?")
15118 "Matches an entire clock drawer.")
15120 (defun org-property-action ()
15121 "Do an action on properties."
15122 (interactive)
15123 (let (c)
15124 (org-at-property-p)
15125 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15126 (setq c (read-char-exclusive))
15127 (cond
15128 ((equal c ?s)
15129 (call-interactively 'org-set-property))
15130 ((equal c ?d)
15131 (call-interactively 'org-delete-property))
15132 ((equal c ?D)
15133 (call-interactively 'org-delete-property-globally))
15134 ((equal c ?c)
15135 (call-interactively 'org-compute-property-at-point))
15136 (t (user-error "No such property action %c" c)))))
15138 (defun org-inc-effort ()
15139 "Increment the value of the effort property in the current entry."
15140 (interactive)
15141 (org-set-effort nil t))
15143 (defvar org-clock-effort) ;; Defined in org-clock.el
15144 (defvar org-clock-current-task) ;; Defined in org-clock.el
15145 (defun org-set-effort (&optional value increment)
15146 "Set the effort property of the current entry.
15147 With numerical prefix arg, use the nth allowed value, 0 stands for the
15148 10th allowed value.
15150 When INCREMENT is non-nil, set the property to the next allowed value."
15151 (interactive "P")
15152 (if (equal value 0) (setq value 10))
15153 (let* ((completion-ignore-case t)
15154 (prop org-effort-property)
15155 (cur (org-entry-get nil prop))
15156 (allowed (org-property-get-allowed-values nil prop 'table))
15157 (existing (mapcar 'list (org-property-values prop)))
15158 (heading (nth 4 (org-heading-components)))
15160 (val (cond
15161 ((stringp value) value)
15162 ((and allowed (integerp value))
15163 (or (car (nth (1- value) allowed))
15164 (car (org-last allowed))))
15165 ((and allowed increment)
15166 (or (caadr (member (list cur) allowed))
15167 (user-error "Allowed effort values are not set")))
15168 (allowed
15169 (message "Select 1-9,0, [RET%s]: %s"
15170 (if cur (concat "=" cur) "")
15171 (mapconcat 'car allowed " "))
15172 (setq rpl (read-char-exclusive))
15173 (if (equal rpl ?\r)
15175 (setq rpl (- rpl ?0))
15176 (if (equal rpl 0) (setq rpl 10))
15177 (if (and (> rpl 0) (<= rpl (length allowed)))
15178 (car (nth (1- rpl) allowed))
15179 (org-completing-read "Effort: " allowed nil))))
15181 (let (org-completion-use-ido org-completion-use-iswitchb)
15182 (org-completing-read
15183 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15184 (concat "[" cur "]") "")
15185 ": ")
15186 existing nil nil "" nil cur))))))
15187 (unless (equal (org-entry-get nil prop) val)
15188 (org-entry-put nil prop val))
15189 (save-excursion
15190 (org-back-to-heading t)
15191 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
15192 (when (string= heading org-clock-current-task)
15193 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
15194 (org-clock-update-mode-line))
15195 (message "%s is now %s" prop val)))
15197 (defun org-at-property-p ()
15198 "Is cursor inside a property drawer?"
15199 (save-excursion
15200 (when (equal 'node-property (car (org-element-at-point)))
15201 (beginning-of-line 1)
15202 (looking-at org-property-re))))
15204 (defun org-get-property-block (&optional beg end force)
15205 "Return the (beg . end) range of the body of the property drawer.
15206 BEG and END are the beginning and end of the current subtree, or of
15207 the part before the first headline. If they are not given, they will
15208 be found. If the drawer does not exist and FORCE is non-nil, create
15209 the drawer."
15210 (catch 'exit
15211 (save-excursion
15212 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15213 (progn (org-back-to-heading t) (point))))
15214 (end (or end (and (not (outline-next-heading)) (point-max))
15215 (point))))
15216 (goto-char beg)
15217 (if (re-search-forward org-property-start-re end t)
15218 (setq beg (1+ (match-end 0)))
15219 (if force
15220 (save-excursion
15221 (org-insert-property-drawer)
15222 (setq end (progn (outline-next-heading) (point))))
15223 (throw 'exit nil))
15224 (goto-char beg)
15225 (if (re-search-forward org-property-start-re end t)
15226 (setq beg (1+ (match-end 0)))))
15227 (if (re-search-forward org-property-end-re end t)
15228 (setq end (match-beginning 0))
15229 (or force (throw 'exit nil))
15230 (goto-char beg)
15231 (setq end beg)
15232 (org-indent-line)
15233 (insert ":END:\n"))
15234 (cons beg end)))))
15236 (defun org-entry-properties (&optional pom which specific)
15237 "Get all properties of the entry at point-or-marker POM.
15238 This includes the TODO keyword, the tags, time strings for deadline,
15239 scheduled, and clocking, and any additional properties defined in the
15240 entry. The return value is an alist, keys may occur multiple times
15241 if the property key was used several times.
15242 POM may also be nil, in which case the current entry is used.
15243 If WHICH is nil or `all', get all properties. If WHICH is
15244 `special' or `standard', only get that subclass. If WHICH
15245 is a string only get exactly this property. SPECIFIC can be a string, the
15246 specific property we are interested in. Specifying it can speed
15247 things up because then unnecessary parsing is avoided."
15248 (setq which (or which 'all))
15249 (org-with-wide-buffer
15250 (org-with-point-at pom
15251 (let ((clockstr (substring org-clock-string 0 -1))
15252 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15253 (case-fold-search nil)
15254 beg end range props sum-props key key1 value string clocksum clocksumt)
15255 (when (and (derived-mode-p 'org-mode)
15256 (ignore-errors (org-back-to-heading t)))
15257 (setq beg (point))
15258 (setq sum-props (get-text-property (point) 'org-summaries))
15259 (setq clocksum (get-text-property (point) :org-clock-minutes)
15260 clocksumt (get-text-property (point) :org-clock-minutes-today))
15261 (outline-next-heading)
15262 (setq end (point))
15263 (when (memq which '(all special))
15264 ;; Get the special properties, like TODO and tags
15265 (goto-char beg)
15266 (when (and (or (not specific) (string= specific "TODO"))
15267 (looking-at org-todo-line-regexp) (match-end 2))
15268 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15269 (when (and (or (not specific) (string= specific "PRIORITY"))
15270 (looking-at org-priority-regexp))
15271 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15272 (when (or (not specific) (string= specific "FILE"))
15273 (push (cons "FILE" buffer-file-name) props))
15274 (when (and (or (not specific) (string= specific "TAGS"))
15275 (setq value (org-get-tags-string))
15276 (string-match "\\S-" value))
15277 (push (cons "TAGS" value) props))
15278 (when (and (or (not specific) (string= specific "ALLTAGS"))
15279 (setq value (org-get-tags-at)))
15280 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15281 ":"))
15282 props))
15283 (when (or (not specific) (string= specific "BLOCKED"))
15284 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15285 (when (or (not specific)
15286 (member specific
15287 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15288 "TIMESTAMP" "TIMESTAMP_IA")))
15289 (catch 'match
15290 (while (and (re-search-forward org-maybe-keyword-time-regexp end t)
15291 (not (text-property-any 0 (length (match-string 0))
15292 'face 'font-lock-comment-face
15293 (match-string 0))))
15294 (setq key (if (match-end 1)
15295 (substring (org-match-string-no-properties 1)
15296 0 -1))
15297 string (if (equal key clockstr)
15298 (org-trim
15299 (buffer-substring-no-properties
15300 (match-beginning 3) (goto-char
15301 (point-at-eol))))
15302 (substring (org-match-string-no-properties 3)
15303 1 -1)))
15304 ;; Get the correct property name from the key. This is
15305 ;; necessary if the user has configured time keywords.
15306 (setq key1 (concat key ":"))
15307 (cond
15308 ((not key)
15309 (setq key
15310 (if (= (char-after (match-beginning 3)) ?\[)
15311 "TIMESTAMP_IA" "TIMESTAMP")))
15312 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15313 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15314 ((equal key1 org-closed-string) (setq key "CLOSED"))
15315 ((equal key1 org-clock-string) (setq key "CLOCK")))
15316 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15317 (progn
15318 (push (cons key string) props)
15319 ;; no need to search further if match is found
15320 (throw 'match t))
15321 (when (or (equal key "CLOCK") (not (assoc key props)))
15322 (push (cons key string) props)))))))
15324 (when (memq which '(all standard))
15325 ;; Get the standard properties, like :PROP: ...
15326 (setq range (org-get-property-block beg end))
15327 (when range
15328 (goto-char (car range))
15329 (while (re-search-forward org-property-re
15330 (cdr range) t)
15331 (setq key (org-match-string-no-properties 2)
15332 value (org-trim (or (org-match-string-no-properties 3) "")))
15333 (unless (member key excluded)
15334 (push (cons key (or value "")) props)))))
15335 (if clocksum
15336 (push (cons "CLOCKSUM"
15337 (org-columns-number-to-string (/ (float clocksum) 60.)
15338 'add_times))
15339 props))
15340 (if clocksumt
15341 (push (cons "CLOCKSUM_T"
15342 (org-columns-number-to-string (/ (float clocksumt) 60.)
15343 'add_times))
15344 props))
15345 (unless (assoc "CATEGORY" props)
15346 (push (cons "CATEGORY" (org-get-category)) props))
15347 (append sum-props (nreverse props)))))))
15349 (defun org-entry-get (pom property &optional inherit literal-nil)
15350 "Get value of PROPERTY for entry or content at point-or-marker POM.
15351 If INHERIT is non-nil and the entry does not have the property,
15352 then also check higher levels of the hierarchy.
15353 If INHERIT is the symbol `selective', use inheritance only if the setting
15354 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15355 If the property is present but empty, the return value is the empty string.
15356 If the property is not present at all, nil is returned.
15358 Return the value as a string.
15360 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15361 do not interpret it as the list atom nil. This is used for inheritance
15362 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15363 (org-with-point-at pom
15364 (if (and inherit (if (eq inherit 'selective)
15365 (org-property-inherit-p property)
15367 (org-entry-get-with-inheritance property literal-nil)
15368 (if (member property org-special-properties)
15369 ;; We need a special property. Use `org-entry-properties'
15370 ;; to retrieve it, but specify the wanted property
15371 (cdr (assoc property (org-entry-properties nil 'special property)))
15372 (org-with-wide-buffer
15373 (let ((range (org-get-property-block)))
15374 (when (and range (not (eq (car range) (cdr range)))
15375 (save-excursion
15376 (goto-char (car range))
15377 (re-search-forward
15378 (concat (org-re-property property) "\\|"
15379 (org-re-property (concat property "+")))
15380 (cdr range) t)))
15381 (let* ((props
15382 (list (or (assoc property org-file-properties)
15383 (assoc property org-global-properties)
15384 (assoc property org-global-properties-fixed))))
15385 (ap (lambda (key)
15386 (when (re-search-forward
15387 (org-re-property key) (cdr range) t)
15388 (setq props
15389 (org-update-property-plist
15391 (if (match-end 3)
15392 (org-match-string-no-properties 3) "")
15393 props)))))
15394 val)
15395 (goto-char (car range))
15396 (funcall ap property)
15397 (goto-char (car range))
15398 (while (funcall ap (concat property "+")))
15399 (setq val (cdr (assoc property props)))
15400 (when val (if literal-nil val (org-not-nil val)))))))))))
15402 (defun org-property-or-variable-value (var &optional inherit)
15403 "Check if there is a property fixing the value of VAR.
15404 If yes, return this value. If not, return the current value of the variable."
15405 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15406 (if (and prop (stringp prop) (string-match "\\S-" prop))
15407 (read prop)
15408 (symbol-value var))))
15410 (defun org-entry-delete (pom property &optional delete-empty-drawer)
15411 "Delete the property PROPERTY from entry at point-or-marker POM.
15412 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15413 an empty drawer to delete."
15414 (org-with-point-at pom
15415 (if (member property org-special-properties)
15416 nil ; cannot delete these properties.
15417 (let ((range (org-get-property-block)))
15418 (if (and range
15419 (goto-char (car range))
15420 (re-search-forward
15421 (org-re-property property nil t)
15422 (cdr range) t))
15423 (progn
15424 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15425 (and delete-empty-drawer
15426 (org-remove-empty-drawer-at
15427 delete-empty-drawer (car range)))
15429 nil)))))
15431 ;; Multi-values properties are properties that contain multiple values
15432 ;; These values are assumed to be single words, separated by whitespace.
15433 (defun org-entry-add-to-multivalued-property (pom property value)
15434 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15435 (let* ((old (org-entry-get pom property))
15436 (values (and old (org-split-string old "[ \t]"))))
15437 (setq value (org-entry-protect-space value))
15438 (unless (member value values)
15439 (setq values (append values (list value)))
15440 (org-entry-put pom property
15441 (mapconcat 'identity values " ")))))
15443 (defun org-entry-remove-from-multivalued-property (pom property value)
15444 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15445 (let* ((old (org-entry-get pom property))
15446 (values (and old (org-split-string old "[ \t]"))))
15447 (setq value (org-entry-protect-space value))
15448 (when (member value values)
15449 (setq values (delete value values))
15450 (org-entry-put pom property
15451 (mapconcat 'identity values " ")))))
15453 (defun org-entry-member-in-multivalued-property (pom property value)
15454 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15455 (let* ((old (org-entry-get pom property))
15456 (values (and old (org-split-string old "[ \t]"))))
15457 (setq value (org-entry-protect-space value))
15458 (member value values)))
15460 (defun org-entry-get-multivalued-property (pom property)
15461 "Return a list of values in a multivalued property."
15462 (let* ((value (org-entry-get pom property))
15463 (values (and value (org-split-string value "[ \t]"))))
15464 (mapcar 'org-entry-restore-space values)))
15466 (defun org-entry-put-multivalued-property (pom property &rest values)
15467 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15468 VALUES should be a list of strings. Spaces will be protected."
15469 (org-entry-put pom property
15470 (mapconcat 'org-entry-protect-space values " "))
15471 (let* ((value (org-entry-get pom property))
15472 (values (and value (org-split-string value "[ \t]"))))
15473 (mapcar 'org-entry-restore-space values)))
15475 (defun org-entry-protect-space (s)
15476 "Protect spaces and newline in string S."
15477 (while (string-match " " s)
15478 (setq s (replace-match "%20" t t s)))
15479 (while (string-match "\n" s)
15480 (setq s (replace-match "%0A" t t s)))
15483 (defun org-entry-restore-space (s)
15484 "Restore spaces and newline in string S."
15485 (while (string-match "%20" s)
15486 (setq s (replace-match " " t t s)))
15487 (while (string-match "%0A" s)
15488 (setq s (replace-match "\n" t t s)))
15491 (defvar org-entry-property-inherited-from (make-marker)
15492 "Marker pointing to the entry from where a property was inherited.
15493 Each call to `org-entry-get-with-inheritance' will set this marker to the
15494 location of the entry where the inheritance search matched. If there was
15495 no match, the marker will point nowhere.
15496 Note that also `org-entry-get' calls this function, if the INHERIT flag
15497 is set.")
15499 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15500 "Get PROPERTY of entry or content at point, search higher levels if needed.
15501 The search will stop at the first ancestor which has the property defined.
15502 If the value found is \"nil\", return nil to show that the property
15503 should be considered as undefined (this is the meaning of nil here).
15504 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15505 (move-marker org-entry-property-inherited-from nil)
15506 (let (tmp)
15507 (save-excursion
15508 (save-restriction
15509 (widen)
15510 (catch 'ex
15511 (while t
15512 (when (setq tmp (org-entry-get nil property nil literal-nil))
15513 (or (ignore-errors (org-back-to-heading t))
15514 (goto-char (point-min)))
15515 (move-marker org-entry-property-inherited-from (point))
15516 (throw 'ex tmp))
15517 (or (ignore-errors (org-up-heading-safe))
15518 (throw 'ex nil))))))
15519 (setq tmp (or tmp
15520 (cdr (assoc property org-file-properties))
15521 (cdr (assoc property org-global-properties))
15522 (cdr (assoc property org-global-properties-fixed))))
15523 (if literal-nil tmp (org-not-nil tmp))))
15525 (defvar org-property-changed-functions nil
15526 "Hook called when the value of a property has changed.
15527 Each hook function should accept two arguments, the name of the property
15528 and the new value.")
15530 (defun org-entry-put (pom property value)
15531 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15532 If the value is `nil', it is converted to the empty string.
15533 If it is not a string, an error is raised."
15534 (cond ((null value) (setq value ""))
15535 ((not (stringp value))
15536 (error "Properties values should be strings.")))
15537 (org-with-point-at pom
15538 (org-back-to-heading t)
15539 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15540 range)
15541 (cond
15542 ((equal property "TODO")
15543 (when (and (string-match "\\S-" value)
15544 (not (member value org-todo-keywords-1)))
15545 (user-error "\"%s\" is not a valid TODO state" value))
15546 (if (or (not value)
15547 (not (string-match "\\S-" value)))
15548 (setq value 'none))
15549 (org-todo value)
15550 (org-set-tags nil 'align))
15551 ((equal property "PRIORITY")
15552 (org-priority (if (and value (string-match "\\S-" value))
15553 (string-to-char value) ?\ ))
15554 (org-set-tags nil 'align))
15555 ((equal property "CLOCKSUM")
15556 (if (not (re-search-forward
15557 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15558 (error "Cannot find a clock log")
15559 (goto-char (- (match-end 1) 2))
15560 (cond
15561 ((eq value 'earlier) (org-timestamp-down))
15562 ((eq value 'later) (org-timestamp-up)))
15563 (org-clock-sum-current-item)))
15564 ((equal property "SCHEDULED")
15565 (if (re-search-forward org-scheduled-time-regexp end t)
15566 (cond
15567 ((eq value 'earlier) (org-timestamp-change -1 'day))
15568 ((eq value 'later) (org-timestamp-change 1 'day))
15569 (t (call-interactively 'org-schedule)))
15570 (call-interactively 'org-schedule)))
15571 ((equal property "DEADLINE")
15572 (if (re-search-forward org-deadline-time-regexp end t)
15573 (cond
15574 ((eq value 'earlier) (org-timestamp-change -1 'day))
15575 ((eq value 'later) (org-timestamp-change 1 'day))
15576 (t (call-interactively 'org-deadline)))
15577 (call-interactively 'org-deadline)))
15578 ((member property org-special-properties)
15579 (error "The %s property can not yet be set with `org-entry-put'"
15580 property))
15581 (t ; a non-special property
15582 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15583 (setq range (org-get-property-block beg end 'force))
15584 (goto-char (car range))
15585 (if (re-search-forward
15586 (org-re-property property nil t) (cdr range) t)
15587 (progn
15588 (delete-region (match-beginning 0) (match-end 0))
15589 (goto-char (match-beginning 0)))
15590 (goto-char (cdr range))
15591 (insert "\n")
15592 (backward-char 1)
15593 (org-indent-line))
15594 (insert ":" property ":")
15595 (and value (insert " " value))
15596 (org-indent-line)))))
15597 (run-hook-with-args 'org-property-changed-functions property value)))
15599 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15600 "Get all property keys in the current buffer.
15601 With INCLUDE-SPECIALS, also list the special properties that reflect things
15602 like tags and TODO state.
15603 With INCLUDE-DEFAULTS, also include properties that has special meaning
15604 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15605 and others.
15606 With INCLUDE-COLUMNS, also include property names given in COLUMN
15607 formats in the current buffer."
15608 (let (rtn range cfmt s p)
15609 (save-excursion
15610 (save-restriction
15611 (widen)
15612 (goto-char (point-min))
15613 (while (re-search-forward org-property-start-re nil t)
15614 (setq range (org-get-property-block))
15615 (goto-char (car range))
15616 (while (re-search-forward org-property-re
15617 (cdr range) t)
15618 (add-to-list 'rtn (org-match-string-no-properties 2)))
15619 (outline-next-heading))))
15621 (when include-specials
15622 (setq rtn (append org-special-properties rtn)))
15624 (when include-defaults
15625 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15626 (add-to-list 'rtn org-effort-property))
15628 (when include-columns
15629 (save-excursion
15630 (save-restriction
15631 (widen)
15632 (goto-char (point-min))
15633 (while (re-search-forward
15634 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15635 nil t)
15636 (setq cfmt (match-string 2) s 0)
15637 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15638 cfmt s)
15639 (setq s (match-end 0)
15640 p (match-string 1 cfmt))
15641 (unless (or (equal p "ITEM")
15642 (member p org-special-properties))
15643 (add-to-list 'rtn (match-string 1 cfmt))))))))
15645 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15647 (defun org-property-values (key)
15648 "Return a list of all values of property KEY in the current buffer."
15649 (save-excursion
15650 (save-restriction
15651 (widen)
15652 (goto-char (point-min))
15653 (let ((re (org-re-property key))
15654 values)
15655 (while (re-search-forward re nil t)
15656 (add-to-list 'values (org-trim (match-string 3))))
15657 (delete "" values)))))
15659 (defun org-insert-property-drawer ()
15660 "Insert a property drawer into the current entry."
15661 (org-back-to-heading t)
15662 (looking-at org-outline-regexp)
15663 (let ((indent (if org-adapt-indentation
15664 (- (match-end 0) (match-beginning 0))
15666 (beg (point))
15667 (re (concat "^[ \t]*" org-keyword-time-regexp))
15668 end hiddenp)
15669 (outline-next-heading)
15670 (setq end (point))
15671 (goto-char beg)
15672 (while (re-search-forward re end t))
15673 (setq hiddenp (outline-invisible-p))
15674 (end-of-line 1)
15675 (and (equal (char-after) ?\n) (forward-char 1))
15676 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15677 (if (member (match-string 1) '("CLOCK:" ":END:"))
15678 ;; just skip this line
15679 (beginning-of-line 2)
15680 ;; Drawer start, find the end
15681 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15682 (beginning-of-line 1)))
15683 (org-skip-over-state-notes)
15684 (skip-chars-backward " \t\n\r")
15685 (if (and (eq (char-before) ?*) (not (eq (char-after) ?\n)))
15686 (forward-char 1))
15687 (goto-char (point-at-eol))
15688 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15689 (beginning-of-line 0)
15690 (org-indent-to-column indent)
15691 (beginning-of-line 2)
15692 (org-indent-to-column indent)
15693 (beginning-of-line 0)
15694 (if hiddenp
15695 (save-excursion
15696 (org-back-to-heading t)
15697 (hide-entry))
15698 (org-flag-drawer t))))
15700 (defun org-insert-drawer (&optional arg drawer)
15701 "Insert a drawer at point.
15703 Optional argument DRAWER, when non-nil, is a string representing
15704 drawer's name. Otherwise, the user is prompted for a name.
15706 If a region is active, insert the drawer around that region
15707 instead.
15709 Point is left between drawer's boundaries."
15710 (interactive "P")
15711 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15712 "LOGBOOK"))
15713 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15714 ;; internally by Org. They are meant to be inserted
15715 ;; automatically.
15716 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15717 ;; Remove system drawers from list. Note: For some reason,
15718 ;; `org-completing-read' ignores the predicate while
15719 ;; `completing-read' handles it fine.
15720 (drawer (if arg "PROPERTIES"
15721 (or drawer
15722 (completing-read
15723 "Drawer: " org-drawers
15724 (lambda (d) (not (member d system-drawers))))))))
15725 (cond
15726 ;; With C-u, fall back on `org-insert-property-drawer'
15727 (arg (org-insert-property-drawer))
15728 ;; With an active region, insert a drawer at point.
15729 ((not (org-region-active-p))
15730 (progn
15731 (unless (bolp) (insert "\n"))
15732 (insert (format ":%s:\n\n:END:\n" drawer))
15733 (forward-line -2)))
15734 ;; Otherwise, insert the drawer at point
15736 (let ((rbeg (region-beginning))
15737 (rend (copy-marker (region-end))))
15738 (unwind-protect
15739 (progn
15740 (goto-char rbeg)
15741 (beginning-of-line)
15742 (when (save-excursion
15743 (re-search-forward org-outline-regexp-bol rend t))
15744 (user-error "Drawers cannot contain headlines"))
15745 ;; Position point at the beginning of the first
15746 ;; non-blank line in region. Insert drawer's opening
15747 ;; there, then indent it.
15748 (org-skip-whitespace)
15749 (beginning-of-line)
15750 (insert ":" drawer ":\n")
15751 (forward-line -1)
15752 (indent-for-tab-command)
15753 ;; Move point to the beginning of the first blank line
15754 ;; after the last non-blank line in region. Insert
15755 ;; drawer's closing, then indent it.
15756 (goto-char rend)
15757 (skip-chars-backward " \r\t\n")
15758 (insert "\n:END:")
15759 (deactivate-mark t)
15760 (indent-for-tab-command)
15761 (unless (eolp) (insert "\n")))
15762 ;; Clear marker, whatever the outcome of insertion is.
15763 (set-marker rend nil)))))))
15765 (defvar org-property-set-functions-alist nil
15766 "Property set function alist.
15767 Each entry should have the following format:
15769 (PROPERTY . READ-FUNCTION)
15771 The read function will be called with the same argument as
15772 `org-completing-read'.")
15774 (defun org-set-property-function (property)
15775 "Get the function that should be used to set PROPERTY.
15776 This is computed according to `org-property-set-functions-alist'."
15777 (or (cdr (assoc property org-property-set-functions-alist))
15778 'org-completing-read))
15780 (defun org-read-property-value (property)
15781 "Read PROPERTY value from user."
15782 (let* ((completion-ignore-case t)
15783 (allowed (org-property-get-allowed-values nil property 'table))
15784 (cur (org-entry-get nil property))
15785 (prompt (concat property " value"
15786 (if (and cur (string-match "\\S-" cur))
15787 (concat " [" cur "]") "") ": "))
15788 (set-function (org-set-property-function property))
15789 (val (if allowed
15790 (funcall set-function prompt allowed nil
15791 (not (get-text-property 0 'org-unrestricted
15792 (caar allowed))))
15793 (let (org-completion-use-ido org-completion-use-iswitchb)
15794 (funcall set-function prompt
15795 (mapcar 'list (org-property-values property))
15796 nil nil "" nil cur)))))
15797 (org-trim val)))
15799 (defvar org-last-set-property nil)
15800 (defvar org-last-set-property-value nil)
15801 (defun org-read-property-name ()
15802 "Read a property name."
15803 (let* ((completion-ignore-case t)
15804 (keys (org-buffer-property-keys nil t t))
15805 (default-prop (or (save-excursion
15806 (save-match-data
15807 (beginning-of-line)
15808 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15809 (null (string= (match-string 1) "END"))
15810 (match-string 1))))
15811 org-last-set-property))
15812 (property (org-icompleting-read
15813 (concat "Property"
15814 (if default-prop (concat " [" default-prop "]") "")
15815 ": ")
15816 (mapcar 'list keys)
15817 nil nil nil nil
15818 default-prop)))
15819 (if (member property keys)
15820 property
15821 (or (cdr (assoc (downcase property)
15822 (mapcar (lambda (x) (cons (downcase x) x))
15823 keys)))
15824 property))))
15826 (defun org-set-property-and-value (use-last)
15827 "Allow to set [PROPERTY]: [value] direction from prompt.
15828 When use-default, don't even ask, just use the last
15829 \"[PROPERTY]: [value]\" string from the history."
15830 (interactive "P")
15831 (let* ((completion-ignore-case t)
15832 (pv (or (and use-last org-last-set-property-value)
15833 (org-completing-read
15834 "Enter a \"[Property]: [value]\" pair: "
15835 nil nil nil nil nil
15836 org-last-set-property-value)))
15837 prop val)
15838 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15839 (setq prop (match-string 1 pv)
15840 val (match-string 2 pv))
15841 (org-set-property prop val))))
15843 (defun org-set-property (property value)
15844 "In the current entry, set PROPERTY to VALUE.
15845 When called interactively, this will prompt for a property name, offering
15846 completion on existing and default properties. And then it will prompt
15847 for a value, offering completion either on allowed values (via an inherited
15848 xxx_ALL property) or on existing values in other instances of this property
15849 in the current file."
15850 (interactive (list nil nil))
15851 (let* ((property (or property (org-read-property-name)))
15852 (value (or value (org-read-property-value property)))
15853 (fn (cdr (assoc property org-properties-postprocess-alist))))
15854 (setq org-last-set-property property)
15855 (setq org-last-set-property-value (concat property ": " value))
15856 ;; Possibly postprocess the inserted value:
15857 (when fn (setq value (funcall fn value)))
15858 (unless (equal (org-entry-get nil property) value)
15859 (org-entry-put nil property value))))
15861 (defun org-delete-property (property &optional delete-empty-drawer)
15862 "In the current entry, delete PROPERTY.
15863 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15864 an empty drawer to delete."
15865 (interactive
15866 (let* ((completion-ignore-case t)
15867 (cat (org-entry-get (point) "CATEGORY"))
15868 (props0 (org-entry-properties nil 'standard))
15869 (props (if cat props0
15870 (delete `("CATEGORY" . ,(org-get-category)) props0)))
15871 (prop (if (< 1 (length props))
15872 (org-icompleting-read "Property: " props nil t)
15873 (caar props))))
15874 (list prop)))
15875 (if (not property)
15876 (message "No property to delete in this entry")
15877 (org-entry-delete nil property delete-empty-drawer)
15878 (message "Property \"%s\" deleted" property)))
15880 (defun org-delete-property-globally (property)
15881 "Remove PROPERTY globally, from all entries."
15882 (interactive
15883 (let* ((completion-ignore-case t)
15884 (prop (org-icompleting-read
15885 "Globally remove property: "
15886 (mapcar 'list (org-buffer-property-keys)))))
15887 (list prop)))
15888 (save-excursion
15889 (save-restriction
15890 (widen)
15891 (goto-char (point-min))
15892 (let ((cnt 0))
15893 (while (re-search-forward
15894 (org-re-property property)
15895 nil t)
15896 (setq cnt (1+ cnt))
15897 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15898 (message "Property \"%s\" removed from %d entries" property cnt)))))
15900 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15902 (defun org-compute-property-at-point ()
15903 "Compute the property at point.
15904 This looks for an enclosing column format, extracts the operator and
15905 then applies it to the property in the column format's scope."
15906 (interactive)
15907 (unless (org-at-property-p)
15908 (user-error "Not at a property"))
15909 (let ((prop (org-match-string-no-properties 2)))
15910 (org-columns-get-format-and-top-level)
15911 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15912 (user-error "No operator defined for property %s" prop))
15913 (org-columns-compute prop)))
15915 (defvar org-property-allowed-value-functions nil
15916 "Hook for functions supplying allowed values for a specific property.
15917 The functions must take a single argument, the name of the property, and
15918 return a flat list of allowed values. If \":ETC\" is one of
15919 the values, this means that these values are intended as defaults for
15920 completion, but that other values should be allowed too.
15921 The functions must return nil if they are not responsible for this
15922 property.")
15924 (defun org-property-get-allowed-values (pom property &optional table)
15925 "Get allowed values for the property PROPERTY.
15926 When TABLE is non-nil, return an alist that can directly be used for
15927 completion."
15928 (let (vals)
15929 (cond
15930 ((equal property "TODO")
15931 (setq vals (org-with-point-at pom
15932 (append org-todo-keywords-1 '("")))))
15933 ((equal property "PRIORITY")
15934 (let ((n org-lowest-priority))
15935 (while (>= n org-highest-priority)
15936 (push (char-to-string n) vals)
15937 (setq n (1- n)))))
15938 ((member property org-special-properties))
15939 ((setq vals (run-hook-with-args-until-success
15940 'org-property-allowed-value-functions property)))
15942 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15943 (when (and vals (string-match "\\S-" vals))
15944 (setq vals (car (read-from-string (concat "(" vals ")"))))
15945 (setq vals (mapcar (lambda (x)
15946 (cond ((stringp x) x)
15947 ((numberp x) (number-to-string x))
15948 ((symbolp x) (symbol-name x))
15949 (t "???")))
15950 vals)))))
15951 (when (member ":ETC" vals)
15952 (setq vals (remove ":ETC" vals))
15953 (org-add-props (car vals) '(org-unrestricted t)))
15954 (if table (mapcar 'list vals) vals)))
15956 (defun org-property-previous-allowed-value (&optional previous)
15957 "Switch to the next allowed value for this property."
15958 (interactive)
15959 (org-property-next-allowed-value t))
15961 (defun org-property-next-allowed-value (&optional previous)
15962 "Switch to the next allowed value for this property."
15963 (interactive)
15964 (unless (org-at-property-p)
15965 (user-error "Not at a property"))
15966 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15967 (key (match-string 2))
15968 (value (match-string 3))
15969 (allowed (or (org-property-get-allowed-values (point) key)
15970 (and (member value '("[ ]" "[-]" "[X]"))
15971 '("[ ]" "[X]"))))
15972 (heading (save-match-data (nth 4 (org-heading-components))))
15973 nval)
15974 (unless allowed
15975 (user-error "Allowed values for this property have not been defined"))
15976 (if previous (setq allowed (reverse allowed)))
15977 (if (member value allowed)
15978 (setq nval (car (cdr (member value allowed)))))
15979 (setq nval (or nval (car allowed)))
15980 (if (equal nval value)
15981 (user-error "Only one allowed value for this property"))
15982 (org-at-property-p)
15983 (replace-match (concat " :" key ": " nval) t t)
15984 (org-indent-line)
15985 (beginning-of-line 1)
15986 (skip-chars-forward " \t")
15987 (when (equal prop org-effort-property)
15988 (save-excursion
15989 (org-back-to-heading t)
15990 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
15991 (when (string= org-clock-current-task heading)
15992 (setq org-clock-effort nval)
15993 (org-clock-update-mode-line)))
15994 (run-hook-with-args 'org-property-changed-functions key nval)))
15996 (defun org-find-olp (path &optional this-buffer)
15997 "Return a marker pointing to the entry at outline path OLP.
15998 If anything goes wrong, throw an error.
15999 You can wrap this call to catch the error like this:
16001 (condition-case msg
16002 (org-mobile-locate-entry (match-string 4))
16003 (error (nth 1 msg)))
16005 The return value will then be either a string with the error message,
16006 or a marker if everything is OK.
16008 If THIS-BUFFER is set, the outline path does not contain a file,
16009 only headings."
16010 (let* ((file (if this-buffer buffer-file-name (pop path)))
16011 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16012 (level 1)
16013 (lmin 1)
16014 (lmax 1)
16015 limit re end found pos heading cnt flevel)
16016 (unless buffer (error "File not found :%s" file))
16017 (with-current-buffer buffer
16018 (save-excursion
16019 (save-restriction
16020 (widen)
16021 (setq limit (point-max))
16022 (goto-char (point-min))
16023 (while (setq heading (pop path))
16024 (setq re (format org-complex-heading-regexp-format
16025 (regexp-quote heading)))
16026 (setq cnt 0 pos (point))
16027 (while (re-search-forward re end t)
16028 (setq level (- (match-end 1) (match-beginning 1)))
16029 (if (and (>= level lmin) (<= level lmax))
16030 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16031 (when (= cnt 0) (error "Heading not found on level %d: %s"
16032 lmax heading))
16033 (when (> cnt 1) (error "Heading not unique on level %d: %s"
16034 lmax heading))
16035 (goto-char found)
16036 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16037 (setq end (save-excursion (org-end-of-subtree t t))))
16038 (when (org-at-heading-p)
16039 (point-marker)))))))
16041 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16042 "Find node HEADING in BUFFER.
16043 Return a marker to the heading if it was found, or nil if not.
16044 If POS-ONLY is set, return just the position instead of a marker.
16046 The heading text must match exact, but it may have a TODO keyword,
16047 a priority cookie and tags in the standard locations."
16048 (with-current-buffer (or buffer (current-buffer))
16049 (save-excursion
16050 (save-restriction
16051 (widen)
16052 (goto-char (point-min))
16053 (let (case-fold-search)
16054 (if (re-search-forward
16055 (format org-complex-heading-regexp-format
16056 (regexp-quote heading)) nil t)
16057 (if pos-only
16058 (match-beginning 0)
16059 (move-marker (make-marker) (match-beginning 0)))))))))
16061 (defun org-find-exact-heading-in-directory (heading &optional dir)
16062 "Find Org node headline HEADING in all .org files in directory DIR.
16063 When the target headline is found, return a marker to this location."
16064 (let ((files (directory-files (or dir default-directory)
16065 nil "\\`[^.#].*\\.org\\'"))
16066 file visiting m buffer)
16067 (catch 'found
16068 (while (setq file (pop files))
16069 (message "trying %s" file)
16070 (setq visiting (org-find-base-buffer-visiting file))
16071 (setq buffer (or visiting (find-file-noselect file)))
16072 (setq m (org-find-exact-headline-in-buffer
16073 heading buffer))
16074 (when (and (not m) (not visiting)) (kill-buffer buffer))
16075 (and m (throw 'found m))))))
16077 (defun org-find-entry-with-id (ident)
16078 "Locate the entry that contains the ID property with exact value IDENT.
16079 IDENT can be a string, a symbol or a number, this function will search for
16080 the string representation of it.
16081 Return the position where this entry starts, or nil if there is no such entry."
16082 (interactive "sID: ")
16083 (let ((id (cond
16084 ((stringp ident) ident)
16085 ((symbol-name ident) (symbol-name ident))
16086 ((numberp ident) (number-to-string ident))
16087 (t (error "IDENT %s must be a string, symbol or number" ident))))
16088 (case-fold-search nil))
16089 (save-excursion
16090 (save-restriction
16091 (widen)
16092 (goto-char (point-min))
16093 (when (re-search-forward
16094 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16095 nil t)
16096 (org-back-to-heading t)
16097 (point))))))
16099 ;;;; Timestamps
16101 (defvar org-last-changed-timestamp nil)
16102 (defvar org-last-inserted-timestamp nil
16103 "The last time stamp inserted with `org-insert-time-stamp'.")
16104 (defvar org-ts-what) ; dynamically scoped parameter
16106 (defun org-time-stamp (arg &optional inactive)
16107 "Prompt for a date/time and insert a time stamp.
16108 If the user specifies a time like HH:MM or if this command is
16109 called with at least one prefix argument, the time stamp contains
16110 the date and the time. Otherwise, only the date is be included.
16112 All parts of a date not specified by the user is filled in from
16113 the current date/time. So if you just press return without
16114 typing anything, the time stamp will represent the current
16115 date/time.
16117 If there is already a timestamp at the cursor, it will be
16118 modified.
16120 With two universal prefix arguments, insert an active timestamp
16121 with the current time without prompting the user.
16123 When called from lisp, the timestamp is inactive if INACTIVE is
16124 non-nil."
16125 (interactive "P")
16126 (let* ((ts nil)
16127 (default-time
16128 ;; Default time is either today, or, when entering a range,
16129 ;; the range start.
16130 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16131 (save-excursion
16132 (re-search-backward
16133 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16134 (- (point) 20) t)))
16135 (apply 'encode-time (org-parse-time-string (match-string 1)))
16136 (current-time)))
16137 (default-input (and ts (org-get-compact-tod ts)))
16138 (repeater (save-excursion
16139 (save-match-data
16140 (beginning-of-line)
16141 (when (re-search-forward
16142 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16143 (save-excursion (progn (end-of-line) (point))) t)
16144 (match-string 0)))))
16145 org-time-was-given org-end-time-was-given time)
16146 (cond
16147 ((and (org-at-timestamp-p t)
16148 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16149 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16150 (insert "--")
16151 (setq time (let ((this-command this-command))
16152 (org-read-date arg 'totime nil nil
16153 default-time default-input inactive)))
16154 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16155 ((org-at-timestamp-p t)
16156 (setq time (let ((this-command this-command))
16157 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16158 (when (org-at-timestamp-p t) ; just to get the match data
16159 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16160 (replace-match "")
16161 (setq org-last-changed-timestamp
16162 (org-insert-time-stamp
16163 time (or org-time-was-given arg)
16164 inactive nil nil (list org-end-time-was-given)))
16165 (when repeater (goto-char (1- (point))) (insert " " repeater)
16166 (setq org-last-changed-timestamp
16167 (concat (substring org-last-inserted-timestamp 0 -1)
16168 " " repeater ">"))))
16169 (message "Timestamp updated"))
16170 ((equal arg '(16))
16171 (org-insert-time-stamp (current-time) t inactive))
16173 (setq time (let ((this-command this-command))
16174 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16175 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16176 nil nil (list org-end-time-was-given))))))
16178 ;; FIXME: can we use this for something else, like computing time differences?
16179 (defun org-get-compact-tod (s)
16180 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16181 (let* ((t1 (match-string 1 s))
16182 (h1 (string-to-number (match-string 2 s)))
16183 (m1 (string-to-number (match-string 3 s)))
16184 (t2 (and (match-end 4) (match-string 5 s)))
16185 (h2 (and t2 (string-to-number (match-string 6 s))))
16186 (m2 (and t2 (string-to-number (match-string 7 s))))
16187 dh dm)
16188 (if (not t2)
16190 (setq dh (- h2 h1) dm (- m2 m1))
16191 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16192 (concat t1 "+" (number-to-string dh)
16193 (and (/= 0 dm) (format ":%02d" dm)))))))
16195 (defun org-time-stamp-inactive (&optional arg)
16196 "Insert an inactive time stamp.
16197 An inactive time stamp is enclosed in square brackets instead of angle
16198 brackets. It is inactive in the sense that it does not trigger agenda entries,
16199 does not link to the calendar and cannot be changed with the S-cursor keys.
16200 So these are more for recording a certain time/date."
16201 (interactive "P")
16202 (org-time-stamp arg 'inactive))
16204 (defvar org-date-ovl (make-overlay 1 1))
16205 (overlay-put org-date-ovl 'face 'org-date-selected)
16206 (org-detach-overlay org-date-ovl)
16208 (defvar org-ans1) ; dynamically scoped parameter
16209 (defvar org-ans2) ; dynamically scoped parameter
16211 (defvar org-plain-time-of-day-regexp) ; defined below
16213 (defvar org-overriding-default-time nil) ; dynamically scoped
16214 (defvar org-read-date-overlay nil)
16215 (defvar org-dcst nil) ; dynamically scoped
16216 (defvar org-read-date-history nil)
16217 (defvar org-read-date-final-answer nil)
16218 (defvar org-read-date-analyze-futurep nil)
16219 (defvar org-read-date-analyze-forced-year nil)
16220 (defvar org-read-date-inactive)
16222 (defvar org-read-date-minibuffer-local-map
16223 (let* ((org-replace-disputed-keys nil)
16224 (map (make-sparse-keymap)))
16225 (set-keymap-parent map minibuffer-local-map)
16226 (org-defkey map (kbd ".")
16227 (lambda () (interactive)
16228 ;; Are we at the beginning of the prompt?
16229 (if (looking-back "^[^:]+: ")
16230 (org-eval-in-calendar '(calendar-goto-today))
16231 (insert "."))))
16232 (org-defkey map (kbd "C-.")
16233 (lambda () (interactive)
16234 (org-eval-in-calendar '(calendar-goto-today))))
16235 (org-defkey map [(meta shift left)]
16236 (lambda () (interactive)
16237 (org-eval-in-calendar '(calendar-backward-month 1))))
16238 (org-defkey map [(meta shift right)]
16239 (lambda () (interactive)
16240 (org-eval-in-calendar '(calendar-forward-month 1))))
16241 (org-defkey map [(meta shift up)]
16242 (lambda () (interactive)
16243 (org-eval-in-calendar '(calendar-backward-year 1))))
16244 (org-defkey map [(meta shift down)]
16245 (lambda () (interactive)
16246 (org-eval-in-calendar '(calendar-forward-year 1))))
16247 (org-defkey map [?\e (shift left)]
16248 (lambda () (interactive)
16249 (org-eval-in-calendar '(calendar-backward-month 1))))
16250 (org-defkey map [?\e (shift right)]
16251 (lambda () (interactive)
16252 (org-eval-in-calendar '(calendar-forward-month 1))))
16253 (org-defkey map [?\e (shift up)]
16254 (lambda () (interactive)
16255 (org-eval-in-calendar '(calendar-backward-year 1))))
16256 (org-defkey map [?\e (shift down)]
16257 (lambda () (interactive)
16258 (org-eval-in-calendar '(calendar-forward-year 1))))
16259 (org-defkey map [(shift up)]
16260 (lambda () (interactive)
16261 (org-eval-in-calendar '(calendar-backward-week 1))))
16262 (org-defkey map [(shift down)]
16263 (lambda () (interactive)
16264 (org-eval-in-calendar '(calendar-forward-week 1))))
16265 (org-defkey map [(shift left)]
16266 (lambda () (interactive)
16267 (org-eval-in-calendar '(calendar-backward-day 1))))
16268 (org-defkey map [(shift right)]
16269 (lambda () (interactive)
16270 (org-eval-in-calendar '(calendar-forward-day 1))))
16271 (org-defkey map "!"
16272 (lambda () (interactive)
16273 (org-eval-in-calendar '(diary-view-entries))
16274 (message "")))
16275 (org-defkey map ">"
16276 (lambda () (interactive)
16277 (org-eval-in-calendar '(scroll-calendar-left 1))))
16278 (org-defkey map "<"
16279 (lambda () (interactive)
16280 (org-eval-in-calendar '(scroll-calendar-right 1))))
16281 (org-defkey map "\C-v"
16282 (lambda () (interactive)
16283 (org-eval-in-calendar
16284 '(calendar-scroll-left-three-months 1))))
16285 (org-defkey map "\M-v"
16286 (lambda () (interactive)
16287 (org-eval-in-calendar
16288 '(calendar-scroll-right-three-months 1))))
16289 map)
16290 "Keymap for minibuffer commands when using `org-read-date'.")
16292 (defvar org-def)
16293 (defvar org-defdecode)
16294 (defvar org-with-time)
16296 (defun org-read-date (&optional org-with-time to-time from-string prompt
16297 default-time default-input inactive)
16298 "Read a date, possibly a time, and make things smooth for the user.
16299 The prompt will suggest to enter an ISO date, but you can also enter anything
16300 which will at least partially be understood by `parse-time-string'.
16301 Unrecognized parts of the date will default to the current day, month, year,
16302 hour and minute. If this command is called to replace a timestamp at point,
16303 or to enter the second timestamp of a range, the default time is taken
16304 from the existing stamp. Furthermore, the command prefers the future,
16305 so if you are giving a date where the year is not given, and the day-month
16306 combination is already past in the current year, it will assume you
16307 mean next year. For details, see the manual. A few examples:
16309 3-2-5 --> 2003-02-05
16310 feb 15 --> currentyear-02-15
16311 2/15 --> currentyear-02-15
16312 sep 12 9 --> 2009-09-12
16313 12:45 --> today 12:45
16314 22 sept 0:34 --> currentyear-09-22 0:34
16315 12 --> currentyear-currentmonth-12
16316 Fri --> nearest Friday after today
16317 -Tue --> last Tuesday
16318 etc.
16320 Furthermore you can specify a relative date by giving, as the *first* thing
16321 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16322 change in days weeks, months, years.
16323 With a single plus or minus, the date is relative to today. With a double
16324 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16325 +4d --> four days from today
16326 +4 --> same as above
16327 +2w --> two weeks from today
16328 ++5 --> five days from default date
16330 The function understands only English month and weekday abbreviations.
16332 While prompting, a calendar is popped up - you can also select the
16333 date with the mouse (button 1). The calendar shows a period of three
16334 months. To scroll it to other months, use the keys `>' and `<'.
16335 If you don't like the calendar, turn it off with
16336 \(setq org-read-date-popup-calendar nil)
16338 With optional argument TO-TIME, the date will immediately be converted
16339 to an internal time.
16340 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16341 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16342 still enter a time, and this function will inform the calling routine
16343 about this change. The calling routine may then choose to change the
16344 format used to insert the time stamp into the buffer to include the time.
16345 With optional argument FROM-STRING, read from this string instead from
16346 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16347 the time/date that is used for everything that is not specified by the
16348 user."
16349 (require 'parse-time)
16350 (let* ((org-time-stamp-rounding-minutes
16351 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16352 (org-dcst org-display-custom-times)
16353 (ct (org-current-time))
16354 (org-def (or org-overriding-default-time default-time ct))
16355 (org-defdecode (decode-time org-def))
16356 (dummy (progn
16357 (when (< (nth 2 org-defdecode) org-extend-today-until)
16358 (setcar (nthcdr 2 org-defdecode) -1)
16359 (setcar (nthcdr 1 org-defdecode) 59)
16360 (setq org-def (apply 'encode-time org-defdecode)
16361 org-defdecode (decode-time org-def)))))
16362 (mouse-autoselect-window nil) ; Don't let the mouse jump
16363 (calendar-frame-setup nil)
16364 (calendar-setup nil)
16365 (calendar-move-hook nil)
16366 (calendar-view-diary-initially-flag nil)
16367 (calendar-view-holidays-initially-flag nil)
16368 (timestr (format-time-string
16369 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16370 (prompt (concat (if prompt (concat prompt " ") "")
16371 (format "Date+time [%s]: " timestr)))
16372 ans (org-ans0 "") org-ans1 org-ans2 final)
16374 (cond
16375 (from-string (setq ans from-string))
16376 (org-read-date-popup-calendar
16377 (save-excursion
16378 (save-window-excursion
16379 (calendar)
16380 (org-eval-in-calendar '(setq cursor-type nil) t)
16381 (unwind-protect
16382 (progn
16383 (calendar-forward-day (- (time-to-days org-def)
16384 (calendar-absolute-from-gregorian
16385 (calendar-current-date))))
16386 (org-eval-in-calendar nil t)
16387 (let* ((old-map (current-local-map))
16388 (map (copy-keymap calendar-mode-map))
16389 (minibuffer-local-map
16390 (copy-keymap org-read-date-minibuffer-local-map)))
16391 (org-defkey map (kbd "RET") 'org-calendar-select)
16392 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16393 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16394 (unwind-protect
16395 (progn
16396 (use-local-map map)
16397 (setq org-read-date-inactive inactive)
16398 (add-hook 'post-command-hook 'org-read-date-display)
16399 (setq org-ans0 (read-string prompt default-input
16400 'org-read-date-history nil))
16401 ;; org-ans0: from prompt
16402 ;; org-ans1: from mouse click
16403 ;; org-ans2: from calendar motion
16404 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16405 (remove-hook 'post-command-hook 'org-read-date-display)
16406 (use-local-map old-map)
16407 (when org-read-date-overlay
16408 (delete-overlay org-read-date-overlay)
16409 (setq org-read-date-overlay nil)))))
16410 (bury-buffer "*Calendar*")))))
16412 (t ; Naked prompt only
16413 (unwind-protect
16414 (setq ans (read-string prompt default-input
16415 'org-read-date-history timestr))
16416 (when org-read-date-overlay
16417 (delete-overlay org-read-date-overlay)
16418 (setq org-read-date-overlay nil)))))
16420 (setq final (org-read-date-analyze ans org-def org-defdecode))
16422 (when org-read-date-analyze-forced-year
16423 (message "Year was forced into %s"
16424 (if org-read-date-force-compatible-dates
16425 "compatible range (1970-2037)"
16426 "range representable on this machine"))
16427 (ding))
16429 ;; One round trip to get rid of 34th of August and stuff like that....
16430 (setq final (decode-time (apply 'encode-time final)))
16432 (setq org-read-date-final-answer ans)
16434 (if to-time
16435 (apply 'encode-time final)
16436 (if (and (boundp 'org-time-was-given) org-time-was-given)
16437 (format "%04d-%02d-%02d %02d:%02d"
16438 (nth 5 final) (nth 4 final) (nth 3 final)
16439 (nth 2 final) (nth 1 final))
16440 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16442 (defun org-read-date-display ()
16443 "Display the current date prompt interpretation in the minibuffer."
16444 (when org-read-date-display-live
16445 (when org-read-date-overlay
16446 (delete-overlay org-read-date-overlay))
16447 (when (minibufferp (current-buffer))
16448 (save-excursion
16449 (end-of-line 1)
16450 (while (not (equal (buffer-substring
16451 (max (point-min) (- (point) 4)) (point))
16452 " "))
16453 (insert " ")))
16454 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16455 " " (or org-ans1 org-ans2)))
16456 (org-end-time-was-given nil)
16457 (f (org-read-date-analyze ans org-def org-defdecode))
16458 (fmts (if org-dcst
16459 org-time-stamp-custom-formats
16460 org-time-stamp-formats))
16461 (fmt (if (or org-with-time
16462 (and (boundp 'org-time-was-given) org-time-was-given))
16463 (cdr fmts)
16464 (car fmts)))
16465 (txt (format-time-string fmt (apply 'encode-time f)))
16466 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16467 (txt (concat "=> " txt)))
16468 (when (and org-end-time-was-given
16469 (string-match org-plain-time-of-day-regexp txt))
16470 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16471 org-end-time-was-given
16472 (substring txt (match-end 0)))))
16473 (when org-read-date-analyze-futurep
16474 (setq txt (concat txt " (=>F)")))
16475 (setq org-read-date-overlay
16476 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16477 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16479 (defun org-read-date-analyze (ans org-def org-defdecode)
16480 "Analyze the combined answer of the date prompt."
16481 ;; FIXME: cleanup and comment
16482 (let ((nowdecode (decode-time (current-time)))
16483 delta deltan deltaw deltadef year month day
16484 hour minute second wday pm h2 m2 tl wday1
16485 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16486 (setq org-read-date-analyze-futurep nil
16487 org-read-date-analyze-forced-year nil)
16488 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16489 (setq ans "+0"))
16491 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16492 (setq ans (replace-match "" t t ans)
16493 deltan (car delta)
16494 deltaw (nth 1 delta)
16495 deltadef (nth 2 delta)))
16497 ;; Check if there is an iso week date in there. If yes, store the
16498 ;; info and postpone interpreting it until the rest of the parsing
16499 ;; is done.
16500 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16501 (setq iso-year (if (match-end 1)
16502 (org-small-year-to-year
16503 (string-to-number (match-string 1 ans))))
16504 iso-weekday (if (match-end 3)
16505 (string-to-number (match-string 3 ans)))
16506 iso-week (string-to-number (match-string 2 ans)))
16507 (setq ans (replace-match "" t t ans)))
16509 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16510 (when (string-match
16511 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16512 (setq year (if (match-end 2)
16513 (string-to-number (match-string 2 ans))
16514 (progn (setq kill-year t)
16515 (string-to-number (format-time-string "%Y"))))
16516 month (string-to-number (match-string 3 ans))
16517 day (string-to-number (match-string 4 ans)))
16518 (if (< year 100) (setq year (+ 2000 year)))
16519 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16520 t nil ans)))
16522 ;; Help matching dotted european dates
16523 (when (string-match
16524 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16525 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16526 (setq kill-year t)
16527 (string-to-number (format-time-string "%Y")))
16528 day (string-to-number (match-string 1 ans))
16529 month (string-to-number (match-string 2 ans))
16530 ans (replace-match (format "%04d-%02d-%02d" year month day)
16531 t nil ans)))
16533 ;; Help matching american dates, like 5/30 or 5/30/7
16534 (when (string-match
16535 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16536 (setq year (if (match-end 4)
16537 (string-to-number (match-string 4 ans))
16538 (progn (setq kill-year t)
16539 (string-to-number (format-time-string "%Y"))))
16540 month (string-to-number (match-string 1 ans))
16541 day (string-to-number (match-string 2 ans)))
16542 (if (< year 100) (setq year (+ 2000 year)))
16543 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16544 t nil ans)))
16545 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16546 ;; If there is a time with am/pm, and *no* time without it, we convert
16547 ;; so that matching will be successful.
16548 (loop for i from 1 to 2 do ; twice, for end time as well
16549 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16550 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16551 (setq hour (string-to-number (match-string 1 ans))
16552 minute (if (match-end 3)
16553 (string-to-number (match-string 3 ans))
16555 pm (equal ?p
16556 (string-to-char (downcase (match-string 4 ans)))))
16557 (if (and (= hour 12) (not pm))
16558 (setq hour 0)
16559 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16560 (setq ans (replace-match (format "%02d:%02d" hour minute)
16561 t t ans))))
16563 ;; Check if a time range is given as a duration
16564 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16565 (setq hour (string-to-number (match-string 1 ans))
16566 h2 (+ hour (string-to-number (match-string 3 ans)))
16567 minute (string-to-number (match-string 2 ans))
16568 m2 (+ minute (if (match-end 5) (string-to-number
16569 (match-string 5 ans))0)))
16570 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16571 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16572 t t ans)))
16574 ;; Check if there is a time range
16575 (when (boundp 'org-end-time-was-given)
16576 (setq org-time-was-given nil)
16577 (when (and (string-match org-plain-time-of-day-regexp ans)
16578 (match-end 8))
16579 (setq org-end-time-was-given (match-string 8 ans))
16580 (setq ans (concat (substring ans 0 (match-beginning 7))
16581 (substring ans (match-end 7))))))
16583 (setq tl (parse-time-string ans)
16584 day (or (nth 3 tl) (nth 3 org-defdecode))
16585 month (or (nth 4 tl)
16586 (if (and org-read-date-prefer-future
16587 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16588 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16589 (nth 4 org-defdecode)))
16590 year (or (and (not kill-year) (nth 5 tl))
16591 (if (and org-read-date-prefer-future
16592 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16593 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16594 (nth 5 org-defdecode)))
16595 hour (or (nth 2 tl) (nth 2 org-defdecode))
16596 minute (or (nth 1 tl) (nth 1 org-defdecode))
16597 second (or (nth 0 tl) 0)
16598 wday (nth 6 tl))
16600 (when (and (eq org-read-date-prefer-future 'time)
16601 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16602 (equal day (nth 3 nowdecode))
16603 (equal month (nth 4 nowdecode))
16604 (equal year (nth 5 nowdecode))
16605 (nth 2 tl)
16606 (or (< (nth 2 tl) (nth 2 nowdecode))
16607 (and (= (nth 2 tl) (nth 2 nowdecode))
16608 (nth 1 tl)
16609 (< (nth 1 tl) (nth 1 nowdecode)))))
16610 (setq day (1+ day)
16611 futurep t))
16613 ;; Special date definitions below
16614 (cond
16615 (iso-week
16616 ;; There was an iso week
16617 (require 'cal-iso)
16618 (setq futurep nil)
16619 (setq year (or iso-year year)
16620 day (or iso-weekday wday 1)
16621 wday nil ; to make sure that the trigger below does not match
16622 iso-date (calendar-gregorian-from-absolute
16623 (calendar-absolute-from-iso
16624 (list iso-week day year))))
16625 ; FIXME: Should we also push ISO weeks into the future?
16626 ; (when (and org-read-date-prefer-future
16627 ; (not iso-year)
16628 ; (< (calendar-absolute-from-gregorian iso-date)
16629 ; (time-to-days (current-time))))
16630 ; (setq year (1+ year)
16631 ; iso-date (calendar-gregorian-from-absolute
16632 ; (calendar-absolute-from-iso
16633 ; (list iso-week day year)))))
16634 (setq month (car iso-date)
16635 year (nth 2 iso-date)
16636 day (nth 1 iso-date)))
16637 (deltan
16638 (setq futurep nil)
16639 (unless deltadef
16640 (let ((now (decode-time (current-time))))
16641 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16642 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16643 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16644 ((equal deltaw "m") (setq month (+ month deltan)))
16645 ((equal deltaw "y") (setq year (+ year deltan)))))
16646 ((and wday (not (nth 3 tl)))
16647 ;; Weekday was given, but no day, so pick that day in the week
16648 ;; on or after the derived date.
16649 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16650 (unless (equal wday wday1)
16651 (setq day (+ day (% (- wday wday1 -7) 7))))))
16652 (if (and (boundp 'org-time-was-given)
16653 (nth 2 tl))
16654 (setq org-time-was-given t))
16655 (if (< year 100) (setq year (+ 2000 year)))
16656 ;; Check of the date is representable
16657 (if org-read-date-force-compatible-dates
16658 (progn
16659 (if (< year 1970)
16660 (setq year 1970 org-read-date-analyze-forced-year t))
16661 (if (> year 2037)
16662 (setq year 2037 org-read-date-analyze-forced-year t)))
16663 (condition-case nil
16664 (ignore (encode-time second minute hour day month year))
16665 (error
16666 (setq year (nth 5 org-defdecode))
16667 (setq org-read-date-analyze-forced-year t))))
16668 (setq org-read-date-analyze-futurep futurep)
16669 (list second minute hour day month year)))
16671 (defvar parse-time-weekdays)
16672 (defun org-read-date-get-relative (s today default)
16673 "Check string S for special relative date string.
16674 TODAY and DEFAULT are internal times, for today and for a default.
16675 Return shift list (N what def-flag)
16676 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16677 N is the number of WHATs to shift.
16678 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16679 the DEFAULT date rather than TODAY."
16680 (require 'parse-time)
16681 (when (and
16682 (string-match
16683 (concat
16684 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16685 "\\([0-9]+\\)?"
16686 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16687 "\\([ \t]\\|$\\)") s)
16688 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16689 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16690 (string-to-char (substring (match-string 1 s) -1))
16691 ?+))
16692 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16693 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16694 (what (if (match-end 3) (match-string 3 s) "d"))
16695 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16696 (date (if rel default today))
16697 (wday (nth 6 (decode-time date)))
16698 delta)
16699 (if wday1
16700 (progn
16701 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16702 (if (= delta 0) (setq delta 7))
16703 (if (= dir ?-)
16704 (progn
16705 (setq delta (- delta 7))
16706 (if (= delta 0) (setq delta -7))))
16707 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16708 (list delta "d" rel))
16709 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16711 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16712 "Turn a user-specified date into the internal representation.
16713 The internal representation needed by the calendar is (month day year).
16714 This is a wrapper to handle the brain-dead convention in calendar that
16715 user function argument order change dependent on argument order."
16716 (if (boundp 'calendar-date-style)
16717 (cond
16718 ((eq calendar-date-style 'american)
16719 (list arg1 arg2 arg3))
16720 ((eq calendar-date-style 'european)
16721 (list arg2 arg1 arg3))
16722 ((eq calendar-date-style 'iso)
16723 (list arg2 arg3 arg1)))
16724 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16725 (if (org-bound-and-true-p european-calendar-style)
16726 (list arg2 arg1 arg3)
16727 (list arg1 arg2 arg3)))))
16729 (defun org-eval-in-calendar (form &optional keepdate)
16730 "Eval FORM in the calendar window and return to current window.
16731 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16732 otherwise stick to the current value of `org-ans2'."
16733 (let ((sf (selected-frame))
16734 (sw (selected-window)))
16735 (select-window (get-buffer-window "*Calendar*" t))
16736 (eval form)
16737 (when (and (not keepdate) (calendar-cursor-to-date))
16738 (let* ((date (calendar-cursor-to-date))
16739 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16740 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16741 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16742 (select-window sw)
16743 (org-select-frame-set-input-focus sf)))
16745 (defun org-calendar-select ()
16746 "Return to `org-read-date' with the date currently selected.
16747 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16748 (interactive)
16749 (when (calendar-cursor-to-date)
16750 (let* ((date (calendar-cursor-to-date))
16751 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16752 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16753 (if (active-minibuffer-window) (exit-minibuffer))))
16755 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16756 "Insert a date stamp for the date given by the internal TIME.
16757 WITH-HM means use the stamp format that includes the time of the day.
16758 INACTIVE means use square brackets instead of angular ones, so that the
16759 stamp will not contribute to the agenda.
16760 PRE and POST are optional strings to be inserted before and after the
16761 stamp.
16762 The command returns the inserted time stamp."
16763 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16764 stamp)
16765 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16766 (insert-before-markers (or pre ""))
16767 (when (listp extra)
16768 (setq extra (car extra))
16769 (if (and (stringp extra)
16770 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16771 (setq extra (format "-%02d:%02d"
16772 (string-to-number (match-string 1 extra))
16773 (string-to-number (match-string 2 extra))))
16774 (setq extra nil)))
16775 (when extra
16776 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16777 (insert-before-markers (setq stamp (format-time-string fmt time)))
16778 (insert-before-markers (or post ""))
16779 (setq org-last-inserted-timestamp stamp)))
16781 (defun org-toggle-time-stamp-overlays ()
16782 "Toggle the use of custom time stamp formats."
16783 (interactive)
16784 (setq org-display-custom-times (not org-display-custom-times))
16785 (unless org-display-custom-times
16786 (let ((p (point-min)) (bmp (buffer-modified-p)))
16787 (while (setq p (next-single-property-change p 'display))
16788 (if (and (get-text-property p 'display)
16789 (eq (get-text-property p 'face) 'org-date))
16790 (remove-text-properties
16791 p (setq p (next-single-property-change p 'display))
16792 '(display t))))
16793 (set-buffer-modified-p bmp)))
16794 (if (featurep 'xemacs)
16795 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16796 (org-restart-font-lock)
16797 (setq org-table-may-need-update t)
16798 (if org-display-custom-times
16799 (message "Time stamps are overlaid with custom format")
16800 (message "Time stamp overlays removed")))
16802 (defun org-display-custom-time (beg end)
16803 "Overlay modified time stamp format over timestamp between BEG and END."
16804 (let* ((ts (buffer-substring beg end))
16805 t1 w1 with-hm tf time str w2 (off 0))
16806 (save-match-data
16807 (setq t1 (org-parse-time-string ts t))
16808 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16809 (setq off (- (match-end 0) (match-beginning 0)))))
16810 (setq end (- end off))
16811 (setq w1 (- end beg)
16812 with-hm (and (nth 1 t1) (nth 2 t1))
16813 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16814 time (org-fix-decoded-time t1)
16815 str (org-add-props
16816 (format-time-string
16817 (substring tf 1 -1) (apply 'encode-time time))
16818 nil 'mouse-face 'highlight)
16819 w2 (length str))
16820 (if (not (= w2 w1))
16821 (add-text-properties (1+ beg) (+ 2 beg)
16822 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16823 (if (featurep 'xemacs)
16824 (progn
16825 (put-text-property beg end 'invisible t)
16826 (put-text-property beg end 'end-glyph (make-glyph str)))
16827 (put-text-property beg end 'display str))))
16829 (defun org-translate-time (string)
16830 "Translate all timestamps in STRING to custom format.
16831 But do this only if the variable `org-display-custom-times' is set."
16832 (when org-display-custom-times
16833 (save-match-data
16834 (let* ((start 0)
16835 (re org-ts-regexp-both)
16836 t1 with-hm inactive tf time str beg end)
16837 (while (setq start (string-match re string start))
16838 (setq beg (match-beginning 0)
16839 end (match-end 0)
16840 t1 (save-match-data
16841 (org-parse-time-string (substring string beg end) t))
16842 with-hm (and (nth 1 t1) (nth 2 t1))
16843 inactive (equal (substring string beg (1+ beg)) "[")
16844 tf (funcall (if with-hm 'cdr 'car)
16845 org-time-stamp-custom-formats)
16846 time (org-fix-decoded-time t1)
16847 str (format-time-string
16848 (concat
16849 (if inactive "[" "<") (substring tf 1 -1)
16850 (if inactive "]" ">"))
16851 (apply 'encode-time time))
16852 string (replace-match str t t string)
16853 start (+ start (length str)))))))
16854 string)
16856 (defun org-fix-decoded-time (time)
16857 "Set 0 instead of nil for the first 6 elements of time.
16858 Don't touch the rest."
16859 (let ((n 0))
16860 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16862 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16864 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16865 "Difference between TIMESTAMP-STRING and now in days.
16866 If SECONDS is non-nil, return the difference in seconds."
16867 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16868 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16869 (funcall fdiff (current-time)))))
16871 (defun org-deadline-close (timestamp-string &optional ndays)
16872 "Is the time in TIMESTAMP-STRING close to the current date?"
16873 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16874 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16875 (not (org-entry-is-done-p))))
16877 (defun org-get-wdays (ts &optional delay zero-delay)
16878 "Get the deadline lead time appropriate for timestring TS.
16879 When DELAY is non-nil, get the delay time for scheduled items
16880 instead of the deadline lead time. When ZERO-DELAY is non-nil
16881 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16882 don't try to find the delay cookie in the scheduled timestamp."
16883 (let ((tv (if delay org-scheduled-delay-days
16884 org-deadline-warning-days)))
16885 (cond
16886 ((or (and delay (< tv 0))
16887 (and delay zero-delay (<= tv 0))
16888 (and (not delay) (<= tv 0)))
16889 ;; Enforce this value no matter what
16890 (- tv))
16891 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16892 ;; lead time is specified.
16893 (floor (* (string-to-number (match-string 1 ts))
16894 (cdr (assoc (match-string 2 ts)
16895 '(("d" . 1) ("w" . 7)
16896 ("m" . 30.4) ("y" . 365.25)
16897 ("h" . 0.041667)))))))
16898 ;; go for the default.
16899 (t tv))))
16901 (defun org-calendar-select-mouse (ev)
16902 "Return to `org-read-date' with the date currently selected.
16903 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16904 (interactive "e")
16905 (mouse-set-point ev)
16906 (when (calendar-cursor-to-date)
16907 (let* ((date (calendar-cursor-to-date))
16908 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16909 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16910 (if (active-minibuffer-window) (exit-minibuffer))))
16912 (defun org-check-deadlines (ndays)
16913 "Check if there are any deadlines due or past due.
16914 A deadline is considered due if it happens within `org-deadline-warning-days'
16915 days from today's date. If the deadline appears in an entry marked DONE,
16916 it is not shown. The prefix arg NDAYS can be used to test that many
16917 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16918 (interactive "P")
16919 (let* ((org-warn-days
16920 (cond
16921 ((equal ndays '(4)) 100000)
16922 (ndays (prefix-numeric-value ndays))
16923 (t (abs org-deadline-warning-days))))
16924 (case-fold-search nil)
16925 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16926 (callback
16927 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16929 (message "%d deadlines past-due or due within %d days"
16930 (org-occur regexp nil callback)
16931 org-warn-days)))
16933 (defsubst org-re-timestamp (type)
16934 "Return a regexp for timestamp TYPE.
16935 Allowed values for TYPE are:
16937 all: all timestamps
16938 active: only active timestamps (<...>)
16939 inactive: only inactive timestamps ([...])
16940 scheduled: only scheduled timestamps
16941 deadline: only deadline timestamps
16942 closed: only closed time-stamps
16944 When TYPE is nil, fall back on returning a regexp that matches
16945 both scheduled and deadline timestamps."
16946 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16947 ((eq type 'active) org-ts-regexp)
16948 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16949 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16950 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16951 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
16952 ((eq type 'scheduled-or-deadline)
16953 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16955 (defun org-check-before-date (date)
16956 "Check if there are deadlines or scheduled entries before DATE."
16957 (interactive (list (org-read-date)))
16958 (let ((case-fold-search nil)
16959 (regexp (org-re-timestamp org-ts-type))
16960 (callback
16961 (lambda () (time-less-p
16962 (org-time-string-to-time (match-string 1))
16963 (org-time-string-to-time date)))))
16964 (message "%d entries before %s"
16965 (org-occur regexp nil callback) date)))
16967 (defun org-check-after-date (date)
16968 "Check if there are deadlines or scheduled entries after DATE."
16969 (interactive (list (org-read-date)))
16970 (let ((case-fold-search nil)
16971 (regexp (org-re-timestamp org-ts-type))
16972 (callback
16973 (lambda () (not
16974 (time-less-p
16975 (org-time-string-to-time (match-string 1))
16976 (org-time-string-to-time date))))))
16977 (message "%d entries after %s"
16978 (org-occur regexp nil callback) date)))
16980 (defun org-check-dates-range (start-date end-date)
16981 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16982 (interactive (list (org-read-date nil nil nil "Range starts")
16983 (org-read-date nil nil nil "Range end")))
16984 (let ((case-fold-search nil)
16985 (regexp (org-re-timestamp org-ts-type))
16986 (callback
16987 (lambda ()
16988 (let ((match (match-string 1)))
16989 (and
16990 (not (time-less-p
16991 (org-time-string-to-time match)
16992 (org-time-string-to-time start-date)))
16993 (time-less-p
16994 (org-time-string-to-time match)
16995 (org-time-string-to-time end-date)))))))
16996 (message "%d entries between %s and %s"
16997 (org-occur regexp nil callback) start-date end-date)))
16999 (defun org-evaluate-time-range (&optional to-buffer)
17000 "Evaluate a time range by computing the difference between start and end.
17001 Normally the result is just printed in the echo area, but with prefix arg
17002 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17003 If the time range is actually in a table, the result is inserted into the
17004 next column.
17005 For time difference computation, a year is assumed to be exactly 365
17006 days in order to avoid rounding problems."
17007 (interactive "P")
17009 (org-clock-update-time-maybe)
17010 (save-excursion
17011 (unless (org-at-date-range-p t)
17012 (goto-char (point-at-bol))
17013 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17014 (if (not (org-at-date-range-p t))
17015 (user-error "Not at a time-stamp range, and none found in current line")))
17016 (let* ((ts1 (match-string 1))
17017 (ts2 (match-string 2))
17018 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17019 (match-end (match-end 0))
17020 (time1 (org-time-string-to-time ts1))
17021 (time2 (org-time-string-to-time ts2))
17022 (t1 (org-float-time time1))
17023 (t2 (org-float-time time2))
17024 (diff (abs (- t2 t1)))
17025 (negative (< (- t2 t1) 0))
17026 ;; (ys (floor (* 365 24 60 60)))
17027 (ds (* 24 60 60))
17028 (hs (* 60 60))
17029 (fy "%dy %dd %02d:%02d")
17030 (fy1 "%dy %dd")
17031 (fd "%dd %02d:%02d")
17032 (fd1 "%dd")
17033 (fh "%02d:%02d")
17034 y d h m align)
17035 (if havetime
17036 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17038 d (floor (/ diff ds)) diff (mod diff ds)
17039 h (floor (/ diff hs)) diff (mod diff hs)
17040 m (floor (/ diff 60)))
17041 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17043 d (floor (+ (/ diff ds) 0.5))
17044 h 0 m 0))
17045 (if (not to-buffer)
17046 (message "%s" (org-make-tdiff-string y d h m))
17047 (if (org-at-table-p)
17048 (progn
17049 (goto-char match-end)
17050 (setq align t)
17051 (and (looking-at " *|") (goto-char (match-end 0))))
17052 (goto-char match-end))
17053 (if (looking-at
17054 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17055 (replace-match ""))
17056 (if negative (insert " -"))
17057 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17058 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17059 (insert " " (format fh h m))))
17060 (if align (org-table-align))
17061 (message "Time difference inserted")))))
17063 (defun org-make-tdiff-string (y d h m)
17064 (let ((fmt "")
17065 (l nil))
17066 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
17067 l (push y l)))
17068 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
17069 l (push d l)))
17070 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
17071 l (push h l)))
17072 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
17073 l (push m l)))
17074 (apply 'format fmt (nreverse l))))
17076 (defun org-time-string-to-time (s &optional buffer pos)
17077 "Convert a timestamp string into internal time."
17078 (condition-case errdata
17079 (apply 'encode-time (org-parse-time-string s))
17080 (error (error "Bad timestamp `%s'%s\nError was: %s"
17081 s (if (not (and buffer pos))
17083 (format " at %d in buffer `%s'" pos buffer))
17084 (cdr errdata)))))
17086 (defun org-time-string-to-seconds (s)
17087 "Convert a timestamp string to a number of seconds."
17088 (org-float-time (org-time-string-to-time s)))
17090 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17091 "Convert a time stamp to an absolute day number.
17092 If there is a specifier for a cyclic time stamp, get the closest
17093 date to DAYNR.
17094 PREFER and SHOW-ALL are passed through to `org-closest-date'.
17095 The variable `date' is bound by the calendar when this is called."
17096 (cond
17097 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17098 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17099 daynr
17100 (+ daynr 1000)))
17101 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
17102 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17103 (time-to-days (current-time))) (match-string 0 s)
17104 prefer show-all))
17105 (t (time-to-days
17106 (condition-case errdata
17107 (apply 'encode-time (org-parse-time-string s))
17108 (error (error "Bad timestamp `%s'%s\nError was: %s"
17109 s (if (not (and buffer pos))
17111 (format " at %d in buffer `%s'" pos buffer))
17112 (cdr errdata))))))))
17114 (defun org-days-to-iso-week (days)
17115 "Return the iso week number."
17116 (require 'cal-iso)
17117 (car (calendar-iso-from-absolute days)))
17119 (defun org-small-year-to-year (year)
17120 "Convert 2-digit years into 4-digit years.
17121 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
17122 The year 2000 cannot be abbreviated. Any year larger than 99
17123 is returned unchanged."
17124 (if (< year 38)
17125 (setq year (+ 2000 year))
17126 (if (< year 100)
17127 (setq year (+ 1900 year))))
17128 year)
17130 (defun org-time-from-absolute (d)
17131 "Return the time corresponding to date D.
17132 D may be an absolute day number, or a calendar-type list (month day year)."
17133 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17134 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17136 (defun org-calendar-holiday ()
17137 "List of holidays, for Diary display in Org-mode."
17138 (require 'holidays)
17139 (let ((hl (funcall
17140 (if (fboundp 'calendar-check-holidays)
17141 'calendar-check-holidays 'check-calendar-holidays) date)))
17142 (if hl (mapconcat 'identity hl "; "))))
17144 (defun org-diary-sexp-entry (sexp entry date)
17145 "Process a SEXP diary ENTRY for DATE."
17146 (require 'diary-lib)
17147 (let ((result (if calendar-debug-sexp
17148 (let ((stack-trace-on-error t))
17149 (eval (car (read-from-string sexp))))
17150 (condition-case nil
17151 (eval (car (read-from-string sexp)))
17152 (error
17153 (beep)
17154 (message "Bad sexp at line %d in %s: %s"
17155 (org-current-line)
17156 (buffer-file-name) sexp)
17157 (sleep-for 2))))))
17158 (cond ((stringp result) (split-string result "; "))
17159 ((and (consp result)
17160 (not (consp (cdr result)))
17161 (stringp (cdr result))) (cdr result))
17162 ((and (consp result)
17163 (stringp (car result))) result)
17164 (result entry))))
17166 (defun org-diary-to-ical-string (frombuf)
17167 "Get iCalendar entries from diary entries in buffer FROMBUF.
17168 This uses the icalendar.el library."
17169 (let* ((tmpdir (if (featurep 'xemacs)
17170 (temp-directory)
17171 temporary-file-directory))
17172 (tmpfile (make-temp-name
17173 (expand-file-name "orgics" tmpdir)))
17174 buf rtn b e)
17175 (with-current-buffer frombuf
17176 (icalendar-export-region (point-min) (point-max) tmpfile)
17177 (setq buf (find-buffer-visiting tmpfile))
17178 (set-buffer buf)
17179 (goto-char (point-min))
17180 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17181 (setq b (match-beginning 0)))
17182 (goto-char (point-max))
17183 (if (re-search-backward "^END:VEVENT" nil t)
17184 (setq e (match-end 0)))
17185 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17186 (kill-buffer buf)
17187 (delete-file tmpfile)
17188 rtn))
17190 (defun org-closest-date (start current change prefer show-all)
17191 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17192 When PREFER is `past', return a date that is either CURRENT or past.
17193 When PREFER is `future', return a date that is either CURRENT or future.
17194 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17195 ;; Make the proper lists from the dates
17196 (catch 'exit
17197 (let ((a1 '(("h" . hour)
17198 ("d" . day)
17199 ("w" . week)
17200 ("m" . month)
17201 ("y" . year)))
17202 (shour (nth 2 (org-parse-time-string start)))
17203 dn dw sday cday n1 n2 n0
17204 d m y y1 y2 date1 date2 nmonths nm ny m2)
17206 (setq start (org-date-to-gregorian start)
17207 current (org-date-to-gregorian
17208 (if show-all
17209 current
17210 (time-to-days (current-time))))
17211 sday (calendar-absolute-from-gregorian start)
17212 cday (calendar-absolute-from-gregorian current))
17214 (if (<= cday sday) (throw 'exit sday))
17216 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17217 (setq dn (string-to-number (match-string 1 change))
17218 dw (cdr (assoc (match-string 2 change) a1)))
17219 (user-error "Invalid change specifier: %s" change))
17220 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17221 (cond
17222 ((eq dw 'hour)
17223 (let ((missing-hours
17224 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17225 dn)))
17226 (setq n1 (if (zerop missing-hours) cday
17227 (- cday (1+ (floor (/ missing-hours 24)))))
17228 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17229 ((eq dw 'day)
17230 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17231 n2 (+ n1 dn)))
17232 ((eq dw 'year)
17233 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17234 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17235 (setq date1 (list m d y1)
17236 n1 (calendar-absolute-from-gregorian date1)
17237 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17238 n2 (calendar-absolute-from-gregorian date2)))
17239 ((eq dw 'month)
17240 ;; approx number of month between the two dates
17241 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17242 ;; How often does dn fit in there?
17243 (setq d (nth 1 start) m (car start) y (nth 2 start)
17244 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17245 m (+ m nm)
17246 ny (floor (/ m 12))
17247 y (+ y ny)
17248 m (- m (* ny 12)))
17249 (while (> m 12) (setq m (- m 12) y (1+ y)))
17250 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17251 (setq m2 (+ m dn) y2 y)
17252 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17253 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17254 (while (<= n2 cday)
17255 (setq n1 n2 m m2 y y2)
17256 (setq m2 (+ m dn) y2 y)
17257 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17258 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17259 ;; Make sure n1 is the earlier date
17260 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17261 (if show-all
17262 (cond
17263 ((eq prefer 'past) (if (= cday n2) n2 n1))
17264 ((eq prefer 'future) (if (= cday n1) n1 n2))
17265 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17266 (cond
17267 ((eq prefer 'past) (if (= cday n2) n2 n1))
17268 ((eq prefer 'future) (if (= cday n1) n1 n2))
17269 (t (if (= cday n1) n1 n2)))))))
17271 (defun org-date-to-gregorian (date)
17272 "Turn any specification of DATE into a Gregorian date for the calendar."
17273 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17274 ((and (listp date) (= (length date) 3)) date)
17275 ((stringp date)
17276 (setq date (org-parse-time-string date))
17277 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17278 ((listp date)
17279 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17281 (defun org-parse-time-string (s &optional nodefault)
17282 "Parse the standard Org-mode time string.
17283 This should be a lot faster than the normal `parse-time-string'.
17284 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17285 hour and minute fields will be nil if not given."
17286 (cond ((string-match org-ts-regexp0 s)
17287 (list 0
17288 (if (or (match-beginning 8) (not nodefault))
17289 (string-to-number (or (match-string 8 s) "0")))
17290 (if (or (match-beginning 7) (not nodefault))
17291 (string-to-number (or (match-string 7 s) "0")))
17292 (string-to-number (match-string 4 s))
17293 (string-to-number (match-string 3 s))
17294 (string-to-number (match-string 2 s))
17295 nil nil nil))
17296 ((string-match "^<[^>]+>$" s)
17297 (decode-time (seconds-to-time (org-matcher-time s))))
17298 (t (error "Not a standard Org-mode time string: %s" s))))
17300 (defun org-timestamp-up (&optional arg)
17301 "Increase the date item at the cursor by one.
17302 If the cursor is on the year, change the year. If it is on the month,
17303 the day or the time, change that.
17304 With prefix ARG, change by that many units."
17305 (interactive "p")
17306 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17308 (defun org-timestamp-down (&optional arg)
17309 "Decrease the date item at the cursor by one.
17310 If the cursor is on the year, change the year. If it is on the month,
17311 the day or the time, change that.
17312 With prefix ARG, change by that many units."
17313 (interactive "p")
17314 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17316 (defun org-timestamp-up-day (&optional arg)
17317 "Increase the date in the time stamp by one day.
17318 With prefix ARG, change that many days."
17319 (interactive "p")
17320 (if (and (not (org-at-timestamp-p t))
17321 (org-at-heading-p))
17322 (org-todo 'up)
17323 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17325 (defun org-timestamp-down-day (&optional arg)
17326 "Decrease the date in the time stamp by one day.
17327 With prefix ARG, change that many days."
17328 (interactive "p")
17329 (if (and (not (org-at-timestamp-p t))
17330 (org-at-heading-p))
17331 (org-todo 'down)
17332 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17334 (defun org-at-timestamp-p (&optional inactive-ok)
17335 "Determine if the cursor is in or at a timestamp."
17336 (interactive)
17337 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17338 (pos (point))
17339 (ans (or (looking-at tsr)
17340 (save-excursion
17341 (skip-chars-backward "^[<\n\r\t")
17342 (if (> (point) (point-min)) (backward-char 1))
17343 (and (looking-at tsr)
17344 (> (- (match-end 0) pos) -1))))))
17345 (and ans
17346 (boundp 'org-ts-what)
17347 (setq org-ts-what
17348 (cond
17349 ((= pos (match-beginning 0)) 'bracket)
17350 ;; Point is considered to be "on the bracket" whether
17351 ;; it's really on it or right after it.
17352 ((= pos (1- (match-end 0))) 'bracket)
17353 ((= pos (match-end 0)) 'after)
17354 ((org-pos-in-match-range pos 2) 'year)
17355 ((org-pos-in-match-range pos 3) 'month)
17356 ((org-pos-in-match-range pos 7) 'hour)
17357 ((org-pos-in-match-range pos 8) 'minute)
17358 ((or (org-pos-in-match-range pos 4)
17359 (org-pos-in-match-range pos 5)) 'day)
17360 ((and (> pos (or (match-end 8) (match-end 5)))
17361 (< pos (match-end 0)))
17362 (- pos (or (match-end 8) (match-end 5))))
17363 (t 'day))))
17364 ans))
17366 (defun org-toggle-timestamp-type ()
17367 "Toggle the type (<active> or [inactive]) of a time stamp."
17368 (interactive)
17369 (when (org-at-timestamp-p t)
17370 (let ((beg (match-beginning 0)) (end (match-end 0))
17371 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17372 (save-excursion
17373 (goto-char beg)
17374 (while (re-search-forward "[][<>]" end t)
17375 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17376 t t)))
17377 (message "Timestamp is now %sactive"
17378 (if (equal (char-after beg) ?<) "" "in")))))
17380 (defun org-at-clock-log-p nil
17381 "Is the cursor on the clock log line?"
17382 (save-excursion
17383 (move-beginning-of-line 1)
17384 (looking-at "^[ \t]*CLOCK:")))
17386 (defvar org-clock-history) ; defined in org-clock.el
17387 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17388 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17389 "Change the date in the time stamp at point.
17390 The date will be changed by N times WHAT. WHAT can be `day', `month',
17391 `year', `minute', `second'. If WHAT is not given, the cursor position
17392 in the timestamp determines what will be changed.
17393 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17394 (let ((origin (point)) origin-cat
17395 with-hm inactive
17396 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17397 org-ts-what
17398 extra rem
17399 ts time time0 fixnext clrgx)
17400 (if (not (org-at-timestamp-p t))
17401 (user-error "Not at a timestamp"))
17402 (if (and (not what) (eq org-ts-what 'bracket))
17403 (org-toggle-timestamp-type)
17404 ;; Point isn't on brackets. Remember the part of the time-stamp
17405 ;; the point was in. Indeed, size of time-stamps may change,
17406 ;; but point must be kept in the same category nonetheless.
17407 (setq origin-cat org-ts-what)
17408 (if (and (not what) (not (eq org-ts-what 'day))
17409 org-display-custom-times
17410 (get-text-property (point) 'display)
17411 (not (get-text-property (1- (point)) 'display)))
17412 (setq org-ts-what 'day))
17413 (setq org-ts-what (or what org-ts-what)
17414 inactive (= (char-after (match-beginning 0)) ?\[)
17415 ts (match-string 0))
17416 (replace-match "")
17417 (when (string-match
17418 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17420 (setq extra (match-string 1 ts))
17421 (if suppress-tmp-delay
17422 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17423 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17424 (setq with-hm t))
17425 (setq time0 (org-parse-time-string ts))
17426 (when (and updown
17427 (eq org-ts-what 'minute)
17428 (not current-prefix-arg))
17429 ;; This looks like s-up and s-down. Change by one rounding step.
17430 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17431 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17432 (setcar (cdr time0) (+ (nth 1 time0)
17433 (if (> n 0) (- rem) (- dm rem))))))
17434 (setq time
17435 (encode-time (or (car time0) 0)
17436 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17437 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17438 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17439 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17440 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17441 (nthcdr 6 time0)))
17442 (when (and (member org-ts-what '(hour minute))
17443 extra
17444 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17445 (setq extra (org-modify-ts-extra
17446 extra
17447 (if (eq org-ts-what 'hour) 2 5)
17448 n dm)))
17449 (when (integerp org-ts-what)
17450 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17451 (if (eq what 'calendar)
17452 (let ((cal-date (org-get-date-from-calendar)))
17453 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17454 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17455 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17456 (setcar time0 (or (car time0) 0))
17457 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17458 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17459 (setq time (apply 'encode-time time0))))
17460 ;; Insert the new time-stamp, and ensure point stays in the same
17461 ;; category as before (i.e. not after the last position in that
17462 ;; category).
17463 (let ((pos (point)))
17464 ;; Stay before inserted string. `save-excursion' is of no use.
17465 (setq org-last-changed-timestamp
17466 (org-insert-time-stamp time with-hm inactive nil nil extra))
17467 (goto-char pos))
17468 (save-match-data
17469 (looking-at org-ts-regexp3)
17470 (goto-char (cond
17471 ;; `day' category ends before `hour' if any, or at
17472 ;; the end of the day name.
17473 ((eq origin-cat 'day)
17474 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17475 ((eq origin-cat 'hour) (min (match-end 7) origin))
17476 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17477 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17478 ;; `year' and `month' have both fixed size: point
17479 ;; couldn't have moved into another part.
17480 (t origin))))
17481 ;; Update clock if on a CLOCK line.
17482 (org-clock-update-time-maybe)
17483 ;; Maybe adjust the closest clock in `org-clock-history'
17484 (when org-clock-adjust-closest
17485 (if (not (and (org-at-clock-log-p)
17486 (< 1 (length (delq nil (mapcar 'marker-position
17487 org-clock-history))))))
17488 (message "No clock to adjust")
17489 (cond ((save-excursion ; fix previous clock?
17490 (re-search-backward org-ts-regexp0 nil t)
17491 (org-looking-back (concat org-clock-string " \\[")))
17492 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17493 ((save-excursion ; fix next clock?
17494 (re-search-backward org-ts-regexp0 nil t)
17495 (looking-at (concat org-ts-regexp0 "\\] =>")))
17496 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17497 (save-window-excursion
17498 ;; Find closest clock to point, adjust the previous/next one in history
17499 (let* ((p (save-excursion (org-back-to-heading t)))
17500 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17501 (clfixnth
17502 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17503 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17504 (if (not clfixpos)
17505 (message "No clock to adjust")
17506 (save-excursion
17507 (org-goto-marker-or-bmk clfixpos)
17508 (org-show-subtree)
17509 (when (re-search-forward clrgx nil t)
17510 (goto-char (match-beginning 1))
17511 (let (org-clock-adjust-closest)
17512 (org-timestamp-change n org-ts-what updown))
17513 (message "Clock adjusted in %s for heading: %s"
17514 (file-name-nondirectory (buffer-file-name))
17515 (org-get-heading t t)))))))))
17516 ;; Try to recenter the calendar window, if any.
17517 (if (and org-calendar-follow-timestamp-change
17518 (get-buffer-window "*Calendar*" t)
17519 (memq org-ts-what '(day month year)))
17520 (org-recenter-calendar (time-to-days time))))))
17522 (defun org-modify-ts-extra (s pos n dm)
17523 "Change the different parts of the lead-time and repeat fields in timestamp."
17524 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17525 ng h m new rem)
17526 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17527 (cond
17528 ((or (org-pos-in-match-range pos 2)
17529 (org-pos-in-match-range pos 3))
17530 (setq m (string-to-number (match-string 3 s))
17531 h (string-to-number (match-string 2 s)))
17532 (if (org-pos-in-match-range pos 2)
17533 (setq h (+ h n))
17534 (setq n (* dm (org-no-warnings (signum n))))
17535 (when (not (= 0 (setq rem (% m dm))))
17536 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17537 (setq m (+ m n)))
17538 (if (< m 0) (setq m (+ m 60) h (1- h)))
17539 (if (> m 59) (setq m (- m 60) h (1+ h)))
17540 (setq h (min 24 (max 0 h)))
17541 (setq ng 1 new (format "-%02d:%02d" h m)))
17542 ((org-pos-in-match-range pos 6)
17543 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17544 ((org-pos-in-match-range pos 5)
17545 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17547 ((org-pos-in-match-range pos 9)
17548 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17549 ((org-pos-in-match-range pos 8)
17550 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17552 (when ng
17553 (setq s (concat
17554 (substring s 0 (match-beginning ng))
17556 (substring s (match-end ng))))))
17559 (defun org-recenter-calendar (date)
17560 "If the calendar is visible, recenter it to DATE."
17561 (let ((cwin (get-buffer-window "*Calendar*" t)))
17562 (when cwin
17563 (let ((calendar-move-hook nil))
17564 (with-selected-window cwin
17565 (calendar-goto-date (if (listp date) date
17566 (calendar-gregorian-from-absolute date))))))))
17568 (defun org-goto-calendar (&optional arg)
17569 "Go to the Emacs calendar at the current date.
17570 If there is a time stamp in the current line, go to that date.
17571 A prefix ARG can be used to force the current date."
17572 (interactive "P")
17573 (let ((tsr org-ts-regexp) diff
17574 (calendar-move-hook nil)
17575 (calendar-view-holidays-initially-flag nil)
17576 (calendar-view-diary-initially-flag nil))
17577 (if (or (org-at-timestamp-p)
17578 (save-excursion
17579 (beginning-of-line 1)
17580 (looking-at (concat ".*" tsr))))
17581 (let ((d1 (time-to-days (current-time)))
17582 (d2 (time-to-days
17583 (org-time-string-to-time (match-string 1)))))
17584 (setq diff (- d2 d1))))
17585 (calendar)
17586 (calendar-goto-today)
17587 (if (and diff (not arg)) (calendar-forward-day diff))))
17589 (defun org-get-date-from-calendar ()
17590 "Return a list (month day year) of date at point in calendar."
17591 (with-current-buffer "*Calendar*"
17592 (save-match-data
17593 (calendar-cursor-to-date))))
17595 (defun org-date-from-calendar ()
17596 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17597 If there is already a time stamp at the cursor position, update it."
17598 (interactive)
17599 (if (org-at-timestamp-p t)
17600 (org-timestamp-change 0 'calendar)
17601 (let ((cal-date (org-get-date-from-calendar)))
17602 (org-insert-time-stamp
17603 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17605 (defcustom org-effort-durations
17606 `(("h" . 60)
17607 ("d" . ,(* 60 8))
17608 ("w" . ,(* 60 8 5))
17609 ("m" . ,(* 60 8 5 4))
17610 ("y" . ,(* 60 8 5 40)))
17611 "Conversion factor to minutes for an effort modifier.
17613 Each entry has the form (MODIFIER . MINUTES).
17615 In an effort string, a number followed by MODIFIER is multiplied
17616 by the specified number of MINUTES to obtain an effort in
17617 minutes.
17619 For example, if the value of this variable is ((\"hours\" . 60)), then an
17620 effort string \"2hours\" is equivalent to 120 minutes."
17621 :group 'org-agenda
17622 :version "24.1"
17623 :type '(alist :key-type (string :tag "Modifier")
17624 :value-type (number :tag "Minutes")))
17626 (defun org-minutes-to-clocksum-string (m)
17627 "Format number of minutes as a clocksum string.
17628 The format is determined by `org-time-clocksum-format',
17629 `org-time-clocksum-use-fractional' and
17630 `org-time-clocksum-fractional-format' and
17631 `org-time-clocksum-use-effort-durations'."
17632 (let ((clocksum "")
17633 (m (round m)) ; Don't allow fractions of minutes
17634 h d w mo y fmt n)
17635 (setq h (if org-time-clocksum-use-effort-durations
17636 (cdr (assoc "h" org-effort-durations)) 60)
17637 d (if org-time-clocksum-use-effort-durations
17638 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17639 w (if org-time-clocksum-use-effort-durations
17640 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17641 mo (if org-time-clocksum-use-effort-durations
17642 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17643 y (if org-time-clocksum-use-effort-durations
17644 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17645 ;; fractional format
17646 (if org-time-clocksum-use-fractional
17647 (cond
17648 ;; single format string
17649 ((stringp org-time-clocksum-fractional-format)
17650 (format org-time-clocksum-fractional-format (/ m (float h))))
17651 ;; choice of fractional formats for different time units
17652 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17653 (> (/ (truncate m) (* y d h)) 0))
17654 (format fmt (/ m (* y d (float h)))))
17655 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17656 (> (/ (truncate m) (* mo d h)) 0))
17657 (format fmt (/ m (* mo d (float h)))))
17658 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17659 (> (/ (truncate m) (* w d h)) 0))
17660 (format fmt (/ m (* w d (float h)))))
17661 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17662 (> (/ (truncate m) (* d h)) 0))
17663 (format fmt (/ m (* d (float h)))))
17664 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17665 (> (/ (truncate m) h) 0))
17666 (format fmt (/ m (float h))))
17667 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17668 (format fmt m))
17669 ;; fall back to smallest time unit with a format
17670 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17671 (format fmt (/ m (float h))))
17672 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17673 (format fmt (/ m (* d (float h)))))
17674 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17675 (format fmt (/ m (* w d (float h)))))
17676 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17677 (format fmt (/ m (* mo d (float h)))))
17678 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17679 (format fmt (/ m (* y d (float h))))))
17680 ;; standard (non-fractional) format, with single format string
17681 (if (stringp org-time-clocksum-format)
17682 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17683 ;; separate formats components
17684 (and (setq fmt (plist-get org-time-clocksum-format :years))
17685 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17686 (plist-get org-time-clocksum-format :require-years))
17687 (setq clocksum (concat clocksum (format fmt n))
17688 m (- m (* n y d h))))
17689 (and (setq fmt (plist-get org-time-clocksum-format :months))
17690 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17691 (plist-get org-time-clocksum-format :require-months))
17692 (setq clocksum (concat clocksum (format fmt n))
17693 m (- m (* n mo d h))))
17694 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17695 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17696 (plist-get org-time-clocksum-format :require-weeks))
17697 (setq clocksum (concat clocksum (format fmt n))
17698 m (- m (* n w d h))))
17699 (and (setq fmt (plist-get org-time-clocksum-format :days))
17700 (or (> (setq n (/ (truncate m) (* d h))) 0)
17701 (plist-get org-time-clocksum-format :require-days))
17702 (setq clocksum (concat clocksum (format fmt n))
17703 m (- m (* n d h))))
17704 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17705 (or (> (setq n (/ (truncate m) h)) 0)
17706 (plist-get org-time-clocksum-format :require-hours))
17707 (setq clocksum (concat clocksum (format fmt n))
17708 m (- m (* n h))))
17709 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17710 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17711 (setq clocksum (concat clocksum (format fmt m))))
17712 ;; return formatted time duration
17713 clocksum))))
17715 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17716 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17717 "Org mode version 8.0")
17719 (defun org-hours-to-clocksum-string (n)
17720 (org-minutes-to-clocksum-string (* n 60)))
17722 (defun org-hh:mm-string-to-minutes (s)
17723 "Convert a string H:MM to a number of minutes.
17724 If the string is just a number, interpret it as minutes.
17725 In fact, the first hh:mm or number in the string will be taken,
17726 there can be extra stuff in the string.
17727 If no number is found, the return value is 0."
17728 (cond
17729 ((integerp s) s)
17730 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17731 (+ (* (string-to-number (match-string 1 s)) 60)
17732 (string-to-number (match-string 2 s))))
17733 ((string-match "\\([0-9]+\\)" s)
17734 (string-to-number (match-string 1 s)))
17735 (t 0)))
17737 (defcustom org-image-actual-width t
17738 "Should we use the actual width of images when inlining them?
17740 When set to `t', always use the image width.
17742 When set to a number, use imagemagick (when available) to set
17743 the image's width to this value.
17745 When set to a number in a list, try to get the width from any
17746 #+ATTR.* keyword if it matches a width specification like
17748 #+ATTR_HTML: :width 300px
17750 and fall back on that number if none is found.
17752 When set to nil, try to get the width from an #+ATTR.* keyword
17753 and fall back on the original width if none is found.
17755 This requires Emacs >= 24.1, build with imagemagick support."
17756 :group 'org-appearance
17757 :version "24.4"
17758 :package-version '(Org . "8.0")
17759 :type '(choice
17760 (const :tag "Use the image width" t)
17761 (integer :tag "Use a number of pixels")
17762 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17763 (const :tag "Use #+ATTR* or don't resize" nil)))
17765 (defcustom org-agenda-inhibit-startup nil
17766 "Inhibit startup when preparing agenda buffers.
17767 When this variable is `t', the initialization of the Org agenda
17768 buffers is inhibited: e.g. the visibility state is not set, the
17769 tables are not re-aligned, etc."
17770 :type 'boolean
17771 :version "24.3"
17772 :group 'org-agenda)
17774 (defcustom org-agenda-ignore-drawer-properties nil
17775 "Avoid updating text properties when building the agenda.
17776 Properties are used to prepare buffers for effort estimates, appointments,
17777 and subtree-local categories.
17778 If you don't use these in the agenda, you can add them to this list and
17779 agenda building will be a bit faster.
17780 The value is a list, with zero or more of the symbols `effort', `appt',
17781 or `category'."
17782 :type '(set :greedy t
17783 (const effort)
17784 (const appt)
17785 (const category))
17786 :version "24.3"
17787 :group 'org-agenda)
17789 (defun org-duration-string-to-minutes (s &optional output-to-string)
17790 "Convert a duration string S to minutes.
17792 A bare number is interpreted as minutes, modifiers can be set by
17793 customizing `org-effort-durations' (which see).
17795 Entries containing a colon are interpreted as H:MM by
17796 `org-hh:mm-string-to-minutes'."
17797 (let ((result 0)
17798 (re (concat "\\([0-9.]+\\) *\\("
17799 (regexp-opt (mapcar 'car org-effort-durations))
17800 "\\)")))
17801 (while (string-match re s)
17802 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17803 (string-to-number (match-string 1 s))))
17804 (setq s (replace-match "" nil t s)))
17805 (setq result (floor result))
17806 (incf result (org-hh:mm-string-to-minutes s))
17807 (if output-to-string (number-to-string result) result)))
17809 ;;;; Files
17811 (defun org-save-all-org-buffers ()
17812 "Save all Org-mode buffers without user confirmation."
17813 (interactive)
17814 (message "Saving all Org-mode buffers...")
17815 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17816 (when (featurep 'org-id) (org-id-locations-save))
17817 (message "Saving all Org-mode buffers... done"))
17819 (defun org-revert-all-org-buffers ()
17820 "Revert all Org-mode buffers.
17821 Prompt for confirmation when there are unsaved changes.
17822 Be sure you know what you are doing before letting this function
17823 overwrite your changes.
17825 This function is useful in a setup where one tracks org files
17826 with a version control system, to revert on one machine after pulling
17827 changes from another. I believe the procedure must be like this:
17829 1. M-x org-save-all-org-buffers
17830 2. Pull changes from the other machine, resolve conflicts
17831 3. M-x org-revert-all-org-buffers"
17832 (interactive)
17833 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17834 (user-error "Abort"))
17835 (save-excursion
17836 (save-window-excursion
17837 (mapc
17838 (lambda (b)
17839 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17840 (with-current-buffer b buffer-file-name))
17841 (org-pop-to-buffer-same-window b)
17842 (revert-buffer t 'no-confirm)))
17843 (buffer-list))
17844 (when (and (featurep 'org-id) org-id-track-globally)
17845 (org-id-locations-load)))))
17847 ;;;; Agenda files
17849 ;;;###autoload
17850 (defun org-switchb (&optional arg)
17851 "Switch between Org buffers.
17852 With one prefix argument, restrict available buffers to files.
17853 With two prefix arguments, restrict available buffers to agenda files.
17855 Defaults to `iswitchb' for buffer name completion.
17856 Set `org-completion-use-ido' to make it use ido instead."
17857 (interactive "P")
17858 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17859 ((equal arg '(16)) (org-buffer-list 'agenda))
17860 (t (org-buffer-list))))
17861 (org-completion-use-iswitchb org-completion-use-iswitchb)
17862 (org-completion-use-ido org-completion-use-ido))
17863 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17864 (setq org-completion-use-iswitchb t))
17865 (org-pop-to-buffer-same-window
17866 (org-icompleting-read "Org buffer: "
17867 (mapcar 'list (mapcar 'buffer-name blist))
17868 nil t))))
17870 ;;; Define some older names previously used for this functionality
17871 ;;;###autoload
17872 (defalias 'org-ido-switchb 'org-switchb)
17873 ;;;###autoload
17874 (defalias 'org-iswitchb 'org-switchb)
17876 (defun org-buffer-list (&optional predicate exclude-tmp)
17877 "Return a list of Org buffers.
17878 PREDICATE can be `export', `files' or `agenda'.
17880 export restrict the list to Export buffers.
17881 files restrict the list to buffers visiting Org files.
17882 agenda restrict the list to buffers visiting agenda files.
17884 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17885 (let* ((bfn nil)
17886 (agenda-files (and (eq predicate 'agenda)
17887 (mapcar 'file-truename (org-agenda-files t))))
17888 (filter
17889 (cond
17890 ((eq predicate 'files)
17891 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17892 ((eq predicate 'export)
17893 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17894 ((eq predicate 'agenda)
17895 (lambda (b)
17896 (with-current-buffer b
17897 (and (derived-mode-p 'org-mode)
17898 (setq bfn (buffer-file-name b))
17899 (member (file-truename bfn) agenda-files)))))
17900 (t (lambda (b) (with-current-buffer b
17901 (or (derived-mode-p 'org-mode)
17902 (string-match "\*Org .*Export"
17903 (buffer-name b)))))))))
17904 (delq nil
17905 (mapcar
17906 (lambda(b)
17907 (if (and (funcall filter b)
17908 (or (not exclude-tmp)
17909 (not (string-match "tmp" (buffer-name b)))))
17911 nil))
17912 (buffer-list)))))
17914 (defun org-agenda-files (&optional unrestricted archives)
17915 "Get the list of agenda files.
17916 Optional UNRESTRICTED means return the full list even if a restriction
17917 is currently in place.
17918 When ARCHIVES is t, include all archive files that are really being
17919 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17920 `org-agenda-archives-mode' is t."
17921 (let ((files
17922 (cond
17923 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17924 ((stringp org-agenda-files) (org-read-agenda-file-list))
17925 ((listp org-agenda-files) org-agenda-files)
17926 (t (error "Invalid value of `org-agenda-files'")))))
17927 (setq files (apply 'append
17928 (mapcar (lambda (f)
17929 (if (file-directory-p f)
17930 (directory-files
17931 f t org-agenda-file-regexp)
17932 (list f)))
17933 files)))
17934 (when org-agenda-skip-unavailable-files
17935 (setq files (delq nil
17936 (mapcar (function
17937 (lambda (file)
17938 (and (file-readable-p file) file)))
17939 files))))
17940 (when (or (eq archives t)
17941 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17942 (setq files (org-add-archive-files files)))
17943 files))
17945 (defun org-agenda-file-p (&optional file)
17946 "Return non-nil, if FILE is an agenda file.
17947 If FILE is omitted, use the file associated with the current
17948 buffer."
17949 (member (or file (buffer-file-name))
17950 (org-agenda-files t)))
17952 (defun org-edit-agenda-file-list ()
17953 "Edit the list of agenda files.
17954 Depending on setup, this either uses customize to edit the variable
17955 `org-agenda-files', or it visits the file that is holding the list. In the
17956 latter case, the buffer is set up in a way that saving it automatically kills
17957 the buffer and restores the previous window configuration."
17958 (interactive)
17959 (if (stringp org-agenda-files)
17960 (let ((cw (current-window-configuration)))
17961 (find-file org-agenda-files)
17962 (org-set-local 'org-window-configuration cw)
17963 (org-add-hook 'after-save-hook
17964 (lambda ()
17965 (set-window-configuration
17966 (prog1 org-window-configuration
17967 (kill-buffer (current-buffer))))
17968 (org-install-agenda-files-menu)
17969 (message "New agenda file list installed"))
17970 nil 'local)
17971 (message "%s" (substitute-command-keys
17972 "Edit list and finish with \\[save-buffer]")))
17973 (customize-variable 'org-agenda-files)))
17975 (defun org-store-new-agenda-file-list (list)
17976 "Set new value for the agenda file list and save it correctly."
17977 (if (stringp org-agenda-files)
17978 (let ((fe (org-read-agenda-file-list t)) b u)
17979 (while (setq b (find-buffer-visiting org-agenda-files))
17980 (kill-buffer b))
17981 (with-temp-file org-agenda-files
17982 (insert
17983 (mapconcat
17984 (lambda (f) ;; Keep un-expanded entries.
17985 (if (setq u (assoc f fe))
17986 (cdr u)
17988 list "\n")
17989 "\n")))
17990 (let ((org-mode-hook nil) (org-inhibit-startup t)
17991 (org-insert-mode-line-in-empty-file nil))
17992 (setq org-agenda-files list)
17993 (customize-save-variable 'org-agenda-files org-agenda-files))))
17995 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17996 "Read the list of agenda files from a file.
17997 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17998 filenames, used by `org-store-new-agenda-file-list' to write back
17999 un-expanded file names."
18000 (when (file-directory-p org-agenda-files)
18001 (error "`org-agenda-files' cannot be a single directory"))
18002 (when (stringp org-agenda-files)
18003 (with-temp-buffer
18004 (insert-file-contents org-agenda-files)
18005 (mapcar
18006 (lambda (f)
18007 (let ((e (expand-file-name (substitute-in-file-name f)
18008 org-directory)))
18009 (if pair-with-expansion
18010 (cons e f)
18011 e)))
18012 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18014 ;;;###autoload
18015 (defun org-cycle-agenda-files ()
18016 "Cycle through the files in `org-agenda-files'.
18017 If the current buffer visits an agenda file, find the next one in the list.
18018 If the current buffer does not, find the first agenda file."
18019 (interactive)
18020 (let* ((fs (org-agenda-files t))
18021 (files (append fs (list (car fs))))
18022 (tcf (if buffer-file-name (file-truename buffer-file-name)))
18023 file)
18024 (unless files (user-error "No agenda files"))
18025 (catch 'exit
18026 (while (setq file (pop files))
18027 (if (equal (file-truename file) tcf)
18028 (when (car files)
18029 (find-file (car files))
18030 (throw 'exit t))))
18031 (find-file (car fs)))
18032 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
18034 (defun org-agenda-file-to-front (&optional to-end)
18035 "Move/add the current file to the top of the agenda file list.
18036 If the file is not present in the list, it is added to the front. If it is
18037 present, it is moved there. With optional argument TO-END, add/move to the
18038 end of the list."
18039 (interactive "P")
18040 (let ((org-agenda-skip-unavailable-files nil)
18041 (file-alist (mapcar (lambda (x)
18042 (cons (file-truename x) x))
18043 (org-agenda-files t)))
18044 (ctf (file-truename
18045 (or buffer-file-name
18046 (user-error "Please save the current buffer to a file"))))
18047 x had)
18048 (setq x (assoc ctf file-alist) had x)
18050 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18051 (if to-end
18052 (setq file-alist (append (delq x file-alist) (list x)))
18053 (setq file-alist (cons x (delq x file-alist))))
18054 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18055 (org-install-agenda-files-menu)
18056 (message "File %s to %s of agenda file list"
18057 (if had "moved" "added") (if to-end "end" "front"))))
18059 (defun org-remove-file (&optional file)
18060 "Remove current file from the list of files in variable `org-agenda-files'.
18061 These are the files which are being checked for agenda entries.
18062 Optional argument FILE means use this file instead of the current."
18063 (interactive)
18064 (let* ((org-agenda-skip-unavailable-files nil)
18065 (file (or file buffer-file-name
18066 (user-error "Current buffer does not visit a file")))
18067 (true-file (file-truename file))
18068 (afile (abbreviate-file-name file))
18069 (files (delq nil (mapcar
18070 (lambda (x)
18071 (if (equal true-file
18072 (file-truename x))
18073 nil x))
18074 (org-agenda-files t)))))
18075 (if (not (= (length files) (length (org-agenda-files t))))
18076 (progn
18077 (org-store-new-agenda-file-list files)
18078 (org-install-agenda-files-menu)
18079 (message "Removed file: %s" afile))
18080 (message "File was not in list: %s (not removed)" afile))))
18082 (defun org-file-menu-entry (file)
18083 (vector file (list 'find-file file) t))
18085 (defun org-check-agenda-file (file)
18086 "Make sure FILE exists. If not, ask user what to do."
18087 (when (not (file-exists-p file))
18088 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18089 (abbreviate-file-name file))
18090 (let ((r (downcase (read-char-exclusive))))
18091 (cond
18092 ((equal r ?r)
18093 (org-remove-file file)
18094 (throw 'nextfile t))
18095 (t (error "Abort"))))))
18097 (defun org-get-agenda-file-buffer (file)
18098 "Get a buffer visiting FILE. If the buffer needs to be created, add
18099 it to the list of buffers which might be released later."
18100 (let ((buf (org-find-base-buffer-visiting file)))
18101 (if buf
18102 buf ; just return it
18103 ;; Make a new buffer and remember it
18104 (setq buf (find-file-noselect file))
18105 (if buf (push buf org-agenda-new-buffers))
18106 buf)))
18108 (defun org-release-buffers (blist)
18109 "Release all buffers in list, asking the user for confirmation when needed.
18110 When a buffer is unmodified, it is just killed. When modified, it is saved
18111 \(if the user agrees) and then killed."
18112 (let (buf file)
18113 (while (setq buf (pop blist))
18114 (setq file (buffer-file-name buf))
18115 (when (and (buffer-modified-p buf)
18116 file
18117 (y-or-n-p (format "Save file %s? " file)))
18118 (with-current-buffer buf (save-buffer)))
18119 (kill-buffer buf))))
18121 (defun org-agenda-prepare-buffers (files)
18122 "Create buffers for all agenda files, protect archived trees and comments."
18123 (interactive)
18124 (let ((pa '(:org-archived t))
18125 (pc '(:org-comment t))
18126 (pall '(:org-archived t :org-comment t))
18127 (inhibit-read-only t)
18128 (org-inhibit-startup org-agenda-inhibit-startup)
18129 (rea (concat ":" org-archive-tag ":"))
18130 file re pos)
18131 (setq org-tag-alist-for-agenda nil
18132 org-tag-groups-alist-for-agenda nil)
18133 (save-excursion
18134 (save-restriction
18135 (while (setq file (pop files))
18136 (catch 'nextfile
18137 (if (bufferp file)
18138 (set-buffer file)
18139 (org-check-agenda-file file)
18140 (set-buffer (org-get-agenda-file-buffer file)))
18141 (widen)
18142 (org-set-regexps-and-options-for-tags)
18143 (setq pos (point))
18144 (goto-char (point-min))
18145 (let ((case-fold-search t))
18146 (when (search-forward "#+setupfile" nil t)
18147 ;; Don't set all regexps and options systematically as
18148 ;; this is only run for setting agenda tags from setup
18149 ;; file
18150 (org-set-regexps-and-options)))
18151 (or (memq 'category org-agenda-ignore-drawer-properties)
18152 (org-refresh-category-properties))
18153 (or (memq 'effort org-agenda-ignore-drawer-properties)
18154 (org-refresh-properties org-effort-property 'org-effort))
18155 (or (memq 'appt org-agenda-ignore-drawer-properties)
18156 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18157 (setq org-todo-keywords-for-agenda
18158 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18159 (setq org-done-keywords-for-agenda
18160 (append org-done-keywords-for-agenda org-done-keywords))
18161 (setq org-todo-keyword-alist-for-agenda
18162 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18163 (setq org-drawers-for-agenda
18164 (append org-drawers-for-agenda org-drawers))
18165 (setq org-tag-alist-for-agenda
18166 (org-uniquify
18167 (append org-tag-alist-for-agenda
18168 org-tag-alist
18169 org-tag-persistent-alist)))
18170 (if org-group-tags
18171 (setq org-tag-groups-alist-for-agenda
18172 (org-uniquify-alist
18173 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18174 (org-with-silent-modifications
18175 (save-excursion
18176 (remove-text-properties (point-min) (point-max) pall)
18177 (when org-agenda-skip-archived-trees
18178 (goto-char (point-min))
18179 (while (re-search-forward rea nil t)
18180 (if (org-at-heading-p t)
18181 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18182 (goto-char (point-min))
18183 (setq re (format org-heading-keyword-regexp-format
18184 org-comment-string))
18185 (while (re-search-forward re nil t)
18186 (add-text-properties
18187 (match-beginning 0) (org-end-of-subtree t) pc))))
18188 (goto-char pos)))))
18189 (setq org-todo-keywords-for-agenda
18190 (org-uniquify org-todo-keywords-for-agenda))
18191 (setq org-todo-keyword-alist-for-agenda
18192 (org-uniquify org-todo-keyword-alist-for-agenda))))
18195 ;;;; CDLaTeX minor mode
18197 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18198 "Keymap for the minor `org-cdlatex-mode'.")
18200 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18201 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18202 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18203 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18204 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
18206 (defvar org-cdlatex-texmathp-advice-is-done nil
18207 "Flag remembering if we have applied the advice to texmathp already.")
18209 (define-minor-mode org-cdlatex-mode
18210 "Toggle the minor `org-cdlatex-mode'.
18211 This mode supports entering LaTeX environment and math in LaTeX fragments
18212 in Org-mode.
18213 \\{org-cdlatex-mode-map}"
18214 nil " OCDL" nil
18215 (when org-cdlatex-mode
18216 (require 'cdlatex)
18217 (run-hooks 'cdlatex-mode-hook)
18218 (cdlatex-compute-tables))
18219 (unless org-cdlatex-texmathp-advice-is-done
18220 (setq org-cdlatex-texmathp-advice-is-done t)
18221 (defadvice texmathp (around org-math-always-on activate)
18222 "Always return t in org-mode buffers.
18223 This is because we want to insert math symbols without dollars even outside
18224 the LaTeX math segments. If Orgmode thinks that point is actually inside
18225 an embedded LaTeX fragment, let texmathp do its job.
18226 \\[org-cdlatex-mode-map]"
18227 (interactive)
18228 (let (p)
18229 (cond
18230 ((not (derived-mode-p 'org-mode)) ad-do-it)
18231 ((eq this-command 'cdlatex-math-symbol)
18232 (setq ad-return-value t
18233 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18235 (let ((p (org-inside-LaTeX-fragment-p)))
18236 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18237 (setq ad-return-value t
18238 texmathp-why '("Org-mode embedded math" . 0))
18239 (if p ad-do-it)))))))))
18241 (defun turn-on-org-cdlatex ()
18242 "Unconditionally turn on `org-cdlatex-mode'."
18243 (org-cdlatex-mode 1))
18245 (defun org-try-cdlatex-tab ()
18246 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18247 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18248 - inside a LaTeX fragment, or
18249 - after the first word in a line, where an abbreviation expansion could
18250 insert a LaTeX environment."
18251 (when org-cdlatex-mode
18252 (cond
18253 ;; Before any word on the line: No expansion possible.
18254 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18255 ;; Just after first word on the line: Expand it. Make sure it
18256 ;; cannot happen on headlines, though.
18257 ((save-excursion
18258 (skip-chars-backward "a-zA-Z0-9*")
18259 (skip-chars-backward " \t")
18260 (and (bolp) (not (org-at-heading-p))))
18261 (cdlatex-tab) t)
18262 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18264 (defun org-cdlatex-underscore-caret (&optional arg)
18265 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18266 Revert to the normal definition outside of these fragments."
18267 (interactive "P")
18268 (if (org-inside-LaTeX-fragment-p)
18269 (call-interactively 'cdlatex-sub-superscript)
18270 (let (org-cdlatex-mode)
18271 (call-interactively (key-binding (vector last-input-event))))))
18273 (defun org-cdlatex-math-modify (&optional arg)
18274 "Execute `cdlatex-math-modify' in LaTeX fragments.
18275 Revert to the normal definition outside of these fragments."
18276 (interactive "P")
18277 (if (org-inside-LaTeX-fragment-p)
18278 (call-interactively 'cdlatex-math-modify)
18279 (let (org-cdlatex-mode)
18280 (call-interactively (key-binding (vector last-input-event))))))
18284 ;;;; LaTeX fragments
18286 (defvar org-latex-regexps
18287 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
18288 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
18289 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
18290 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18291 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18292 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
18293 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
18294 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
18295 "Regular expressions for matching embedded LaTeX.")
18297 (defun org-inside-LaTeX-fragment-p ()
18298 "Test if point is inside a LaTeX fragment.
18299 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18300 sequence appearing also before point.
18301 Even though the matchers for math are configurable, this function assumes
18302 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18303 delimiters are skipped when they have been removed by customization.
18304 The return value is nil, or a cons cell with the delimiter and the
18305 position of this delimiter.
18307 This function does a reasonably good job, but can locally be fooled by
18308 for example currency specifications. For example it will assume being in
18309 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18310 fragments that are properly closed, but during editing, we have to live
18311 with the uncertainty caused by missing closing delimiters. This function
18312 looks only before point, not after."
18313 (catch 'exit
18314 (let ((pos (point))
18315 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18316 (lim (progn
18317 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18318 (point)))
18319 dd-on str (start 0) m re)
18320 (goto-char pos)
18321 (when dodollar
18322 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18323 re (nth 1 (assoc "$" org-latex-regexps)))
18324 (while (string-match re str start)
18325 (cond
18326 ((= (match-end 0) (length str))
18327 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18328 ((= (match-end 0) (- (length str) 5))
18329 (throw 'exit nil))
18330 (t (setq start (match-end 0))))))
18331 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18332 (goto-char pos)
18333 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18334 (and (match-beginning 2) (throw 'exit nil))
18335 ;; count $$
18336 (while (re-search-backward "\\$\\$" lim t)
18337 (setq dd-on (not dd-on)))
18338 (goto-char pos)
18339 (if dd-on (cons "$$" m))))))
18341 (defun org-inside-latex-macro-p ()
18342 "Is point inside a LaTeX macro or its arguments?"
18343 (save-match-data
18344 (org-in-regexp
18345 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18347 (defvar org-latex-fragment-image-overlays nil
18348 "List of overlays carrying the images of latex fragments.")
18349 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18351 (defun org-remove-latex-fragment-image-overlays ()
18352 "Remove all overlays with LaTeX fragment images in current buffer."
18353 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18354 (setq org-latex-fragment-image-overlays nil))
18356 (defun org-preview-latex-fragment (&optional subtree)
18357 "Preview the LaTeX fragment at point, or all locally or globally.
18358 If the cursor is in a LaTeX fragment, create the image and overlay
18359 it over the source code. If there is no fragment at point, display
18360 all fragments in the current text, from one headline to the next. With
18361 prefix SUBTREE, display all fragments in the current subtree. With a
18362 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18363 the cursor is before the first headline,
18364 display all fragments in the buffer.
18365 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18366 (interactive "P")
18367 (unless buffer-file-name
18368 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18369 (when (display-graphic-p)
18370 (org-remove-latex-fragment-image-overlays)
18371 (save-excursion
18372 (save-restriction
18373 (let (beg end at msg)
18374 (cond
18375 ((or (equal subtree '(16))
18376 (not (save-excursion
18377 (re-search-backward org-outline-regexp-bol nil t))))
18378 (setq beg (point-min) end (point-max)
18379 msg "Creating images for buffer...%s"))
18380 ((equal subtree '(4))
18381 (org-back-to-heading)
18382 (setq beg (point) end (org-end-of-subtree t)
18383 msg "Creating images for subtree...%s"))
18385 (if (setq at (org-inside-LaTeX-fragment-p))
18386 (goto-char (max (point-min) (- (cdr at) 2)))
18387 (org-back-to-heading))
18388 (setq beg (point) end (progn (outline-next-heading) (point))
18389 msg (if at "Creating image...%s"
18390 "Creating images for entry...%s"))))
18391 (message msg "")
18392 (narrow-to-region beg end)
18393 (goto-char beg)
18394 (org-format-latex
18395 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18396 (file-name-nondirectory
18397 buffer-file-name)))
18398 default-directory 'overlays msg at 'forbuffer
18399 org-latex-create-formula-image-program)
18400 (message msg "done. Use `C-c C-c' to remove images."))))))
18402 (defun org-format-latex (prefix &optional dir overlays msg at
18403 forbuffer processing-type)
18404 "Replace LaTeX fragments with links to an image, and produce images.
18405 Some of the options can be changed using the variable
18406 `org-format-latex-options'."
18407 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18408 (let* ((prefixnodir (file-name-nondirectory prefix))
18409 (absprefix (expand-file-name prefix dir))
18410 (todir (file-name-directory absprefix))
18411 (opt org-format-latex-options)
18412 (optnew org-format-latex-options)
18413 (matchers (plist-get opt :matchers))
18414 (re-list org-latex-regexps)
18415 (cnt 0) txt hash link beg end re e checkdir
18416 string
18417 m n block-type block linkfile movefile ov)
18418 ;; Check the different regular expressions
18419 (while (setq e (pop re-list))
18420 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18421 block (if block-type "\n\n" ""))
18422 (when (member m matchers)
18423 (goto-char (point-min))
18424 (while (re-search-forward re nil t)
18425 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18426 (or (not overlays)
18427 (not (eq (get-char-property (match-beginning n)
18428 'org-overlay-type)
18429 'org-latex-overlay))))
18430 (cond
18431 ((eq processing-type 'verbatim))
18432 ((eq processing-type 'mathjax)
18433 ;; Prepare for MathJax processing.
18434 (setq string (match-string n))
18435 (when (member m '("$" "$1"))
18436 (save-excursion
18437 (delete-region (match-beginning n) (match-end n))
18438 (goto-char (match-beginning n))
18439 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18440 ((or (eq processing-type 'dvipng)
18441 (eq processing-type 'imagemagick))
18442 ;; Process to an image.
18443 (setq txt (match-string n)
18444 beg (match-beginning n) end (match-end n)
18445 cnt (1+ cnt))
18446 (let ((face (face-at-point))
18447 (fg (plist-get opt :foreground))
18448 (bg (plist-get opt :background))
18449 ;; Ensure full list is printed.
18450 print-length print-level)
18451 (when forbuffer
18452 ;; Get the colors from the face at point.
18453 (goto-char beg)
18454 (when (eq fg 'auto)
18455 (setq fg (face-attribute face :foreground nil 'default)))
18456 (when (eq bg 'auto)
18457 (setq bg (face-attribute face :background nil 'default)))
18458 (setq optnew (copy-sequence opt))
18459 (plist-put optnew :foreground fg)
18460 (plist-put optnew :background bg))
18461 (setq hash (sha1 (prin1-to-string
18462 (list org-format-latex-header
18463 org-latex-default-packages-alist
18464 org-latex-packages-alist
18465 org-format-latex-options
18466 forbuffer txt fg bg)))
18467 linkfile (format "%s_%s.png" prefix hash)
18468 movefile (format "%s_%s.png" absprefix hash)))
18469 (setq link (concat block "[[file:" linkfile "]]" block))
18470 (if msg (message msg cnt))
18471 (goto-char beg)
18472 (unless checkdir ; Ensure the directory exists.
18473 (setq checkdir t)
18474 (or (file-directory-p todir) (make-directory todir t)))
18475 (unless (file-exists-p movefile)
18476 (org-create-formula-image
18477 txt movefile optnew forbuffer processing-type))
18478 (if overlays
18479 (progn
18480 (mapc (lambda (o)
18481 (if (eq (overlay-get o 'org-overlay-type)
18482 'org-latex-overlay)
18483 (delete-overlay o)))
18484 (overlays-in beg end))
18485 (setq ov (make-overlay beg end))
18486 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18487 (if (featurep 'xemacs)
18488 (progn
18489 (overlay-put ov 'invisible t)
18490 (overlay-put
18491 ov 'end-glyph
18492 (make-glyph (vector 'png :file movefile))))
18493 (overlay-put
18494 ov 'display
18495 (list 'image :type 'png :file movefile :ascent 'center)))
18496 (push ov org-latex-fragment-image-overlays)
18497 (goto-char end))
18498 (delete-region beg end)
18499 (insert (org-add-props link
18500 (list 'org-latex-src
18501 (replace-regexp-in-string
18502 "\"" "" txt)
18503 'org-latex-src-embed-type
18504 (if block-type 'paragraph 'character))))))
18505 ((eq processing-type 'mathml)
18506 ;; Process to MathML
18507 (unless (save-match-data (org-format-latex-mathml-available-p))
18508 (user-error "LaTeX to MathML converter not configured"))
18509 (setq txt (match-string n)
18510 beg (match-beginning n) end (match-end n)
18511 cnt (1+ cnt))
18512 (if msg (message msg cnt))
18513 (goto-char beg)
18514 (delete-region beg end)
18515 (insert (org-format-latex-as-mathml
18516 txt block-type prefix dir)))
18518 (error "Unknown conversion type %s for LaTeX fragments"
18519 processing-type)))))))))
18521 (defun org-create-math-formula (latex-frag &optional mathml-file)
18522 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18523 Use `org-latex-to-mathml-convert-command'. If the conversion is
18524 sucessful, return the portion between \"<math...> </math>\"
18525 elements otherwise return nil. When MATHML-FILE is specified,
18526 write the results in to that file. When invoked as an
18527 interactive command, prompt for LATEX-FRAG, with initial value
18528 set to the current active region and echo the results for user
18529 inspection."
18530 (interactive (list (let ((frag (when (org-region-active-p)
18531 (buffer-substring-no-properties
18532 (region-beginning) (region-end)))))
18533 (read-string "LaTeX Fragment: " frag nil frag))))
18534 (unless latex-frag (error "Invalid LaTeX fragment"))
18535 (let* ((tmp-in-file (file-relative-name
18536 (make-temp-name (expand-file-name "ltxmathml-in"))))
18537 (ignore (write-region latex-frag nil tmp-in-file))
18538 (tmp-out-file (file-relative-name
18539 (make-temp-name (expand-file-name "ltxmathml-out"))))
18540 (cmd (format-spec
18541 org-latex-to-mathml-convert-command
18542 `((?j . ,(shell-quote-argument
18543 (expand-file-name org-latex-to-mathml-jar-file)))
18544 (?I . ,(shell-quote-argument tmp-in-file))
18545 (?o . ,(shell-quote-argument tmp-out-file)))))
18546 mathml shell-command-output)
18547 (when (org-called-interactively-p 'any)
18548 (unless (org-format-latex-mathml-available-p)
18549 (user-error "LaTeX to MathML converter not configured")))
18550 (message "Running %s" cmd)
18551 (setq shell-command-output (shell-command-to-string cmd))
18552 (setq mathml
18553 (when (file-readable-p tmp-out-file)
18554 (with-current-buffer (find-file-noselect tmp-out-file t)
18555 (goto-char (point-min))
18556 (when (re-search-forward
18557 (concat
18558 (regexp-quote
18559 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18560 "\\(.\\|\n\\)*"
18561 (regexp-quote "</math>")) nil t)
18562 (prog1 (match-string 0) (kill-buffer))))))
18563 (cond
18564 (mathml
18565 (setq mathml
18566 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18567 (when mathml-file
18568 (write-region mathml nil mathml-file))
18569 (when (org-called-interactively-p 'any)
18570 (message mathml)))
18571 ((message "LaTeX to MathML conversion failed")
18572 (message shell-command-output)))
18573 (delete-file tmp-in-file)
18574 (when (file-exists-p tmp-out-file)
18575 (delete-file tmp-out-file))
18576 mathml))
18578 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18579 prefix &optional dir)
18580 "Use `org-create-math-formula' but check local cache first."
18581 (let* ((absprefix (expand-file-name prefix dir))
18582 (print-length nil) (print-level nil)
18583 (formula-id (concat
18584 "formula-"
18585 (sha1
18586 (prin1-to-string
18587 (list latex-frag
18588 org-latex-to-mathml-convert-command)))))
18589 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18590 (formula-cache-dir (file-name-directory formula-cache)))
18592 (unless (file-directory-p formula-cache-dir)
18593 (make-directory formula-cache-dir t))
18595 (unless (file-exists-p formula-cache)
18596 (org-create-math-formula latex-frag formula-cache))
18598 (if (file-exists-p formula-cache)
18599 ;; Successful conversion. Return the link to MathML file.
18600 (org-add-props
18601 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18602 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18603 'org-latex-src-embed-type (if latex-frag-type
18604 'paragraph 'character)))
18605 ;; Failed conversion. Return the LaTeX fragment verbatim
18606 latex-frag)))
18608 (defun org-create-formula-image (string tofile options buffer &optional type)
18609 "Create an image from LaTeX source using dvipng or convert.
18610 This function calls either `org-create-formula-image-with-dvipng'
18611 or `org-create-formula-image-with-imagemagick' depending on the
18612 value of `org-latex-create-formula-image-program' or on the value
18613 of the optional TYPE variable.
18615 Note: ultimately these two function should be combined as they
18616 share a good deal of logic."
18617 (org-check-external-command
18618 "latex" "needed to convert LaTeX fragments to images")
18619 (funcall
18620 (case (or type org-latex-create-formula-image-program)
18621 ('dvipng
18622 (org-check-external-command
18623 "dvipng" "needed to convert LaTeX fragments to images")
18624 #'org-create-formula-image-with-dvipng)
18625 ('imagemagick
18626 (org-check-external-command
18627 "convert" "you need to install imagemagick")
18628 #'org-create-formula-image-with-imagemagick)
18629 (t (error
18630 "Invalid value of `org-latex-create-formula-image-program'")))
18631 string tofile options buffer))
18633 (declare-function org-export-get-backend "ox" (name))
18634 (declare-function org-export--get-global-options "ox" (&optional backend))
18635 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18636 (declare-function org-latex-guess-inputenc "ox-latex" (header))
18637 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
18638 (defun org-create-formula--latex-header ()
18639 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18640 (let ((info (org-combine-plists (org-export--get-global-options
18641 (org-export-get-backend 'latex))
18642 (org-export--get-inbuffer-options
18643 (org-export-get-backend 'latex)))))
18644 (org-latex-guess-babel-language
18645 (org-latex-guess-inputenc
18646 (org-splice-latex-header
18647 org-format-latex-header
18648 org-latex-default-packages-alist
18649 org-latex-packages-alist t
18650 (plist-get info :latex-header)))
18651 info)))
18653 ;; This function borrows from Ganesh Swami's latex2png.el
18654 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18655 "This calls dvipng."
18656 (require 'ox-latex)
18657 (let* ((tmpdir (if (featurep 'xemacs)
18658 (temp-directory)
18659 temporary-file-directory))
18660 (texfilebase (make-temp-name
18661 (expand-file-name "orgtex" tmpdir)))
18662 (texfile (concat texfilebase ".tex"))
18663 (dvifile (concat texfilebase ".dvi"))
18664 (pngfile (concat texfilebase ".png"))
18665 (fnh (if (featurep 'xemacs)
18666 (font-height (face-font 'default))
18667 (face-attribute 'default :height nil)))
18668 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18669 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18670 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18671 "Black"))
18672 (bg (or (plist-get options (if buffer :background :html-background))
18673 "Transparent")))
18674 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18675 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18676 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18677 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18678 (let ((latex-header (org-create-formula--latex-header)))
18679 (with-temp-file texfile
18680 (insert latex-header)
18681 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18682 (let ((dir default-directory))
18683 (condition-case nil
18684 (progn
18685 (cd tmpdir)
18686 (call-process "latex" nil nil nil texfile))
18687 (error nil))
18688 (cd dir))
18689 (if (not (file-exists-p dvifile))
18690 (progn (message "Failed to create dvi file from %s" texfile) nil)
18691 (condition-case nil
18692 (if (featurep 'xemacs)
18693 (call-process "dvipng" nil nil nil
18694 "-fg" fg "-bg" bg
18695 "-T" "tight"
18696 "-o" pngfile
18697 dvifile)
18698 (call-process "dvipng" nil nil nil
18699 "-fg" fg "-bg" bg
18700 "-D" dpi
18701 ;;"-x" scale "-y" scale
18702 "-T" "tight"
18703 "-o" pngfile
18704 dvifile))
18705 (error nil))
18706 (if (not (file-exists-p pngfile))
18707 (if org-format-latex-signal-error
18708 (error "Failed to create png file from %s" texfile)
18709 (message "Failed to create png file from %s" texfile)
18710 nil)
18711 ;; Use the requested file name and clean up
18712 (copy-file pngfile tofile 'replace)
18713 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18714 (if (file-exists-p (concat texfilebase e))
18715 (delete-file (concat texfilebase e))))
18716 pngfile))))
18718 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18719 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18720 "This calls convert, which is included into imagemagick."
18721 (require 'ox-latex)
18722 (let* ((tmpdir (if (featurep 'xemacs)
18723 (temp-directory)
18724 temporary-file-directory))
18725 (texfilebase (make-temp-name
18726 (expand-file-name "orgtex" tmpdir)))
18727 (texfile (concat texfilebase ".tex"))
18728 (pdffile (concat texfilebase ".pdf"))
18729 (pngfile (concat texfilebase ".png"))
18730 (fnh (if (featurep 'xemacs)
18731 (font-height (face-font 'default))
18732 (face-attribute 'default :height nil)))
18733 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18734 (dpi (number-to-string (* scale (floor (if buffer fnh 120.)))))
18735 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18736 "black"))
18737 (bg (or (plist-get options (if buffer :background :html-background))
18738 "white")))
18739 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18740 (setq fg (org-latex-color-format fg)))
18741 (if (eq bg 'default) (setq bg (org-latex-color :background))
18742 (setq bg (org-latex-color-format
18743 (if (string= bg "Transparent") "white" bg))))
18744 (let ((latex-header (org-create-formula--latex-header)))
18745 (with-temp-file texfile
18746 (insert latex-header)
18747 (insert "\n\\begin{document}\n"
18748 "\\definecolor{fg}{rgb}{" fg "}\n"
18749 "\\definecolor{bg}{rgb}{" bg "}\n"
18750 "\n\\pagecolor{bg}\n"
18751 "\n{\\color{fg}\n"
18752 string
18753 "\n}\n"
18754 "\n\\end{document}\n")))
18755 (org-latex-compile texfile t)
18756 (if (not (file-exists-p pdffile))
18757 (progn (message "Failed to create pdf file from %s" texfile) nil)
18758 (condition-case nil
18759 (if (featurep 'xemacs)
18760 (call-process "convert" nil nil nil
18761 "-density" "96"
18762 "-trim"
18763 "-antialias"
18764 pdffile
18765 "-quality" "100"
18766 ;; "-sharpen" "0x1.0"
18767 pngfile)
18768 (call-process "convert" nil nil nil
18769 "-density" dpi
18770 "-trim"
18771 "-antialias"
18772 pdffile
18773 "-quality" "100"
18774 ;; "-sharpen" "0x1.0"
18775 pngfile))
18776 (error nil))
18777 (if (not (file-exists-p pngfile))
18778 (if org-format-latex-signal-error
18779 (error "Failed to create png file from %s" texfile)
18780 (message "Failed to create png file from %s" texfile)
18781 nil)
18782 ;; Use the requested file name and clean up
18783 (copy-file pngfile tofile 'replace)
18784 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18785 (if (file-exists-p (concat texfilebase e))
18786 (delete-file (concat texfilebase e))))
18787 pngfile))))
18789 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18790 "Fill a LaTeX header template TPL.
18791 In the template, the following place holders will be recognized:
18793 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18794 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18795 [PACKAGES] \\usepackage statements for PKG
18796 [NO-PACKAGES] do not include PKG
18797 [EXTRA] the string EXTRA
18798 [NO-EXTRA] do not include EXTRA
18800 For backward compatibility, if both the positive and the negative place
18801 holder is missing, the positive one (without the \"NO-\") will be
18802 assumed to be present at the end of the template.
18803 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18804 EXTRA is a string.
18805 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18806 (let (rpl (end ""))
18807 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18808 (setq rpl (if (or (match-end 1) (not def-pkg))
18809 "" (org-latex-packages-to-string def-pkg snippets-p t))
18810 tpl (replace-match rpl t t tpl))
18811 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18813 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18814 (setq rpl (if (or (match-end 1) (not pkg))
18815 "" (org-latex-packages-to-string pkg snippets-p t))
18816 tpl (replace-match rpl t t tpl))
18817 (if pkg (setq end
18818 (concat end "\n"
18819 (org-latex-packages-to-string pkg snippets-p)))))
18821 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18822 (setq rpl (if (or (match-end 1) (not extra))
18823 "" (concat extra "\n"))
18824 tpl (replace-match rpl t t tpl))
18825 (if (and extra (string-match "\\S-" extra))
18826 (setq end (concat end "\n" extra))))
18828 (if (string-match "\\S-" end)
18829 (concat tpl "\n" end)
18830 tpl)))
18832 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18833 "Turn an alist of packages into a string with the \\usepackage macros."
18834 (setq pkg (mapconcat (lambda(p)
18835 (cond
18836 ((stringp p) p)
18837 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18838 (format "%% Package %s omitted" (cadr p)))
18839 ((equal "" (car p))
18840 (format "\\usepackage{%s}" (cadr p)))
18842 (format "\\usepackage[%s]{%s}"
18843 (car p) (cadr p)))))
18845 "\n"))
18846 (if newline (concat pkg "\n") pkg))
18848 (defun org-dvipng-color (attr)
18849 "Return a RGB color specification for dvipng."
18850 (apply 'format "rgb %s %s %s"
18851 (mapcar 'org-normalize-color
18852 (if (featurep 'xemacs)
18853 (color-rgb-components
18854 (face-property 'default
18855 (cond ((eq attr :foreground) 'foreground)
18856 ((eq attr :background) 'background))))
18857 (color-values (face-attribute 'default attr nil))))))
18859 (defun org-dvipng-color-format (color-name)
18860 "Convert COLOR-NAME to a RGB color value for dvipng."
18861 (apply 'format "rgb %s %s %s"
18862 (mapcar 'org-normalize-color
18863 (color-values color-name))))
18865 (defun org-latex-color (attr)
18866 "Return a RGB color for the LaTeX color package."
18867 (apply 'format "%s,%s,%s"
18868 (mapcar 'org-normalize-color
18869 (if (featurep 'xemacs)
18870 (color-rgb-components
18871 (face-property 'default
18872 (cond ((eq attr :foreground) 'foreground)
18873 ((eq attr :background) 'background))))
18874 (color-values (face-attribute 'default attr nil))))))
18876 (defun org-latex-color-format (color-name)
18877 "Convert COLOR-NAME to a RGB color value."
18878 (apply 'format "%s,%s,%s"
18879 (mapcar 'org-normalize-color
18880 (color-values color-name))))
18882 (defun org-normalize-color (value)
18883 "Return string to be used as color value for an RGB component."
18884 (format "%g" (/ value 65535.0)))
18888 ;; Image display
18890 (defvar org-inline-image-overlays nil)
18891 (make-variable-buffer-local 'org-inline-image-overlays)
18893 (defun org-toggle-inline-images (&optional include-linked)
18894 "Toggle the display of inline images.
18895 INCLUDE-LINKED is passed to `org-display-inline-images'."
18896 (interactive "P")
18897 (if org-inline-image-overlays
18898 (progn
18899 (org-remove-inline-images)
18900 (message "Inline image display turned off"))
18901 (org-display-inline-images include-linked)
18902 (if (and (org-called-interactively-p)
18903 org-inline-image-overlays)
18904 (message "%d images displayed inline"
18905 (length org-inline-image-overlays))
18906 (message "No images to display inline"))))
18908 (defun org-redisplay-inline-images ()
18909 "Refresh the display of inline images."
18910 (interactive)
18911 (if (not org-inline-image-overlays)
18912 (org-toggle-inline-images)
18913 (org-toggle-inline-images)
18914 (org-toggle-inline-images)))
18916 (defun org-display-inline-images (&optional include-linked refresh beg end)
18917 "Display inline images.
18918 Normally only links without a description part are inlined, because this
18919 is how it will work for export. When INCLUDE-LINKED is set, also links
18920 with a description part will be inlined. This can be nice for a quick
18921 look at those images, but it does not reflect what exported files will look
18922 like.
18923 When REFRESH is set, refresh existing images between BEG and END.
18924 This will create new image displays only if necessary.
18925 BEG and END default to the buffer boundaries."
18926 (interactive "P")
18927 (when (display-graphic-p)
18928 (unless refresh
18929 (org-remove-inline-images)
18930 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18931 (save-excursion
18932 (save-restriction
18933 (widen)
18934 (setq beg (or beg (point-min)) end (or end (point-max)))
18935 (goto-char beg)
18936 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18937 (substring (org-image-file-name-regexp) 0 -2)
18938 "\\)\\]" (if include-linked "" "\\]")))
18939 (case-fold-search t)
18940 old file ov img type attrwidth width)
18941 (while (re-search-forward re end t)
18942 (setq old (get-char-property-and-overlay (match-beginning 1)
18943 'org-image-overlay)
18944 file (expand-file-name
18945 (concat (or (match-string 3) "") (match-string 4))))
18946 (when (image-type-available-p 'imagemagick)
18947 (setq attrwidth (if (or (listp org-image-actual-width)
18948 (null org-image-actual-width))
18949 (save-excursion
18950 (save-match-data
18951 (when (re-search-backward
18952 "#\\+attr.*:width[ \t]+\\([^ ]+\\)"
18953 (save-excursion
18954 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18955 (string-to-number (match-string 1))))))
18956 width (cond ((eq org-image-actual-width t) nil)
18957 ((null org-image-actual-width) attrwidth)
18958 ((numberp org-image-actual-width)
18959 org-image-actual-width)
18960 ((listp org-image-actual-width)
18961 (or attrwidth (car org-image-actual-width))))
18962 type (if width 'imagemagick)))
18963 (when (file-exists-p file)
18964 (if (and (car-safe old) refresh)
18965 (image-refresh (overlay-get (cdr old) 'display))
18966 (setq img (save-match-data (create-image file type nil :width width)))
18967 (when img
18968 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18969 (overlay-put ov 'display img)
18970 (overlay-put ov 'face 'default)
18971 (overlay-put ov 'org-image-overlay t)
18972 (overlay-put ov 'modification-hooks
18973 (list 'org-display-inline-remove-overlay))
18974 (push ov org-inline-image-overlays))))))))))
18976 (define-obsolete-function-alias
18977 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18979 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18980 "Remove inline-display overlay if a corresponding region is modified."
18981 (let ((inhibit-modification-hooks t))
18982 (when (and ov after)
18983 (delete ov org-inline-image-overlays)
18984 (delete-overlay ov))))
18986 (defun org-remove-inline-images ()
18987 "Remove inline display of images."
18988 (interactive)
18989 (mapc 'delete-overlay org-inline-image-overlays)
18990 (setq org-inline-image-overlays nil))
18992 ;;;; Key bindings
18994 ;; Outline functions from `outline-mode-prefix-map'
18995 ;; that can be remapped in Org:
18996 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18997 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18998 (define-key org-mode-map [remap outline-forward-same-level]
18999 'org-forward-heading-same-level)
19000 (define-key org-mode-map [remap outline-backward-same-level]
19001 'org-backward-heading-same-level)
19002 (define-key org-mode-map [remap show-branches]
19003 'org-kill-note-or-show-branches)
19004 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19005 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19006 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19008 ;; Outline functions from `outline-mode-prefix-map' that can not
19009 ;; be remapped in Org:
19011 ;; - the column "key binding" shows whether the Outline function is still
19012 ;; available in Org mode on the same key that it has been bound to in
19013 ;; Outline mode:
19014 ;; - "overridden": key used for a different functionality in Org mode
19015 ;; - else: key still bound to the same Outline function in Org mode
19017 ;; | Outline function | key binding | Org replacement |
19018 ;; |------------------------------------+-------------+-----------------------|
19019 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
19020 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
19021 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19022 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19023 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19024 ;; | `show-entry' | overridden | no replacement |
19025 ;; | `show-children' | `C-c C-i' | visibility cycling |
19026 ;; | `show-branches' | `C-c C-k' | still same function |
19027 ;; | `show-subtree' | overridden | visibility cycling |
19028 ;; | `show-all' | overridden | no replacement |
19029 ;; | `hide-subtree' | overridden | visibility cycling |
19030 ;; | `hide-body' | overridden | no replacement |
19031 ;; | `hide-entry' | overridden | visibility cycling |
19032 ;; | `hide-leaves' | overridden | no replacement |
19033 ;; | `hide-sublevels' | overridden | no replacement |
19034 ;; | `hide-other' | overridden | no replacement |
19036 ;; Make `C-c C-x' a prefix key
19037 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19039 ;; TAB key with modifiers
19040 (org-defkey org-mode-map "\C-i" 'org-cycle)
19041 (org-defkey org-mode-map [(tab)] 'org-cycle)
19042 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19043 (org-defkey org-mode-map "\M-\t" 'pcomplete)
19044 ;; The following line is necessary under Suse GNU/Linux
19045 (unless (featurep 'xemacs)
19046 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
19047 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19048 (define-key org-mode-map [backtab] 'org-shifttab)
19050 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19051 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19052 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19054 ;; Cursor keys with modifiers
19055 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19056 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19057 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19058 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19060 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19061 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19062 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19063 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19065 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19066 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19067 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19068 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19070 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19071 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19072 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19073 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19075 ;; Babel keys
19076 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19077 (mapc (lambda (pair)
19078 (define-key org-babel-map (car pair) (cdr pair)))
19079 org-babel-key-bindings)
19081 ;;; Extra keys for tty access.
19082 ;; We only set them when really needed because otherwise the
19083 ;; menus don't show the simple keys
19085 (when (or org-use-extra-keys
19086 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19087 (not window-system))
19088 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19089 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19090 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19091 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19092 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19093 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19094 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19095 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19096 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19097 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19098 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19099 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19100 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19101 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19102 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19103 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19104 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19105 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19106 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19107 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19108 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19109 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19110 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
19111 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19112 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19113 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19114 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19115 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19117 ;; All the other keys
19119 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
19120 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19121 (if (boundp 'narrow-map)
19122 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19123 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19124 (if (boundp 'narrow-map)
19125 (org-defkey narrow-map "b" 'org-narrow-to-block)
19126 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19127 (if (boundp 'narrow-map)
19128 (org-defkey narrow-map "e" 'org-narrow-to-element)
19129 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19130 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19131 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19132 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19133 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19134 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19135 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19136 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19137 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19138 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19139 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19140 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
19141 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19142 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19143 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19144 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19145 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19146 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19147 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19148 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19149 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19150 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19151 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19152 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19153 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19154 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19155 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19156 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19157 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19158 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19159 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19160 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19161 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19162 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19163 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19164 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19165 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19166 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19167 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19168 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19169 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19170 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19171 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19172 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19173 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19174 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19175 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19176 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19177 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19178 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19179 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19180 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19181 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19182 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19183 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19184 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19185 (org-defkey org-mode-map "\C-c^" 'org-sort)
19186 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19187 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19188 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19189 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19190 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19191 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19192 (org-defkey org-mode-map "\C-m" 'org-return)
19193 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19194 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19195 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19196 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19197 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19198 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19199 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19200 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19201 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19202 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19203 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19204 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19205 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19206 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19207 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
19208 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19209 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19210 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19211 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19212 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19213 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19214 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19215 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19217 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19218 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19219 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19221 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19222 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19223 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19224 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19225 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19226 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19227 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19228 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19229 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19230 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19231 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
19232 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19233 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19234 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19235 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19236 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19237 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19238 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19239 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19240 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19241 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19242 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19243 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19245 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19246 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19247 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19248 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19249 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19251 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19253 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19255 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19256 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19258 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19261 (when (featurep 'xemacs)
19262 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19265 (defconst org-speed-commands-default
19267 ("Outline Navigation")
19268 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19269 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19270 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19271 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19272 ("F" . org-next-block)
19273 ("B" . org-previous-block)
19274 ("u" . (org-speed-move-safe 'outline-up-heading))
19275 ("j" . org-goto)
19276 ("g" . (org-refile t))
19277 ("Outline Visibility")
19278 ("c" . org-cycle)
19279 ("C" . org-shifttab)
19280 (" " . org-display-outline-path)
19281 ("s" . org-narrow-to-subtree)
19282 ("=" . org-columns)
19283 ("Outline Structure Editing")
19284 ("U" . org-shiftmetaup)
19285 ("D" . org-shiftmetadown)
19286 ("r" . org-metaright)
19287 ("l" . org-metaleft)
19288 ("R" . org-shiftmetaright)
19289 ("L" . org-shiftmetaleft)
19290 ("i" . (progn (forward-char 1) (call-interactively
19291 'org-insert-heading-respect-content)))
19292 ("^" . org-sort)
19293 ("w" . org-refile)
19294 ("a" . org-archive-subtree-default-with-confirmation)
19295 ("@" . org-mark-subtree)
19296 ("#" . org-toggle-comment)
19297 ("Clock Commands")
19298 ("I" . org-clock-in)
19299 ("O" . org-clock-out)
19300 ("Meta Data Editing")
19301 ("t" . org-todo)
19302 ("," . (org-priority))
19303 ("0" . (org-priority ?\ ))
19304 ("1" . (org-priority ?A))
19305 ("2" . (org-priority ?B))
19306 ("3" . (org-priority ?C))
19307 (":" . org-set-tags-command)
19308 ("e" . org-set-effort)
19309 ("E" . org-inc-effort)
19310 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19311 (org-entry-put (point) "APPT_WARNTIME" m)))
19312 ("Agenda Views etc")
19313 ("v" . org-agenda)
19314 ("/" . org-sparse-tree)
19315 ("Misc")
19316 ("o" . org-open-at-point)
19317 ("?" . org-speed-command-help)
19318 ("<" . (org-agenda-set-restriction-lock 'subtree))
19319 (">" . (org-agenda-remove-restriction-lock))
19321 "The default speed commands.")
19323 (defun org-print-speed-command (e)
19324 (if (> (length (car e)) 1)
19325 (progn
19326 (princ "\n")
19327 (princ (car e))
19328 (princ "\n")
19329 (princ (make-string (length (car e)) ?-))
19330 (princ "\n"))
19331 (princ (car e))
19332 (princ " ")
19333 (if (symbolp (cdr e))
19334 (princ (symbol-name (cdr e)))
19335 (prin1 (cdr e)))
19336 (princ "\n")))
19338 (defun org-speed-command-help ()
19339 "Show the available speed commands."
19340 (interactive)
19341 (if (not org-use-speed-commands)
19342 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19343 (with-output-to-temp-buffer "*Help*"
19344 (princ "User-defined Speed commands\n===========================\n")
19345 (mapc 'org-print-speed-command org-speed-commands-user)
19346 (princ "\n")
19347 (princ "Built-in Speed commands\n=======================\n")
19348 (mapc 'org-print-speed-command org-speed-commands-default))
19349 (with-current-buffer "*Help*"
19350 (setq truncate-lines t))))
19352 (defun org-speed-move-safe (cmd)
19353 "Execute CMD, but make sure that the cursor always ends up in a headline.
19354 If not, return to the original position and throw an error."
19355 (interactive)
19356 (let ((pos (point)))
19357 (call-interactively cmd)
19358 (unless (and (bolp) (org-at-heading-p))
19359 (goto-char pos)
19360 (error "Boundary reached while executing %s" cmd))))
19362 (defvar org-self-insert-command-undo-counter 0)
19364 (defvar org-table-auto-blank-field) ; defined in org-table.el
19365 (defvar org-speed-command nil)
19367 (define-obsolete-function-alias
19368 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19370 (defun org-speed-command-activate (keys)
19371 "Hook for activating single-letter speed commands.
19372 `org-speed-commands-default' specifies a minimal command set.
19373 Use `org-speed-commands-user' for further customization."
19374 (when (or (and (bolp) (looking-at org-outline-regexp))
19375 (and (functionp org-use-speed-commands)
19376 (funcall org-use-speed-commands)))
19377 (cdr (assoc keys (append org-speed-commands-user
19378 org-speed-commands-default)))))
19380 (define-obsolete-function-alias
19381 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19383 (defun org-babel-speed-command-activate (keys)
19384 "Hook for activating single-letter code block commands."
19385 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19386 (cdr (assoc keys org-babel-key-bindings))))
19388 (defcustom org-speed-command-hook
19389 '(org-speed-command-default-hook org-babel-speed-command-hook)
19390 "Hook for activating speed commands at strategic locations.
19391 Hook functions are called in sequence until a valid handler is
19392 found.
19394 Each hook takes a single argument, a user-pressed command key
19395 which is also a `self-insert-command' from the global map.
19397 Within the hook, examine the cursor position and the command key
19398 and return nil or a valid handler as appropriate. Handler could
19399 be one of an interactive command, a function, or a form.
19401 Set `org-use-speed-commands' to non-nil value to enable this
19402 hook. The default setting is `org-speed-command-activate'."
19403 :group 'org-structure
19404 :version "24.1"
19405 :type 'hook)
19407 (defun org-self-insert-command (N)
19408 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19409 If the cursor is in a table looking at whitespace, the whitespace is
19410 overwritten, and the table is not marked as requiring realignment."
19411 (interactive "p")
19412 (org-check-before-invisible-edit 'insert)
19413 (cond
19414 ((and org-use-speed-commands
19415 (setq org-speed-command
19416 (run-hook-with-args-until-success
19417 'org-speed-command-hook (this-command-keys))))
19418 (cond
19419 ((commandp org-speed-command)
19420 (setq this-command org-speed-command)
19421 (call-interactively org-speed-command))
19422 ((functionp org-speed-command)
19423 (funcall org-speed-command))
19424 ((and org-speed-command (listp org-speed-command))
19425 (eval org-speed-command))
19426 (t (let (org-use-speed-commands)
19427 (call-interactively 'org-self-insert-command)))))
19428 ((and
19429 (org-table-p)
19430 (progn
19431 ;; check if we blank the field, and if that triggers align
19432 (and (featurep 'org-table) org-table-auto-blank-field
19433 (member last-command
19434 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19435 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19436 ;; got extra space, this field does not determine column width
19437 (let (org-table-may-need-update) (org-table-blank-field))
19438 ;; no extra space, this field may determine column width
19439 (org-table-blank-field)))
19441 (eq N 1)
19442 (looking-at "[^|\n]* |"))
19443 (let (org-table-may-need-update)
19444 (goto-char (1- (match-end 0)))
19445 (backward-delete-char 1)
19446 (goto-char (match-beginning 0))
19447 (self-insert-command N)))
19449 (setq org-table-may-need-update t)
19450 (self-insert-command N)
19451 (org-fix-tags-on-the-fly)
19452 (if org-self-insert-cluster-for-undo
19453 (if (not (eq last-command 'org-self-insert-command))
19454 (setq org-self-insert-command-undo-counter 1)
19455 (if (>= org-self-insert-command-undo-counter 20)
19456 (setq org-self-insert-command-undo-counter 1)
19457 (and (> org-self-insert-command-undo-counter 0)
19458 buffer-undo-list (listp buffer-undo-list)
19459 (not (cadr buffer-undo-list)) ; remove nil entry
19460 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19461 (setq org-self-insert-command-undo-counter
19462 (1+ org-self-insert-command-undo-counter))))))))
19464 (defun org-check-before-invisible-edit (kind)
19465 "Check is editing if kind KIND would be dangerous with invisible text around.
19466 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19467 ;; First, try to get out of here as quickly as possible, to reduce overhead
19468 (if (and org-catch-invisible-edits
19469 (or (not (boundp 'visible-mode)) (not visible-mode))
19470 (or (get-char-property (point) 'invisible)
19471 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19472 ;; OK, we need to take a closer look
19473 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19474 (invisible-before-point (if (bobp) nil (get-char-property
19475 (1- (point)) 'invisible)))
19476 (border-and-ok-direction
19478 ;; Check if we are acting predictably before invisible text
19479 (and invisible-at-point (not invisible-before-point)
19480 (memq kind '(insert delete-backward)))
19481 ;; Check if we are acting predictably after invisible text
19482 ;; This works not well, and I have turned it off. It seems
19483 ;; better to always show and stop after invisible text.
19484 ;; (and (not invisible-at-point) invisible-before-point
19485 ;; (memq kind '(insert delete)))
19487 (when (or (memq invisible-at-point '(outline org-hide-block t))
19488 (memq invisible-before-point '(outline org-hide-block t)))
19489 (if (eq org-catch-invisible-edits 'error)
19490 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19491 (if (and org-custom-properties-overlays
19492 (y-or-n-p "Display invisible properties in this buffer? "))
19493 (org-toggle-custom-properties-visibility)
19494 ;; Make the area visible
19495 (save-excursion
19496 (if invisible-before-point
19497 (goto-char (previous-single-char-property-change
19498 (point) 'invisible)))
19499 (show-subtree))
19500 (cond
19501 ((eq org-catch-invisible-edits 'show)
19502 ;; That's it, we do the edit after showing
19503 (message
19504 "Unfolding invisible region around point before editing")
19505 (sit-for 1))
19506 ((and (eq org-catch-invisible-edits 'smart)
19507 border-and-ok-direction)
19508 (message "Unfolding invisible region around point before editing"))
19510 ;; Don't do the edit, make the user repeat it in full visibility
19511 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19513 (defun org-fix-tags-on-the-fly ()
19514 (when (and (equal (char-after (point-at-bol)) ?*)
19515 (org-at-heading-p))
19516 (org-align-tags-here org-tags-column)))
19518 (defun org-delete-backward-char (N)
19519 "Like `delete-backward-char', insert whitespace at field end in tables.
19520 When deleting backwards, in tables this function will insert whitespace in
19521 front of the next \"|\" separator, to keep the table aligned. The table will
19522 still be marked for re-alignment if the field did fill the entire column,
19523 because, in this case the deletion might narrow the column."
19524 (interactive "p")
19525 (save-match-data
19526 (org-check-before-invisible-edit 'delete-backward)
19527 (if (and (org-table-p)
19528 (eq N 1)
19529 (string-match "|" (buffer-substring (point-at-bol) (point)))
19530 (looking-at ".*?|"))
19531 (let ((pos (point))
19532 (noalign (looking-at "[^|\n\r]* |"))
19533 (c org-table-may-need-update))
19534 (backward-delete-char N)
19535 (if (not overwrite-mode)
19536 (progn
19537 (skip-chars-forward "^|")
19538 (insert " ")
19539 (goto-char (1- pos))))
19540 ;; noalign: if there were two spaces at the end, this field
19541 ;; does not determine the width of the column.
19542 (if noalign (setq org-table-may-need-update c)))
19543 (backward-delete-char N)
19544 (org-fix-tags-on-the-fly))))
19546 (defun org-delete-char (N)
19547 "Like `delete-char', but insert whitespace at field end in tables.
19548 When deleting characters, in tables this function will insert whitespace in
19549 front of the next \"|\" separator, to keep the table aligned. The table will
19550 still be marked for re-alignment if the field did fill the entire column,
19551 because, in this case the deletion might narrow the column."
19552 (interactive "p")
19553 (save-match-data
19554 (org-check-before-invisible-edit 'delete)
19555 (if (and (org-table-p)
19556 (not (bolp))
19557 (not (= (char-after) ?|))
19558 (eq N 1))
19559 (if (looking-at ".*?|")
19560 (let ((pos (point))
19561 (noalign (looking-at "[^|\n\r]* |"))
19562 (c org-table-may-need-update))
19563 (replace-match
19564 (concat (substring (match-string 0) 1 -1) " |") nil t)
19565 (goto-char pos)
19566 ;; noalign: if there were two spaces at the end, this field
19567 ;; does not determine the width of the column.
19568 (if noalign (setq org-table-may-need-update c)))
19569 (delete-char N))
19570 (delete-char N)
19571 (org-fix-tags-on-the-fly))))
19573 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19574 (put 'org-self-insert-command 'delete-selection
19575 (lambda ()
19576 (not (run-hook-with-args-until-success
19577 'self-insert-uses-region-functions))))
19578 (put 'orgtbl-self-insert-command 'delete-selection
19579 (lambda ()
19580 (not (run-hook-with-args-until-success
19581 'self-insert-uses-region-functions))))
19582 (put 'org-delete-char 'delete-selection 'supersede)
19583 (put 'org-delete-backward-char 'delete-selection 'supersede)
19584 (put 'org-yank 'delete-selection 'yank)
19586 ;; Make `flyspell-mode' delay after some commands
19587 (put 'org-self-insert-command 'flyspell-delayed t)
19588 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19589 (put 'org-delete-char 'flyspell-delayed t)
19590 (put 'org-delete-backward-char 'flyspell-delayed t)
19592 ;; Make pabbrev-mode expand after org-mode commands
19593 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19594 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19596 (defun org-remap (map &rest commands)
19597 "In MAP, remap the functions given in COMMANDS.
19598 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19599 (let (new old)
19600 (while commands
19601 (setq old (pop commands) new (pop commands))
19602 (if (fboundp 'command-remapping)
19603 (org-defkey map (vector 'remap old) new)
19604 (substitute-key-definition old new map global-map)))))
19606 (defun org-transpose-words ()
19607 "Transpose words for Org.
19608 This uses the `org-mode-transpose-word-syntax-table' syntax
19609 table, which interprets characters in `org-emphasis-alist' as
19610 word constituents."
19611 (interactive)
19612 (with-syntax-table org-mode-transpose-word-syntax-table
19613 (call-interactively 'transpose-words)))
19614 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19616 (when (eq org-enable-table-editor 'optimized)
19617 ;; If the user wants maximum table support, we need to hijack
19618 ;; some standard editing functions
19619 (org-remap org-mode-map
19620 'self-insert-command 'org-self-insert-command
19621 'delete-char 'org-delete-char
19622 'delete-backward-char 'org-delete-backward-char)
19623 (org-defkey org-mode-map "|" 'org-force-self-insert))
19625 (defvar org-ctrl-c-ctrl-c-hook nil
19626 "Hook for functions attaching themselves to `C-c C-c'.
19628 This can be used to add additional functionality to the C-c C-c
19629 key which executes context-dependent commands. This hook is run
19630 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19631 run after the last test.
19633 Each function will be called with no arguments. The function
19634 must check if the context is appropriate for it to act. If yes,
19635 it should do its thing and then return a non-nil value. If the
19636 context is wrong, just do nothing and return nil.")
19638 (defvar org-ctrl-c-ctrl-c-final-hook nil
19639 "Hook for functions attaching themselves to `C-c C-c'.
19641 This can be used to add additional functionality to the C-c C-c
19642 key which executes context-dependent commands. This hook is run
19643 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19644 before the first test.
19646 Each function will be called with no arguments. The function
19647 must check if the context is appropriate for it to act. If yes,
19648 it should do its thing and then return a non-nil value. If the
19649 context is wrong, just do nothing and return nil.")
19651 (defvar org-tab-first-hook nil
19652 "Hook for functions to attach themselves to TAB.
19653 See `org-ctrl-c-ctrl-c-hook' for more information.
19654 This hook runs as the first action when TAB is pressed, even before
19655 `org-cycle' messes around with the `outline-regexp' to cater for
19656 inline tasks and plain list item folding.
19657 If any function in this hook returns t, any other actions that
19658 would have been caused by TAB (such as table field motion or visibility
19659 cycling) will not occur.")
19661 (defvar org-tab-after-check-for-table-hook nil
19662 "Hook for functions to attach themselves to TAB.
19663 See `org-ctrl-c-ctrl-c-hook' for more information.
19664 This hook runs after it has been established that the cursor is not in a
19665 table, but before checking if the cursor is in a headline or if global cycling
19666 should be done.
19667 If any function in this hook returns t, not other actions like visibility
19668 cycling will be done.")
19670 (defvar org-tab-after-check-for-cycling-hook nil
19671 "Hook for functions to attach themselves to TAB.
19672 See `org-ctrl-c-ctrl-c-hook' for more information.
19673 This hook runs after it has been established that not table field motion and
19674 not visibility should be done because of current context. This is probably
19675 the place where a package like yasnippets can hook in.")
19677 (defvar org-tab-before-tab-emulation-hook nil
19678 "Hook for functions to attach themselves to TAB.
19679 See `org-ctrl-c-ctrl-c-hook' for more information.
19680 This hook runs after every other options for TAB have been exhausted, but
19681 before indentation and \t insertion takes place.")
19683 (defvar org-metaleft-hook nil
19684 "Hook for functions attaching themselves to `M-left'.
19685 See `org-ctrl-c-ctrl-c-hook' for more information.")
19686 (defvar org-metaright-hook nil
19687 "Hook for functions attaching themselves to `M-right'.
19688 See `org-ctrl-c-ctrl-c-hook' for more information.")
19689 (defvar org-metaup-hook nil
19690 "Hook for functions attaching themselves to `M-up'.
19691 See `org-ctrl-c-ctrl-c-hook' for more information.")
19692 (defvar org-metadown-hook nil
19693 "Hook for functions attaching themselves to `M-down'.
19694 See `org-ctrl-c-ctrl-c-hook' for more information.")
19695 (defvar org-shiftmetaleft-hook nil
19696 "Hook for functions attaching themselves to `M-S-left'.
19697 See `org-ctrl-c-ctrl-c-hook' for more information.")
19698 (defvar org-shiftmetaright-hook nil
19699 "Hook for functions attaching themselves to `M-S-right'.
19700 See `org-ctrl-c-ctrl-c-hook' for more information.")
19701 (defvar org-shiftmetaup-hook nil
19702 "Hook for functions attaching themselves to `M-S-up'.
19703 See `org-ctrl-c-ctrl-c-hook' for more information.")
19704 (defvar org-shiftmetadown-hook nil
19705 "Hook for functions attaching themselves to `M-S-down'.
19706 See `org-ctrl-c-ctrl-c-hook' for more information.")
19707 (defvar org-metareturn-hook nil
19708 "Hook for functions attaching themselves to `M-RET'.
19709 See `org-ctrl-c-ctrl-c-hook' for more information.")
19710 (defvar org-shiftup-hook nil
19711 "Hook for functions attaching themselves to `S-up'.
19712 See `org-ctrl-c-ctrl-c-hook' for more information.")
19713 (defvar org-shiftup-final-hook nil
19714 "Hook for functions attaching themselves to `S-up'.
19715 This one runs after all other options except shift-select have been excluded.
19716 See `org-ctrl-c-ctrl-c-hook' for more information.")
19717 (defvar org-shiftdown-hook nil
19718 "Hook for functions attaching themselves to `S-down'.
19719 See `org-ctrl-c-ctrl-c-hook' for more information.")
19720 (defvar org-shiftdown-final-hook nil
19721 "Hook for functions attaching themselves to `S-down'.
19722 This one runs after all other options except shift-select have been excluded.
19723 See `org-ctrl-c-ctrl-c-hook' for more information.")
19724 (defvar org-shiftleft-hook nil
19725 "Hook for functions attaching themselves to `S-left'.
19726 See `org-ctrl-c-ctrl-c-hook' for more information.")
19727 (defvar org-shiftleft-final-hook nil
19728 "Hook for functions attaching themselves to `S-left'.
19729 This one runs after all other options except shift-select have been excluded.
19730 See `org-ctrl-c-ctrl-c-hook' for more information.")
19731 (defvar org-shiftright-hook nil
19732 "Hook for functions attaching themselves to `S-right'.
19733 See `org-ctrl-c-ctrl-c-hook' for more information.")
19734 (defvar org-shiftright-final-hook nil
19735 "Hook for functions attaching themselves to `S-right'.
19736 This one runs after all other options except shift-select have been excluded.
19737 See `org-ctrl-c-ctrl-c-hook' for more information.")
19739 (defun org-modifier-cursor-error ()
19740 "Throw an error, a modified cursor command was applied in wrong context."
19741 (user-error "This command is active in special context like tables, headlines or items"))
19743 (defun org-shiftselect-error ()
19744 "Throw an error because Shift-Cursor command was applied in wrong context."
19745 (if (and (boundp 'shift-select-mode) shift-select-mode)
19746 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19747 (user-error "This command works only in special context like headlines or timestamps")))
19749 (defun org-call-for-shift-select (cmd)
19750 (let ((this-command-keys-shift-translated t))
19751 (call-interactively cmd)))
19753 (defun org-shifttab (&optional arg)
19754 "Global visibility cycling or move to previous table field.
19755 Call `org-table-previous-field' within a table.
19756 When ARG is nil, cycle globally through visibility states.
19757 When ARG is a numeric prefix, show contents of this level."
19758 (interactive "P")
19759 (cond
19760 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19761 ((integerp arg)
19762 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19763 (message "Content view to level: %d" arg)
19764 (org-content (prefix-numeric-value arg2))
19765 (org-cycle-show-empty-lines t)
19766 (setq org-cycle-global-status 'overview)))
19767 (t (call-interactively 'org-global-cycle))))
19769 (defun org-shiftmetaleft ()
19770 "Promote subtree or delete table column.
19771 Calls `org-promote-subtree', `org-outdent-item-tree', or
19772 `org-table-delete-column', depending on context. See the
19773 individual commands for more information."
19774 (interactive)
19775 (cond
19776 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19777 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19778 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19779 ((if (not (org-region-active-p)) (org-at-item-p)
19780 (save-excursion (goto-char (region-beginning))
19781 (org-at-item-p)))
19782 (call-interactively 'org-outdent-item-tree))
19783 (t (org-modifier-cursor-error))))
19785 (defun org-shiftmetaright ()
19786 "Demote subtree or insert table column.
19787 Calls `org-demote-subtree', `org-indent-item-tree', or
19788 `org-table-insert-column', depending on context. See the
19789 individual commands for more information."
19790 (interactive)
19791 (cond
19792 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19793 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19794 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19795 ((if (not (org-region-active-p)) (org-at-item-p)
19796 (save-excursion (goto-char (region-beginning))
19797 (org-at-item-p)))
19798 (call-interactively 'org-indent-item-tree))
19799 (t (org-modifier-cursor-error))))
19801 (defun org-shiftmetaup (&optional arg)
19802 "Move subtree up or kill table row.
19803 Calls `org-move-subtree-up' or `org-table-kill-row' or
19804 `org-move-item-up' or `org-timestamp-up', depending on context.
19805 See the individual commands for more information."
19806 (interactive "P")
19807 (cond
19808 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19809 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19810 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19811 ((org-at-item-p) (call-interactively 'org-move-item-up))
19812 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19813 (call-interactively 'org-timestamp-up)))
19814 (t (call-interactively 'org-drag-line-backward))))
19816 (defun org-shiftmetadown (&optional arg)
19817 "Move subtree down or insert table row.
19818 Calls `org-move-subtree-down' or `org-table-insert-row' or
19819 `org-move-item-down' or `org-timestamp-up', depending on context.
19820 See the individual commands for more information."
19821 (interactive "P")
19822 (cond
19823 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19824 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19825 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19826 ((org-at-item-p) (call-interactively 'org-move-item-down))
19827 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19828 (call-interactively 'org-timestamp-down)))
19829 (t (call-interactively 'org-drag-line-forward))))
19831 (defsubst org-hidden-tree-error ()
19832 (user-error
19833 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19835 (defun org-metaleft (&optional arg)
19836 "Promote heading or move table column to left.
19837 Calls `org-do-promote' or `org-table-move-column', depending on context.
19838 With no specific context, calls the Emacs default `backward-word'.
19839 See the individual commands for more information."
19840 (interactive "P")
19841 (cond
19842 ((run-hook-with-args-until-success 'org-metaleft-hook))
19843 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19844 ((org-with-limited-levels
19845 (or (org-at-heading-p)
19846 (and (org-region-active-p)
19847 (save-excursion
19848 (goto-char (region-beginning))
19849 (org-at-heading-p)))))
19850 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19851 (call-interactively 'org-do-promote))
19852 ;; At an inline task.
19853 ((org-at-heading-p)
19854 (call-interactively 'org-inlinetask-promote))
19855 ((or (org-at-item-p)
19856 (and (org-region-active-p)
19857 (save-excursion
19858 (goto-char (region-beginning))
19859 (org-at-item-p))))
19860 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19861 (call-interactively 'org-outdent-item))
19862 (t (call-interactively 'backward-word))))
19864 (defun org-metaright (&optional arg)
19865 "Demote a subtree, a list item or move table column to right.
19866 In front of a drawer or a block keyword, indent it correctly.
19867 With no specific context, calls the Emacs default `forward-word'.
19868 See the individual commands for more information."
19869 (interactive "P")
19870 (cond
19871 ((run-hook-with-args-until-success 'org-metaright-hook))
19872 ((org-at-table-p) (call-interactively 'org-table-move-column))
19873 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19874 ((org-at-block-p) (call-interactively 'org-indent-block))
19875 ((org-with-limited-levels
19876 (or (org-at-heading-p)
19877 (and (org-region-active-p)
19878 (save-excursion
19879 (goto-char (region-beginning))
19880 (org-at-heading-p)))))
19881 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19882 (call-interactively 'org-do-demote))
19883 ;; At an inline task.
19884 ((org-at-heading-p)
19885 (call-interactively 'org-inlinetask-demote))
19886 ((or (org-at-item-p)
19887 (and (org-region-active-p)
19888 (save-excursion
19889 (goto-char (region-beginning))
19890 (org-at-item-p))))
19891 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19892 (call-interactively 'org-indent-item))
19893 (t (call-interactively 'forward-word))))
19895 (defun org-check-for-hidden (what)
19896 "Check if there are hidden headlines/items in the current visual line.
19897 WHAT can be either `headlines' or `items'. If the current line is
19898 an outline or item heading and it has a folded subtree below it,
19899 this function returns t, nil otherwise."
19900 (let ((re (cond
19901 ((eq what 'headlines) org-outline-regexp-bol)
19902 ((eq what 'items) (org-item-beginning-re))
19903 (t (error "This should not happen"))))
19904 beg end)
19905 (save-excursion
19906 (catch 'exit
19907 (unless (org-region-active-p)
19908 (setq beg (point-at-bol))
19909 (beginning-of-line 2)
19910 (while (and (not (eobp)) ;; this is like `next-line'
19911 (get-char-property (1- (point)) 'invisible))
19912 (beginning-of-line 2))
19913 (setq end (point))
19914 (goto-char beg)
19915 (goto-char (point-at-eol))
19916 (setq end (max end (point)))
19917 (while (re-search-forward re end t)
19918 (if (get-char-property (match-beginning 0) 'invisible)
19919 (throw 'exit t))))
19920 nil))))
19922 (defun org-metaup (&optional arg)
19923 "Move subtree up or move table row up.
19924 Calls `org-move-subtree-up' or `org-table-move-row' or
19925 `org-move-item-up', depending on context. See the individual commands
19926 for more information."
19927 (interactive "P")
19928 (cond
19929 ((run-hook-with-args-until-success 'org-metaup-hook))
19930 ((org-region-active-p)
19931 (let* ((a (min (region-beginning) (region-end)))
19932 (b (1- (max (region-beginning) (region-end))))
19933 (c (save-excursion (goto-char a)
19934 (move-beginning-of-line 0)))
19935 (d (save-excursion (goto-char a)
19936 (move-end-of-line 0) (point))))
19937 (transpose-regions a b c d)
19938 (goto-char c)))
19939 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19940 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19941 ((org-at-item-p) (call-interactively 'org-move-item-up))
19942 (t (org-drag-element-backward))))
19944 (defun org-metadown (&optional arg)
19945 "Move subtree down or move table row down.
19946 Calls `org-move-subtree-down' or `org-table-move-row' or
19947 `org-move-item-down', depending on context. See the individual
19948 commands for more information."
19949 (interactive "P")
19950 (cond
19951 ((run-hook-with-args-until-success 'org-metadown-hook))
19952 ((org-region-active-p)
19953 (let* ((a (min (region-beginning) (region-end)))
19954 (b (max (region-beginning) (region-end)))
19955 (c (save-excursion (goto-char b)
19956 (move-beginning-of-line 1)))
19957 (d (save-excursion (goto-char b)
19958 (move-end-of-line 1) (1+ (point)))))
19959 (transpose-regions a b c d)
19960 (goto-char d)))
19961 ((org-at-table-p) (call-interactively 'org-table-move-row))
19962 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19963 ((org-at-item-p) (call-interactively 'org-move-item-down))
19964 (t (org-drag-element-forward))))
19966 (defun org-shiftup (&optional arg)
19967 "Increase item in timestamp or increase priority of current headline.
19968 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19969 depending on context. See the individual commands for more information."
19970 (interactive "P")
19971 (cond
19972 ((run-hook-with-args-until-success 'org-shiftup-hook))
19973 ((and org-support-shift-select (org-region-active-p))
19974 (org-call-for-shift-select 'previous-line))
19975 ((org-at-timestamp-p t)
19976 (call-interactively (if org-edit-timestamp-down-means-later
19977 'org-timestamp-down 'org-timestamp-up)))
19978 ((and (not (eq org-support-shift-select 'always))
19979 org-enable-priority-commands
19980 (org-at-heading-p))
19981 (call-interactively 'org-priority-up))
19982 ((and (not org-support-shift-select) (org-at-item-p))
19983 (call-interactively 'org-previous-item))
19984 ((org-clocktable-try-shift 'up arg))
19985 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19986 (org-support-shift-select
19987 (org-call-for-shift-select 'previous-line))
19988 (t (org-shiftselect-error))))
19990 (defun org-shiftdown (&optional arg)
19991 "Decrease item in timestamp or decrease priority of current headline.
19992 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19993 depending on context. See the individual commands for more information."
19994 (interactive "P")
19995 (cond
19996 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19997 ((and org-support-shift-select (org-region-active-p))
19998 (org-call-for-shift-select 'next-line))
19999 ((org-at-timestamp-p t)
20000 (call-interactively (if org-edit-timestamp-down-means-later
20001 'org-timestamp-up 'org-timestamp-down)))
20002 ((and (not (eq org-support-shift-select 'always))
20003 org-enable-priority-commands
20004 (org-at-heading-p))
20005 (call-interactively 'org-priority-down))
20006 ((and (not org-support-shift-select) (org-at-item-p))
20007 (call-interactively 'org-next-item))
20008 ((org-clocktable-try-shift 'down arg))
20009 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20010 (org-support-shift-select
20011 (org-call-for-shift-select 'next-line))
20012 (t (org-shiftselect-error))))
20014 (defun org-shiftright (&optional arg)
20015 "Cycle the thing at point or in the current line, depending on context.
20016 Depending on context, this does one of the following:
20018 - switch a timestamp at point one day into the future
20019 - on a headline, switch to the next TODO keyword.
20020 - on an item, switch entire list to the next bullet type
20021 - on a property line, switch to the next allowed value
20022 - on a clocktable definition line, move time block into the future"
20023 (interactive "P")
20024 (cond
20025 ((run-hook-with-args-until-success 'org-shiftright-hook))
20026 ((and org-support-shift-select (org-region-active-p))
20027 (org-call-for-shift-select 'forward-char))
20028 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20029 ((and (not (eq org-support-shift-select 'always))
20030 (org-at-heading-p))
20031 (let ((org-inhibit-logging
20032 (not org-treat-S-cursor-todo-selection-as-state-change))
20033 (org-inhibit-blocking
20034 (not org-treat-S-cursor-todo-selection-as-state-change)))
20035 (org-call-with-arg 'org-todo 'right)))
20036 ((or (and org-support-shift-select
20037 (not (eq org-support-shift-select 'always))
20038 (org-at-item-bullet-p))
20039 (and (not org-support-shift-select) (org-at-item-p)))
20040 (org-call-with-arg 'org-cycle-list-bullet nil))
20041 ((and (not (eq org-support-shift-select 'always))
20042 (org-at-property-p))
20043 (call-interactively 'org-property-next-allowed-value))
20044 ((org-clocktable-try-shift 'right arg))
20045 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20046 (org-support-shift-select
20047 (org-call-for-shift-select 'forward-char))
20048 (t (org-shiftselect-error))))
20050 (defun org-shiftleft (&optional arg)
20051 "Cycle the thing at point or in the current line, depending on context.
20052 Depending on context, this does one of the following:
20054 - switch a timestamp at point one day into the past
20055 - on a headline, switch to the previous TODO keyword.
20056 - on an item, switch entire list to the previous bullet type
20057 - on a property line, switch to the previous allowed value
20058 - on a clocktable definition line, move time block into the past"
20059 (interactive "P")
20060 (cond
20061 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20062 ((and org-support-shift-select (org-region-active-p))
20063 (org-call-for-shift-select 'backward-char))
20064 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20065 ((and (not (eq org-support-shift-select 'always))
20066 (org-at-heading-p))
20067 (let ((org-inhibit-logging
20068 (not org-treat-S-cursor-todo-selection-as-state-change))
20069 (org-inhibit-blocking
20070 (not org-treat-S-cursor-todo-selection-as-state-change)))
20071 (org-call-with-arg 'org-todo 'left)))
20072 ((or (and org-support-shift-select
20073 (not (eq org-support-shift-select 'always))
20074 (org-at-item-bullet-p))
20075 (and (not org-support-shift-select) (org-at-item-p)))
20076 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20077 ((and (not (eq org-support-shift-select 'always))
20078 (org-at-property-p))
20079 (call-interactively 'org-property-previous-allowed-value))
20080 ((org-clocktable-try-shift 'left arg))
20081 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20082 (org-support-shift-select
20083 (org-call-for-shift-select 'backward-char))
20084 (t (org-shiftselect-error))))
20086 (defun org-shiftcontrolright ()
20087 "Switch to next TODO set."
20088 (interactive)
20089 (cond
20090 ((and org-support-shift-select (org-region-active-p))
20091 (org-call-for-shift-select 'forward-word))
20092 ((and (not (eq org-support-shift-select 'always))
20093 (org-at-heading-p))
20094 (org-call-with-arg 'org-todo 'nextset))
20095 (org-support-shift-select
20096 (org-call-for-shift-select 'forward-word))
20097 (t (org-shiftselect-error))))
20099 (defun org-shiftcontrolleft ()
20100 "Switch to previous TODO set."
20101 (interactive)
20102 (cond
20103 ((and org-support-shift-select (org-region-active-p))
20104 (org-call-for-shift-select 'backward-word))
20105 ((and (not (eq org-support-shift-select 'always))
20106 (org-at-heading-p))
20107 (org-call-with-arg 'org-todo 'previousset))
20108 (org-support-shift-select
20109 (org-call-for-shift-select 'backward-word))
20110 (t (org-shiftselect-error))))
20112 (defun org-shiftcontrolup (&optional n)
20113 "Change timestamps synchronously up in CLOCK log lines.
20114 Optional argument N tells to change by that many units."
20115 (interactive "P")
20116 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20117 (let (org-support-shift-select)
20118 (org-clock-timestamps-up n))
20119 (user-error "Not at a clock log")))
20121 (defun org-shiftcontroldown (&optional n)
20122 "Change timestamps synchronously down in CLOCK log lines.
20123 Optional argument N tells to change by that many units."
20124 (interactive "P")
20125 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20126 (let (org-support-shift-select)
20127 (org-clock-timestamps-down n))
20128 (user-error "Not at a clock log")))
20130 (defun org-ctrl-c-ret ()
20131 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20132 (interactive)
20133 (cond
20134 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20135 (t (call-interactively 'org-insert-heading))))
20137 (defun org-find-visible ()
20138 (let ((s (point)))
20139 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20140 (get-char-property s 'invisible)))
20142 (defun org-find-invisible ()
20143 (let ((s (point)))
20144 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20145 (not (get-char-property s 'invisible))))
20148 (defun org-copy-visible (beg end)
20149 "Copy the visible parts of the region."
20150 (interactive "r")
20151 (let (snippets s)
20152 (save-excursion
20153 (save-restriction
20154 (narrow-to-region beg end)
20155 (setq s (goto-char (point-min)))
20156 (while (not (= (point) (point-max)))
20157 (goto-char (org-find-invisible))
20158 (push (buffer-substring s (point)) snippets)
20159 (setq s (goto-char (org-find-visible))))))
20160 (kill-new (apply 'concat (nreverse snippets)))))
20162 (defun org-copy-special ()
20163 "Copy region in table or copy current subtree.
20164 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20165 See the individual commands for more information."
20166 (interactive)
20167 (call-interactively
20168 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20170 (defun org-cut-special ()
20171 "Cut region in table or cut current subtree.
20172 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20173 See the individual commands for more information."
20174 (interactive)
20175 (call-interactively
20176 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20178 (defun org-paste-special (arg)
20179 "Paste rectangular region into table, or past subtree relative to level.
20180 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20181 See the individual commands for more information."
20182 (interactive "P")
20183 (if (org-at-table-p)
20184 (org-table-paste-rectangle)
20185 (org-paste-subtree arg)))
20187 (defsubst org-in-fixed-width-region-p ()
20188 "Is point in a fixed-width region?"
20189 (save-match-data
20190 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20192 (defun org-edit-special (&optional arg)
20193 "Call a special editor for the element at point.
20194 When at a table, call the formula editor with `org-table-edit-formulas'.
20195 When in a source code block, call `org-edit-src-code'.
20196 When in a fixed-width region, call `org-edit-fixed-width-region'.
20197 When at an #+INCLUDE keyword, visit the included file.
20198 On a link, call `ffap' to visit the link at point.
20199 Otherwise, return a user error."
20200 (interactive "P")
20201 (let ((element (org-element-at-point)))
20202 (assert (not buffer-read-only) nil
20203 "Buffer is read-only: %s" (buffer-name))
20204 (case (org-element-type element)
20205 (src-block
20206 (if (not arg) (org-edit-src-code)
20207 (let* ((info (org-babel-get-src-block-info))
20208 (lang (nth 0 info))
20209 (params (nth 2 info))
20210 (session (cdr (assq :session params))))
20211 (if (not session) (org-edit-src-code)
20212 ;; At a src-block with a session and function called with
20213 ;; an ARG: switch to the buffer related to the inferior
20214 ;; process.
20215 (switch-to-buffer
20216 (funcall (intern (concat "org-babel-prep-session:" lang))
20217 session params))))))
20218 (keyword
20219 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20220 (find-file
20221 (org-remove-double-quotes
20222 (car (org-split-string (org-element-property :value element)))))
20223 (user-error "No special environment to edit here")))
20224 (table
20225 (if (eq (org-element-property :type element) 'table.el)
20226 (org-edit-src-code)
20227 (call-interactively 'org-table-edit-formulas)))
20228 ;; Only Org tables contain `table-row' type elements.
20229 (table-row (call-interactively 'org-table-edit-formulas))
20230 ((example-block export-block) (org-edit-src-code))
20231 (fixed-width (org-edit-fixed-width-region))
20232 (otherwise
20233 ;; No notable element at point. Though, we may be at a link,
20234 ;; which is an object. Thus, scan deeper.
20235 (if (eq (org-element-type (org-element-context element)) 'link)
20236 (call-interactively 'ffap)
20237 (user-error "No special environment to edit here"))))))
20239 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20240 (defun org-ctrl-c-ctrl-c (&optional arg)
20241 "Set tags in headline, or update according to changed information at point.
20243 This command does many different things, depending on context:
20245 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20246 this is what we do.
20248 - If the cursor is on a statistics cookie, update it.
20250 - If the cursor is in a headline, prompt for tags and insert them
20251 into the current line, aligned to `org-tags-column'. When called
20252 with prefix arg, realign all tags in the current buffer.
20254 - If the cursor is in one of the special #+KEYWORD lines, this
20255 triggers scanning the buffer for these lines and updating the
20256 information.
20258 - If the cursor is inside a table, realign the table. This command
20259 works even if the automatic table editor has been turned off.
20261 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20262 the entire table.
20264 - If the cursor is at a footnote reference or definition, jump to
20265 the corresponding definition or references, respectively.
20267 - If the cursor is a the beginning of a dynamic block, update it.
20269 - If the current buffer is a capture buffer, close note and file it.
20271 - If the cursor is on a <<<target>>>, update radio targets and
20272 corresponding links in this buffer.
20274 - If the cursor is on a numbered item in a plain list, renumber the
20275 ordered list.
20277 - If the cursor is on a checkbox, toggle it.
20279 - If the cursor is on a code block, evaluate it. The variable
20280 `org-confirm-babel-evaluate' can be used to control prompting
20281 before code block evaluation, by default every code block
20282 evaluation requires confirmation. Code block evaluation can be
20283 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20284 (interactive "P")
20285 (cond
20286 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20287 org-occur-highlights
20288 org-latex-fragment-image-overlays)
20289 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20290 (org-remove-occur-highlights)
20291 (org-remove-latex-fragment-image-overlays)
20292 (message "Temporary highlights/overlays removed from current buffer"))
20293 ((and (local-variable-p 'org-finish-function (current-buffer))
20294 (fboundp org-finish-function))
20295 (funcall org-finish-function))
20296 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20298 (let* ((context (org-element-context)) (type (org-element-type context)))
20299 ;; Test if point is within a blank line.
20300 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20301 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20302 (user-error "C-c C-c can do nothing useful at this location"))
20303 (case type
20304 ;; When at a link, act according to the parent instead.
20305 (link (setq context (org-element-property :parent context))
20306 (setq type (org-element-type context)))
20307 ;; Unsupported object types: refer to the first supported
20308 ;; element or object containing it.
20309 ((bold code entity export-snippet inline-babel-call inline-src-block
20310 italic latex-fragment line-break macro strike-through subscript
20311 superscript underline verbatim)
20312 (while (and (setq context (org-element-property :parent context))
20313 (not (memq (setq type (org-element-type context))
20314 '(radio-target paragraph verse-block
20315 table-cell)))))))
20316 ;; For convenience: at the first line of a paragraph on the
20317 ;; same line as an item, apply function on that item instead.
20318 (when (eq type 'paragraph)
20319 (let ((parent (org-element-property :parent context)))
20320 (when (and (eq (org-element-type parent) 'item)
20321 (= (point-at-bol) (org-element-property :begin parent)))
20322 (setq context parent type 'item))))
20323 ;; Act according to type of element or object at point.
20324 (case type
20325 (clock (org-clock-update-time-maybe))
20326 (dynamic-block
20327 (save-excursion
20328 (goto-char (org-element-property :post-affiliated context))
20329 (org-update-dblock)))
20330 (footnote-definition
20331 (goto-char (org-element-property :post-affiliated context))
20332 (call-interactively 'org-footnote-action))
20333 (footnote-reference (call-interactively 'org-footnote-action))
20334 ((headline inlinetask)
20335 (save-excursion (goto-char (org-element-property :begin context))
20336 (call-interactively 'org-set-tags)))
20337 (item
20338 ;; At an item: a double C-u set checkbox to "[-]"
20339 ;; unconditionally, whereas a single one will toggle its
20340 ;; presence. Without an universal argument, if the item
20341 ;; has a checkbox, toggle it. Otherwise repair the list.
20342 (let* ((box (org-element-property :checkbox context))
20343 (struct (org-element-property :structure context))
20344 (old-struct (copy-tree struct))
20345 (parents (org-list-parents-alist struct))
20346 (prevs (org-list-prevs-alist struct))
20347 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20348 (org-list-set-checkbox
20349 (org-element-property :begin context) struct
20350 (cond ((equal arg '(16)) "[-]")
20351 ((and (not box) (equal arg '(4))) "[ ]")
20352 ((or (not box) (equal arg '(4))) nil)
20353 ((eq box 'on) "[ ]")
20354 (t "[X]")))
20355 ;; Mimic `org-list-write-struct' but with grabbing
20356 ;; a return value from `org-list-struct-fix-box'.
20357 (org-list-struct-fix-ind struct parents 2)
20358 (org-list-struct-fix-item-end struct)
20359 (org-list-struct-fix-bul struct prevs)
20360 (org-list-struct-fix-ind struct parents)
20361 (let ((block-item
20362 (org-list-struct-fix-box struct parents prevs orderedp)))
20363 (if (and box (equal struct old-struct))
20364 (if (equal arg '(16))
20365 (message "Checkboxes already reset")
20366 (user-error "Cannot toggle this checkbox: %s"
20367 (if (eq box 'on)
20368 "all subitems checked"
20369 "unchecked subitems")))
20370 (org-list-struct-apply-struct struct old-struct)
20371 (org-update-checkbox-count-maybe))
20372 (when block-item
20373 (message "Checkboxes were removed due to empty box at line %d"
20374 (org-current-line block-item))))))
20375 (keyword
20376 (let ((org-inhibit-startup-visibility-stuff t)
20377 (org-startup-align-all-tables nil))
20378 (when (boundp 'org-table-coordinate-overlays)
20379 (mapc 'delete-overlay org-table-coordinate-overlays)
20380 (setq org-table-coordinate-overlays nil))
20381 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20382 (message "Local setup has been refreshed"))
20383 (plain-list
20384 ;; At a plain list, with a double C-u argument, set
20385 ;; checkboxes of each item to "[-]", whereas a single one
20386 ;; will toggle their presence according to the state of the
20387 ;; first item in the list. Without an argument, repair the
20388 ;; list.
20389 (let* ((begin (org-element-property :contents-begin context))
20390 (beginm (move-marker (make-marker) begin))
20391 (struct (org-element-property :structure context))
20392 (old-struct (copy-tree struct))
20393 (first-box (save-excursion
20394 (goto-char begin)
20395 (looking-at org-list-full-item-re)
20396 (match-string-no-properties 3)))
20397 (new-box (cond ((equal arg '(16)) "[-]")
20398 ((equal arg '(4)) (unless first-box "[ ]"))
20399 ((equal first-box "[X]") "[ ]")
20400 (t "[X]"))))
20401 (cond
20402 (arg
20403 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20404 (org-list-get-all-items
20405 begin struct (org-list-prevs-alist struct))))
20406 ((and first-box (eq (point) begin))
20407 ;; For convenience, when point is at bol on the first
20408 ;; item of the list and no argument is provided, simply
20409 ;; toggle checkbox of that item, if any.
20410 (org-list-set-checkbox begin struct new-box)))
20411 (org-list-write-struct
20412 struct (org-list-parents-alist struct) old-struct)
20413 (org-update-checkbox-count-maybe)
20414 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20415 ((property-drawer node-property)
20416 (call-interactively 'org-property-action))
20417 ((radio-target target)
20418 (call-interactively 'org-update-radio-target-regexp))
20419 (statistics-cookie
20420 (call-interactively 'org-update-statistics-cookies))
20421 ((table table-cell table-row)
20422 ;; At a table, recalculate every field and align it. Also
20423 ;; send the table if necessary. If the table has
20424 ;; a `table.el' type, just give up. At a table row or
20425 ;; cell, maybe recalculate line but always align table.
20426 (if (eq (org-element-property :type context) 'table.el)
20427 (message "Use C-c ' to edit table.el tables")
20428 (let ((org-enable-table-editor t))
20429 (if (or (eq type 'table)
20430 ;; Check if point is at a TBLFM line.
20431 (and (eq type 'table-row)
20432 (= (point) (org-element-property :end context))))
20433 (save-excursion
20434 (if (org-at-TBLFM-p)
20435 (progn (require 'org-table)
20436 (org-table-calc-current-TBLFM))
20437 (goto-char (org-element-property :contents-begin context))
20438 (org-call-with-arg 'org-table-recalculate (or arg t))
20439 (orgtbl-send-table 'maybe)))
20440 (org-table-maybe-eval-formula)
20441 (cond (arg (call-interactively 'org-table-recalculate))
20442 ((org-table-maybe-recalculate-line))
20443 (t (org-table-align)))))))
20444 (timestamp (org-timestamp-change 0 'day))
20445 (otherwise
20446 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20447 (user-error
20448 "C-c C-c can do nothing useful at this location")))))))))
20450 (defun org-mode-restart ()
20451 (interactive)
20452 (let ((indent-status (org-bound-and-true-p org-indent-mode)))
20453 (funcall major-mode)
20454 (hack-local-variables)
20455 (when (and indent-status (not (org-bound-and-true-p org-indent-mode)))
20456 (org-indent-mode -1)))
20457 (message "%s restarted" major-mode))
20459 (defun org-kill-note-or-show-branches ()
20460 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20461 (interactive)
20462 (if (not org-finish-function)
20463 (progn
20464 (hide-subtree)
20465 (call-interactively 'show-branches))
20466 (let ((org-note-abort t))
20467 (funcall org-finish-function))))
20469 (defun org-open-line (n)
20470 "Insert a new row in tables, call `open-line' elsewhere.
20471 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
20472 (interactive "*p")
20473 (cond
20474 ((not org-special-ctrl-o)
20475 (open-line n))
20476 ((org-at-table-p)
20477 (org-table-insert-row))
20479 (open-line n))))
20481 (defun org-return (&optional indent)
20482 "Goto next table row or insert a newline.
20483 Calls `org-table-next-row' or `newline', depending on context.
20484 See the individual commands for more information."
20485 (interactive)
20486 (let (org-ts-what)
20487 (cond
20488 ((or (bobp) (org-in-src-block-p))
20489 (if indent (newline-and-indent) (newline)))
20490 ((org-at-table-p)
20491 (org-table-justify-field-maybe)
20492 (call-interactively 'org-table-next-row))
20493 ;; when `newline-and-indent' is called within a list, make sure
20494 ;; text moved stays inside the item.
20495 ((and (org-in-item-p) indent)
20496 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20497 (progn
20498 (save-match-data (newline))
20499 (org-indent-line-to (length (match-string 0))))
20500 (let ((ind (org-get-indentation)))
20501 (newline)
20502 (if (org-looking-back org-list-end-re)
20503 (org-indent-line)
20504 (org-indent-line-to ind)))))
20505 ((and org-return-follows-link
20506 (org-at-timestamp-p t)
20507 (not (eq org-ts-what 'after)))
20508 (org-follow-timestamp-link))
20509 ((and org-return-follows-link
20510 (let ((tprop (get-text-property (point) 'face)))
20511 (or (eq tprop 'org-link)
20512 (and (listp tprop) (memq 'org-link tprop)))))
20513 (call-interactively 'org-open-at-point))
20514 ((and (org-at-heading-p)
20515 (looking-at
20516 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20517 (org-show-entry)
20518 (end-of-line 1)
20519 (newline))
20520 (t (if indent (newline-and-indent) (newline))))))
20522 (defun org-return-indent ()
20523 "Goto next table row or insert a newline and indent.
20524 Calls `org-table-next-row' or `newline-and-indent', depending on
20525 context. See the individual commands for more information."
20526 (interactive)
20527 (org-return t))
20529 (defun org-ctrl-c-star ()
20530 "Compute table, or change heading status of lines.
20531 Calls `org-table-recalculate' or `org-toggle-heading',
20532 depending on context."
20533 (interactive)
20534 (cond
20535 ((org-at-table-p)
20536 (call-interactively 'org-table-recalculate))
20538 ;; Convert all lines in region to list items
20539 (call-interactively 'org-toggle-heading))))
20541 (defun org-ctrl-c-minus ()
20542 "Insert separator line in table or modify bullet status of line.
20543 Also turns a plain line or a region of lines into list items.
20544 Calls `org-table-insert-hline', `org-toggle-item', or
20545 `org-cycle-list-bullet', depending on context."
20546 (interactive)
20547 (cond
20548 ((org-at-table-p)
20549 (call-interactively 'org-table-insert-hline))
20550 ((org-region-active-p)
20551 (call-interactively 'org-toggle-item))
20552 ((org-in-item-p)
20553 (call-interactively 'org-cycle-list-bullet))
20555 (call-interactively 'org-toggle-item))))
20557 (defun org-toggle-item (arg)
20558 "Convert headings or normal lines to items, items to normal lines.
20559 If there is no active region, only the current line is considered.
20561 If the first non blank line in the region is a headline, convert
20562 all headlines to items, shifting text accordingly.
20564 If it is an item, convert all items to normal lines.
20566 If it is normal text, change region into a list of items.
20567 With a prefix argument ARG, change the region in a single item."
20568 (interactive "P")
20569 (let ((shift-text
20570 (function
20571 ;; Shift text in current section to IND, from point to END.
20572 ;; The function leaves point to END line.
20573 (lambda (ind end)
20574 (let ((min-i 1000) (end (copy-marker end)))
20575 ;; First determine the minimum indentation (MIN-I) of
20576 ;; the text.
20577 (save-excursion
20578 (catch 'exit
20579 (while (< (point) end)
20580 (let ((i (org-get-indentation)))
20581 (cond
20582 ;; Skip blank lines and inline tasks.
20583 ((looking-at "^[ \t]*$"))
20584 ((looking-at org-outline-regexp-bol))
20585 ;; We can't find less than 0 indentation.
20586 ((zerop i) (throw 'exit (setq min-i 0)))
20587 ((< i min-i) (setq min-i i))))
20588 (forward-line))))
20589 ;; Then indent each line so that a line indented to
20590 ;; MIN-I becomes indented to IND. Ignore blank lines
20591 ;; and inline tasks in the process.
20592 (let ((delta (- ind min-i)))
20593 (while (< (point) end)
20594 (unless (or (looking-at "^[ \t]*$")
20595 (looking-at org-outline-regexp-bol))
20596 (org-indent-line-to (+ (org-get-indentation) delta)))
20597 (forward-line)))))))
20598 (skip-blanks
20599 (function
20600 ;; Return beginning of first non-blank line, starting from
20601 ;; line at POS.
20602 (lambda (pos)
20603 (save-excursion
20604 (goto-char pos)
20605 (skip-chars-forward " \r\t\n")
20606 (point-at-bol)))))
20607 beg end)
20608 ;; Determine boundaries of changes.
20609 (if (org-region-active-p)
20610 (setq beg (funcall skip-blanks (region-beginning))
20611 end (copy-marker (region-end)))
20612 (setq beg (funcall skip-blanks (point-at-bol))
20613 end (copy-marker (point-at-eol))))
20614 ;; Depending on the starting line, choose an action on the text
20615 ;; between BEG and END.
20616 (org-with-limited-levels
20617 (save-excursion
20618 (goto-char beg)
20619 (cond
20620 ;; Case 1. Start at an item: de-itemize. Note that it only
20621 ;; happens when a region is active: `org-ctrl-c-minus'
20622 ;; would call `org-cycle-list-bullet' otherwise.
20623 ((org-at-item-p)
20624 (while (< (point) end)
20625 (when (org-at-item-p)
20626 (skip-chars-forward " \t")
20627 (delete-region (point) (match-end 0)))
20628 (forward-line)))
20629 ;; Case 2. Start at an heading: convert to items.
20630 ((org-at-heading-p)
20631 (let* ((bul (org-list-bullet-string "-"))
20632 (bul-len (length bul))
20633 ;; Indentation of the first heading. It should be
20634 ;; relative to the indentation of its parent, if any.
20635 (start-ind (save-excursion
20636 (cond
20637 ((not org-adapt-indentation) 0)
20638 ((not (outline-previous-heading)) 0)
20639 (t (length (match-string 0))))))
20640 ;; Level of first heading. Further headings will be
20641 ;; compared to it to determine hierarchy in the list.
20642 (ref-level (org-reduced-level (org-outline-level))))
20643 (while (< (point) end)
20644 (let* ((level (org-reduced-level (org-outline-level)))
20645 (delta (max 0 (- level ref-level))))
20646 ;; If current headline is less indented than the first
20647 ;; one, set it as reference, in order to preserve
20648 ;; subtrees.
20649 (when (< level ref-level) (setq ref-level level))
20650 (replace-match bul t t)
20651 (org-indent-line-to (+ start-ind (* delta bul-len)))
20652 ;; Ensure all text down to END (or SECTION-END) belongs
20653 ;; to the newly created item.
20654 (let ((section-end (save-excursion
20655 (or (outline-next-heading) (point)))))
20656 (forward-line)
20657 (funcall shift-text
20658 (+ start-ind (* (1+ delta) bul-len))
20659 (min end section-end)))))))
20660 ;; Case 3. Normal line with ARG: make the first line of region
20661 ;; an item, and shift indentation of others lines to
20662 ;; set them as item's body.
20663 (arg (let* ((bul (org-list-bullet-string "-"))
20664 (bul-len (length bul))
20665 (ref-ind (org-get-indentation)))
20666 (skip-chars-forward " \t")
20667 (insert bul)
20668 (forward-line)
20669 (while (< (point) end)
20670 ;; Ensure that lines less indented than first one
20671 ;; still get included in item body.
20672 (funcall shift-text
20673 (+ ref-ind bul-len)
20674 (min end (save-excursion (or (outline-next-heading)
20675 (point)))))
20676 (forward-line))))
20677 ;; Case 4. Normal line without ARG: turn each non-item line
20678 ;; into an item.
20680 (while (< (point) end)
20681 (unless (or (org-at-heading-p) (org-at-item-p))
20682 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20683 (replace-match
20684 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20685 (forward-line))))))))
20687 (defun org-toggle-heading (&optional nstars)
20688 "Convert headings to normal text, or items or text to headings.
20689 If there is no active region, only convert the current line.
20691 With a \\[universal-argument] prefix, convert the whole list at
20692 point into heading.
20694 In a region:
20696 - If the first non blank line is a headline, remove the stars
20697 from all headlines in the region.
20699 - If it is a normal line, turn each and every normal line (i.e.,
20700 not an heading or an item) in the region into headings. If you
20701 want to convert only the first line of this region, use one
20702 universal prefix argument.
20704 - If it is a plain list item, turn all plain list items into headings.
20706 When converting a line into a heading, the number of stars is chosen
20707 such that the lines become children of the current entry. However,
20708 when a numeric prefix argument is given, its value determines the
20709 number of stars to add."
20710 (interactive "P")
20711 (let ((skip-blanks
20712 (function
20713 ;; Return beginning of first non-blank line, starting from
20714 ;; line at POS.
20715 (lambda (pos)
20716 (save-excursion
20717 (goto-char pos)
20718 (while (org-at-comment-p) (forward-line))
20719 (skip-chars-forward " \r\t\n")
20720 (point-at-bol)))))
20721 beg end toggled)
20722 ;; Determine boundaries of changes. If a universal prefix has
20723 ;; been given, put the list in a region. If region ends at a bol,
20724 ;; do not consider the last line to be in the region.
20726 (when (and current-prefix-arg (org-at-item-p))
20727 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20728 (org-mark-element))
20730 (if (org-region-active-p)
20731 (setq beg (funcall skip-blanks (region-beginning))
20732 end (copy-marker (save-excursion
20733 (goto-char (region-end))
20734 (if (bolp) (point) (point-at-eol)))))
20735 (setq beg (funcall skip-blanks (point-at-bol))
20736 end (copy-marker (point-at-eol))))
20737 ;; Ensure inline tasks don't count as headings.
20738 (org-with-limited-levels
20739 (save-excursion
20740 (goto-char beg)
20741 (cond
20742 ;; Case 1. Started at an heading: de-star headings.
20743 ((org-at-heading-p)
20744 (while (< (point) end)
20745 (when (org-at-heading-p t)
20746 (looking-at org-outline-regexp) (replace-match "")
20747 (setq toggled t))
20748 (forward-line)))
20749 ;; Case 2. Started at an item: change items into headlines.
20750 ;; One star will be added by `org-list-to-subtree'.
20751 ((org-at-item-p)
20752 (let* ((stars (make-string
20753 ;; subtract the star that will be added again by
20754 ;; `org-list-to-subtree'
20755 (if (numberp nstars) (1- nstars)
20756 (or (org-current-level) 0))
20757 ?*))
20758 (add-stars
20759 (cond (nstars "") ; stars from prefix only
20760 ((equal stars "") "") ; before first heading
20761 (org-odd-levels-only "*") ; inside heading, odd
20762 (t "")))) ; inside heading, oddeven
20763 (while (< (point) end)
20764 (when (org-at-item-p)
20765 ;; Pay attention to cases when region ends before list.
20766 (let* ((struct (org-list-struct))
20767 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20768 (save-restriction
20769 (narrow-to-region (point) list-end)
20770 (insert
20771 (org-list-to-subtree
20772 (org-list-parse-list t)
20773 '(:istart (concat stars add-stars (funcall get-stars depth))
20774 :icount (concat stars add-stars (funcall get-stars depth)))))))
20775 (setq toggled t))
20776 (forward-line))))
20777 ;; Case 3. Started at normal text: make every line an heading,
20778 ;; skipping headlines and items.
20779 (t (let* ((stars
20780 (make-string
20781 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20782 (add-stars
20783 (cond (nstars "") ; stars from prefix only
20784 ((equal stars "") "*") ; before first heading
20785 (org-odd-levels-only "**") ; inside heading, odd
20786 (t "*"))) ; inside heading, oddeven
20787 (rpl (concat stars add-stars " "))
20788 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20789 (while (< (point) (if (equal nstars '(4)) lend end))
20790 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20791 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20792 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20793 (forward-line)))))))
20794 (unless toggled (message "Cannot toggle heading from here"))))
20796 (defun org-meta-return (&optional arg)
20797 "Insert a new heading or wrap a region in a table.
20798 Calls `org-insert-heading' or `org-table-wrap-region', depending
20799 on context. See the individual commands for more information."
20800 (interactive "P")
20801 (org-check-before-invisible-edit 'insert)
20802 (or (run-hook-with-args-until-success 'org-metareturn-hook)
20803 (let* ((element (org-element-at-point))
20804 (type (org-element-type element)))
20805 (when (eq type 'table-row)
20806 (setq element (org-element-property :parent element))
20807 (setq type 'table))
20808 (if (and (eq type 'table)
20809 (eq (org-element-property :type element) 'org)
20810 (>= (point) (org-element-property :contents-begin element))
20811 (< (point) (org-element-property :contents-end element)))
20812 (call-interactively 'org-table-wrap-region)
20813 (call-interactively 'org-insert-heading)))))
20815 ;;; Menu entries
20817 (defsubst org-in-subtree-not-table-p ()
20818 "Are we in a subtree and not in a table?"
20819 (and (not (org-before-first-heading-p))
20820 (not (org-at-table-p))))
20822 ;; Define the Org-mode menus
20823 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20824 '("Tbl"
20825 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20826 ["Next Field" org-cycle (org-at-table-p)]
20827 ["Previous Field" org-shifttab (org-at-table-p)]
20828 ["Next Row" org-return (org-at-table-p)]
20829 "--"
20830 ["Blank Field" org-table-blank-field (org-at-table-p)]
20831 ["Edit Field" org-table-edit-field (org-at-table-p)]
20832 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20833 "--"
20834 ("Column"
20835 ["Move Column Left" org-metaleft (org-at-table-p)]
20836 ["Move Column Right" org-metaright (org-at-table-p)]
20837 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20838 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20839 ("Row"
20840 ["Move Row Up" org-metaup (org-at-table-p)]
20841 ["Move Row Down" org-metadown (org-at-table-p)]
20842 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20843 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20844 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20845 "--"
20846 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20847 ("Rectangle"
20848 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20849 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20850 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20851 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20852 "--"
20853 ("Calculate"
20854 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20855 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20856 ["Edit Formulas" org-edit-special (org-at-table-p)]
20857 "--"
20858 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20859 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20860 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20861 "--"
20862 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20863 "--"
20864 ["Sum Column/Rectangle" org-table-sum
20865 (or (org-at-table-p) (org-region-active-p))]
20866 ["Which Column?" org-table-current-column (org-at-table-p)])
20867 ["Debug Formulas"
20868 org-table-toggle-formula-debugger
20869 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20870 ["Show Col/Row Numbers"
20871 org-table-toggle-coordinate-overlays
20872 :style toggle
20873 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20874 "--"
20875 ["Create" org-table-create (and (not (org-at-table-p))
20876 org-enable-table-editor)]
20877 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20878 ["Import from File" org-table-import (not (org-at-table-p))]
20879 ["Export to File" org-table-export (org-at-table-p)]
20880 "--"
20881 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20883 (easy-menu-define org-org-menu org-mode-map "Org menu"
20884 '("Org"
20885 ("Show/Hide"
20886 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20887 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20888 ["Sparse Tree..." org-sparse-tree t]
20889 ["Reveal Context" org-reveal t]
20890 ["Show All" show-all t]
20891 "--"
20892 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20893 "--"
20894 ["New Heading" org-insert-heading t]
20895 ("Navigate Headings"
20896 ["Up" outline-up-heading t]
20897 ["Next" outline-next-visible-heading t]
20898 ["Previous" outline-previous-visible-heading t]
20899 ["Next Same Level" outline-forward-same-level t]
20900 ["Previous Same Level" outline-backward-same-level t]
20901 "--"
20902 ["Jump" org-goto t])
20903 ("Edit Structure"
20904 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20905 "--"
20906 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20907 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20908 "--"
20909 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20910 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20911 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20912 "--"
20913 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20914 "--"
20915 ["Copy visible text" org-copy-visible t]
20916 "--"
20917 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20918 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20919 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20920 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20921 "--"
20922 ["Sort Region/Children" org-sort t]
20923 "--"
20924 ["Convert to odd levels" org-convert-to-odd-levels t]
20925 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20926 ("Editing"
20927 ["Emphasis..." org-emphasize t]
20928 ["Edit Source Example" org-edit-special t]
20929 "--"
20930 ["Footnote new/jump" org-footnote-action t]
20931 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20932 ("Archive"
20933 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20934 "--"
20935 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20936 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20937 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20939 "--"
20940 ("Hyperlinks"
20941 ["Store Link (Global)" org-store-link t]
20942 ["Find existing link to here" org-occur-link-in-agenda-files t]
20943 ["Insert Link" org-insert-link t]
20944 ["Follow Link" org-open-at-point t]
20945 "--"
20946 ["Next link" org-next-link t]
20947 ["Previous link" org-previous-link t]
20948 "--"
20949 ["Descriptive Links"
20950 org-toggle-link-display
20951 :style radio
20952 :selected org-descriptive-links
20954 ["Literal Links"
20955 org-toggle-link-display
20956 :style radio
20957 :selected (not org-descriptive-links)])
20958 "--"
20959 ("TODO Lists"
20960 ["TODO/DONE/-" org-todo t]
20961 ("Select keyword"
20962 ["Next keyword" org-shiftright (org-at-heading-p)]
20963 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20964 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20965 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20966 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20967 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20968 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20969 "--"
20970 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20971 :selected org-enforce-todo-dependencies :style toggle :active t]
20972 "Settings for tree at point"
20973 ["Do Children sequentially" org-toggle-ordered-property :style radio
20974 :selected (org-entry-get nil "ORDERED")
20975 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20976 ["Do Children parallel" org-toggle-ordered-property :style radio
20977 :selected (not (org-entry-get nil "ORDERED"))
20978 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20979 "--"
20980 ["Set Priority" org-priority t]
20981 ["Priority Up" org-shiftup t]
20982 ["Priority Down" org-shiftdown t]
20983 "--"
20984 ["Get news from all feeds" org-feed-update-all t]
20985 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20986 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20987 ("TAGS and Properties"
20988 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20989 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20990 "--"
20991 ["Set property" org-set-property (not (org-before-first-heading-p))]
20992 ["Column view of properties" org-columns t]
20993 ["Insert Column View DBlock" org-insert-columns-dblock t])
20994 ("Dates and Scheduling"
20995 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20996 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20997 ("Change Date"
20998 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20999 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21000 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21001 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21002 ["Compute Time Range" org-evaluate-time-range t]
21003 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21004 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21005 "--"
21006 ["Custom time format" org-toggle-time-stamp-overlays
21007 :style radio :selected org-display-custom-times]
21008 "--"
21009 ["Goto Calendar" org-goto-calendar t]
21010 ["Date from Calendar" org-date-from-calendar t]
21011 "--"
21012 ["Start/Restart Timer" org-timer-start t]
21013 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21014 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21015 ["Insert Timer String" org-timer t]
21016 ["Insert Timer Item" org-timer-item t])
21017 ("Logging work"
21018 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21019 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21020 ["Clock out" org-clock-out t]
21021 ["Clock cancel" org-clock-cancel t]
21022 "--"
21023 ["Mark as default task" org-clock-mark-default-task t]
21024 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21025 ["Goto running clock" org-clock-goto t]
21026 "--"
21027 ["Display times" org-clock-display t]
21028 ["Create clock table" org-clock-report t]
21029 "--"
21030 ["Record DONE time"
21031 (progn (setq org-log-done (not org-log-done))
21032 (message "Switching to %s will %s record a timestamp"
21033 (car org-done-keywords)
21034 (if org-log-done "automatically" "not")))
21035 :style toggle :selected org-log-done])
21036 "--"
21037 ["Agenda Command..." org-agenda t]
21038 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21039 ("File List for Agenda")
21040 ("Special views current file"
21041 ["TODO Tree" org-show-todo-tree t]
21042 ["Check Deadlines" org-check-deadlines t]
21043 ["Timeline" org-timeline t]
21044 ["Tags/Property tree" org-match-sparse-tree t])
21045 "--"
21046 ["Export/Publish..." org-export-dispatch t]
21047 ("LaTeX"
21048 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21049 :selected org-cdlatex-mode]
21050 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21051 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21052 ["Modify math symbol" org-cdlatex-math-modify
21053 (org-inside-LaTeX-fragment-p)]
21054 ["Insert citation" org-reftex-citation t]
21055 "--"
21056 ["Template for BEAMER" (org-beamer-insert-options-template) t])
21057 "--"
21058 ("MobileOrg"
21059 ["Push Files and Views" org-mobile-push t]
21060 ["Get Captured and Flagged" org-mobile-pull t]
21061 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21062 "--"
21063 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21064 "--"
21065 ("Documentation"
21066 ["Show Version" org-version t]
21067 ["Info Documentation" org-info t])
21068 ("Customize"
21069 ["Browse Org Group" org-customize t]
21070 "--"
21071 ["Expand This Menu" org-create-customize-menu
21072 (fboundp 'customize-menu-create)])
21073 ["Send bug report" org-submit-bug-report t]
21074 "--"
21075 ("Refresh/Reload"
21076 ["Refresh setup current buffer" org-mode-restart t]
21077 ["Reload Org (after update)" org-reload t]
21078 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21081 (defun org-info (&optional node)
21082 "Read documentation for Org-mode in the info system.
21083 With optional NODE, go directly to that node."
21084 (interactive)
21085 (info (format "(org)%s" (or node ""))))
21087 ;;;###autoload
21088 (defun org-submit-bug-report ()
21089 "Submit a bug report on Org-mode via mail.
21091 Don't hesitate to report any problems or inaccurate documentation.
21093 If you don't have setup sending mail from (X)Emacs, please copy the
21094 output buffer into your mail program, as it gives us important
21095 information about your Org-mode version and configuration."
21096 (interactive)
21097 (require 'reporter)
21098 (org-load-modules-maybe)
21099 (org-require-autoloaded-modules)
21100 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21101 (reporter-submit-bug-report
21102 "emacs-orgmode@gnu.org"
21103 (org-version nil 'full)
21104 (let (list)
21105 (save-window-excursion
21106 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21107 (delete-other-windows)
21108 (erase-buffer)
21109 (insert "You are about to submit a bug report to the Org-mode mailing list.
21111 We would like to add your full Org-mode and Outline configuration to the
21112 bug report. This greatly simplifies the work of the maintainer and
21113 other experts on the mailing list.
21115 HOWEVER, some variables you have customized may contain private
21116 information. The names of customers, colleagues, or friends, might
21117 appear in the form of file names, tags, todo states, or search strings.
21118 If you answer yes to the prompt, you might want to check and remove
21119 such private information before sending the email.")
21120 (add-text-properties (point-min) (point-max) '(face org-warning))
21121 (when (yes-or-no-p "Include your Org-mode configuration ")
21122 (mapatoms
21123 (lambda (v)
21124 (and (boundp v)
21125 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21126 (or (and (symbol-value v)
21127 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21128 (and
21129 (get v 'custom-type) (get v 'standard-value)
21130 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21131 (push v list)))))
21132 (kill-buffer (get-buffer "*Warn about privacy*"))
21133 list))
21134 nil nil
21135 "Remember to cover the basics, that is, what you expected to happen and
21136 what in fact did happen. You don't know how to make a good report? See
21138 http://orgmode.org/manual/Feedback.html#Feedback
21140 Your bug report will be posted to the Org-mode mailing list.
21141 ------------------------------------------------------------------------")
21142 (save-excursion
21143 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21144 (replace-match "\\1Bug: \\3 [\\2]")))))
21147 (defun org-install-agenda-files-menu ()
21148 (let ((bl (buffer-list)))
21149 (save-excursion
21150 (while bl
21151 (set-buffer (pop bl))
21152 (if (derived-mode-p 'org-mode) (setq bl nil)))
21153 (when (derived-mode-p 'org-mode)
21154 (easy-menu-change
21155 '("Org") "File List for Agenda"
21156 (append
21157 (list
21158 ["Edit File List" (org-edit-agenda-file-list) t]
21159 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21160 ["Remove Current File from List" org-remove-file t]
21161 ["Cycle through agenda files" org-cycle-agenda-files t]
21162 ["Occur in all agenda files" org-occur-in-agenda-files t]
21163 "--")
21164 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21166 ;;;; Documentation
21168 (defun org-require-autoloaded-modules ()
21169 (interactive)
21170 (mapc 'require
21171 '(org-agenda org-archive org-attach org-clock org-colview org-id
21172 org-table org-timer)))
21174 ;;;###autoload
21175 (defun org-reload (&optional uncompiled)
21176 "Reload all org lisp files.
21177 With prefix arg UNCOMPILED, load the uncompiled versions."
21178 (interactive "P")
21179 (require 'loadhist)
21180 (let* ((org-dir (org-find-library-dir "org"))
21181 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21182 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21183 (remove-re (mapconcat 'identity
21184 (mapcar (lambda (f) (concat "^" f "$"))
21185 (list (if (featurep 'xemacs)
21186 "org-colview"
21187 "org-colview-xemacs")
21188 "org" "org-loaddefs" "org-version"))
21189 "\\|"))
21190 (feats (delete-dups
21191 (mapcar 'file-name-sans-extension
21192 (mapcar 'file-name-nondirectory
21193 (delq nil
21194 (mapcar 'feature-file
21195 features))))))
21196 (lfeat (append
21197 (sort
21198 (setq feats
21199 (delq nil (mapcar
21200 (lambda (f)
21201 (if (and (string-match feature-re f)
21202 (not (string-match remove-re f)))
21203 f nil))
21204 feats)))
21205 'string-lessp)
21206 (list "org-version" "org")))
21207 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21208 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21209 load-uncore load-misses)
21210 (setq load-misses
21211 (delq 't
21212 (mapcar (lambda (f)
21213 (or (org-load-noerror-mustsuffix (concat org-dir f))
21214 (and (string= org-dir contrib-dir)
21215 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21216 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21217 (add-to-list 'load-uncore f 'append)
21220 lfeat)))
21221 (if load-uncore
21222 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21223 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21224 (if load-misses
21225 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21226 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21227 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21229 ;;;###autoload
21230 (defun org-customize ()
21231 "Call the customize function with org as argument."
21232 (interactive)
21233 (org-load-modules-maybe)
21234 (org-require-autoloaded-modules)
21235 (customize-browse 'org))
21237 (defun org-create-customize-menu ()
21238 "Create a full customization menu for Org-mode, insert it into the menu."
21239 (interactive)
21240 (org-load-modules-maybe)
21241 (org-require-autoloaded-modules)
21242 (if (fboundp 'customize-menu-create)
21243 (progn
21244 (easy-menu-change
21245 '("Org") "Customize"
21246 `(["Browse Org group" org-customize t]
21247 "--"
21248 ,(customize-menu-create 'org)
21249 ["Set" Custom-set t]
21250 ["Save" Custom-save t]
21251 ["Reset to Current" Custom-reset-current t]
21252 ["Reset to Saved" Custom-reset-saved t]
21253 ["Reset to Standard Settings" Custom-reset-standard t]))
21254 (message "\"Org\"-menu now contains full customization menu"))
21255 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21257 ;;;; Miscellaneous stuff
21259 ;;; Generally useful functions
21261 (defun org-get-at-bol (property)
21262 "Get text property PROPERTY at beginning of line."
21263 (get-text-property (point-at-bol) property))
21265 (defun org-find-text-property-in-string (prop s)
21266 "Return the first non-nil value of property PROP in string S."
21267 (or (get-text-property 0 prop s)
21268 (get-text-property (or (next-single-property-change 0 prop s) 0)
21269 prop s)))
21271 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21272 "Display the given MESSAGE as a warning."
21273 (if (fboundp 'display-warning)
21274 (display-warning 'org message
21275 (if (featurep 'xemacs) 'warning :warning))
21276 (let ((buf (get-buffer-create "*Org warnings*")))
21277 (with-current-buffer buf
21278 (goto-char (point-max))
21279 (insert "Warning (Org): " message)
21280 (unless (bolp)
21281 (newline)))
21282 (display-buffer buf)
21283 (sit-for 0))))
21285 (defun org-eval (form)
21286 "Eval FORM and return result."
21287 (condition-case error
21288 (eval form)
21289 (error (format "%%![Error: %s]" error))))
21291 (defun org-in-clocktable-p ()
21292 "Check if the cursor is in a clocktable."
21293 (let ((pos (point)) start)
21294 (save-excursion
21295 (end-of-line 1)
21296 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21297 (setq start (match-beginning 0))
21298 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21299 (>= (match-end 0) pos)
21300 start))))
21302 (defun org-in-commented-line ()
21303 "Is point in a line starting with `#'?"
21304 (equal (char-after (point-at-bol)) ?#))
21306 (defun org-in-indented-comment-line ()
21307 "Is point in a line starting with `#' after some white space?"
21308 (save-excursion
21309 (save-match-data
21310 (goto-char (point-at-bol))
21311 (looking-at "[ \t]*#"))))
21313 (defun org-in-verbatim-emphasis ()
21314 (save-match-data
21315 (and (org-in-regexp org-emph-re 2)
21316 (>= (point) (match-beginning 3))
21317 (<= (point) (match-end 4))
21318 (member (match-string 3) '("=" "~")))))
21320 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21321 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21322 (if (and marker (marker-buffer marker)
21323 (buffer-live-p (marker-buffer marker)))
21324 (progn
21325 (org-pop-to-buffer-same-window (marker-buffer marker))
21326 (if (or (> marker (point-max)) (< marker (point-min)))
21327 (widen))
21328 (goto-char marker)
21329 (org-show-context 'org-goto))
21330 (if bookmark
21331 (bookmark-jump bookmark)
21332 (error "Cannot find location"))))
21334 (defun org-quote-csv-field (s)
21335 "Quote field for inclusion in CSV material."
21336 (if (string-match "[\",]" s)
21337 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21340 (defun org-force-self-insert (N)
21341 "Needed to enforce self-insert under remapping."
21342 (interactive "p")
21343 (self-insert-command N))
21345 (defun org-string-width (s)
21346 "Compute width of string, ignoring invisible characters.
21347 This ignores character with invisibility property `org-link', and also
21348 characters with property `org-cwidth', because these will become invisible
21349 upon the next fontification round."
21350 (let (b l)
21351 (when (or (eq t buffer-invisibility-spec)
21352 (assq 'org-link buffer-invisibility-spec))
21353 (while (setq b (text-property-any 0 (length s)
21354 'invisible 'org-link s))
21355 (setq s (concat (substring s 0 b)
21356 (substring s (or (next-single-property-change
21357 b 'invisible s) (length s)))))))
21358 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21359 (setq s (concat (substring s 0 b)
21360 (substring s (or (next-single-property-change
21361 b 'org-cwidth s) (length s))))))
21362 (setq l (string-width s) b -1)
21363 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21364 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21367 (defun org-shorten-string (s maxlength)
21368 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21369 If the string is shorter or has length MAXLENGTH, just return the
21370 original string. If it is longer, the functions finds a space in the
21371 string, breaks this string off at that locations and adds three dots
21372 as ellipsis. Including the ellipsis, the string will not be longer
21373 than MAXLENGTH. If finding a good breaking point in the string does
21374 not work, the string is just chopped off in the middle of a word
21375 if necessary."
21376 (if (<= (length s) maxlength)
21378 (let* ((n (max (- maxlength 4) 1))
21379 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21380 (if (string-match re s)
21381 (concat (match-string 1 s) "...")
21382 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21384 (defun org-get-indentation (&optional line)
21385 "Get the indentation of the current line, interpreting tabs.
21386 When LINE is given, assume it represents a line and compute its indentation."
21387 (if line
21388 (if (string-match "^ *" (org-remove-tabs line))
21389 (match-end 0))
21390 (save-excursion
21391 (beginning-of-line 1)
21392 (skip-chars-forward " \t")
21393 (current-column))))
21395 (defun org-get-string-indentation (s)
21396 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21397 (let ((n -1) (i 0) (w tab-width) c)
21398 (catch 'exit
21399 (while (< (setq n (1+ n)) (length s))
21400 (setq c (aref s n))
21401 (cond ((= c ?\ ) (setq i (1+ i)))
21402 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21403 (t (throw 'exit t)))))
21406 (defun org-remove-tabs (s &optional width)
21407 "Replace tabulators in S with spaces.
21408 Assumes that s is a single line, starting in column 0."
21409 (setq width (or width tab-width))
21410 (while (string-match "\t" s)
21411 (setq s (replace-match
21412 (make-string
21413 (- (* width (/ (+ (match-beginning 0) width) width))
21414 (match-beginning 0)) ?\ )
21415 t t s)))
21418 (defun org-fix-indentation (line ind)
21419 "Fix indentation in LINE.
21420 IND is a cons cell with target and minimum indentation.
21421 If the current indentation in LINE is smaller than the minimum,
21422 leave it alone. If it is larger than ind, set it to the target."
21423 (let* ((l (org-remove-tabs line))
21424 (i (org-get-indentation l))
21425 (i1 (car ind)) (i2 (cdr ind)))
21426 (if (>= i i2) (setq l (substring line i2)))
21427 (if (> i1 0)
21428 (concat (make-string i1 ?\ ) l)
21429 l)))
21431 (defun org-remove-indentation (code &optional n)
21432 "Remove the maximum common indentation from the lines in CODE.
21433 N may optionally be the number of spaces to remove."
21434 (with-temp-buffer
21435 (insert code)
21436 (org-do-remove-indentation n)
21437 (buffer-string)))
21439 (defun org-do-remove-indentation (&optional n)
21440 "Remove the maximum common indentation from the buffer."
21441 (untabify (point-min) (point-max))
21442 (let ((min 10000) re)
21443 (if n
21444 (setq min n)
21445 (goto-char (point-min))
21446 (while (re-search-forward "^ *[^ \n]" nil t)
21447 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21448 (unless (or (= min 0) (= min 10000))
21449 (setq re (format "^ \\{%d\\}" min))
21450 (goto-char (point-min))
21451 (while (re-search-forward re nil t)
21452 (replace-match "")
21453 (end-of-line 1))
21454 min)))
21456 (defun org-fill-template (template alist)
21457 "Find each %key of ALIST in TEMPLATE and replace it."
21458 (let ((case-fold-search nil)
21459 entry key value)
21460 (setq alist (sort (copy-sequence alist)
21461 (lambda (a b) (< (length (car a)) (length (car b))))))
21462 (while (setq entry (pop alist))
21463 (setq template
21464 (replace-regexp-in-string
21465 (concat "%" (regexp-quote (car entry)))
21466 (or (cdr entry) "") template t t)))
21467 template))
21469 (defun org-base-buffer (buffer)
21470 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21471 (if (not buffer)
21472 buffer
21473 (or (buffer-base-buffer buffer)
21474 buffer)))
21476 (defun org-trim (s)
21477 "Remove whitespace at beginning and end of string."
21478 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
21479 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
21482 (defun org-wrap (string &optional width lines)
21483 "Wrap string to either a number of lines, or a width in characters.
21484 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21485 that costs. If there is a word longer than WIDTH, the text is actually
21486 wrapped to the length of that word.
21487 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21488 many lines, whatever width that takes.
21489 The return value is a list of lines, without newlines at the end."
21490 (let* ((words (org-split-string string "[ \t\n]+"))
21491 (maxword (apply 'max (mapcar 'org-string-width words)))
21492 w ll)
21493 (cond (width
21494 (org-do-wrap words (max maxword width)))
21495 (lines
21496 (setq w maxword)
21497 (setq ll (org-do-wrap words maxword))
21498 (if (<= (length ll) lines)
21500 (setq ll words)
21501 (while (> (length ll) lines)
21502 (setq w (1+ w))
21503 (setq ll (org-do-wrap words w)))
21504 ll))
21505 (t (error "Cannot wrap this")))))
21507 (defun org-do-wrap (words width)
21508 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21509 (let (lines line)
21510 (while words
21511 (setq line (pop words))
21512 (while (and words (< (+ (length line) (length (car words))) width))
21513 (setq line (concat line " " (pop words))))
21514 (setq lines (push line lines)))
21515 (nreverse lines)))
21517 (defun org-split-string (string &optional separators)
21518 "Splits STRING into substrings at SEPARATORS.
21519 No empty strings are returned if there are matches at the beginning
21520 and end of string."
21521 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21522 (start 0)
21523 notfirst
21524 (list nil))
21525 (while (and (string-match rexp string
21526 (if (and notfirst
21527 (= start (match-beginning 0))
21528 (< start (length string)))
21529 (1+ start) start))
21530 (< (match-beginning 0) (length string)))
21531 (setq notfirst t)
21532 (or (eq (match-beginning 0) 0)
21533 (and (eq (match-beginning 0) (match-end 0))
21534 (eq (match-beginning 0) start))
21535 (setq list
21536 (cons (substring string start (match-beginning 0))
21537 list)))
21538 (setq start (match-end 0)))
21539 (or (eq start (length string))
21540 (setq list
21541 (cons (substring string start)
21542 list)))
21543 (nreverse list)))
21545 (defun org-quote-vert (s)
21546 "Replace \"|\" with \"\\vert\"."
21547 (while (string-match "|" s)
21548 (setq s (replace-match "\\vert" t t s)))
21551 (defun org-uuidgen-p (s)
21552 "Is S an ID created by UUIDGEN?"
21553 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21555 (defun org-in-src-block-p (&optional inside)
21556 "Whether point is in a code source block.
21557 When INSIDE is non-nil, don't consider we are within a src block
21558 when point is at #+BEGIN_SRC or #+END_SRC."
21559 (let ((case-fold-search t) ov)
21560 (or (and (setq ov (overlays-at (point)))
21561 (memq 'org-block-background
21562 (overlay-properties (car ov))))
21563 (and (not inside)
21564 (save-match-data
21565 (save-excursion
21566 (beginning-of-line)
21567 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21569 (defun org-context ()
21570 "Return a list of contexts of the current cursor position.
21571 If several contexts apply, all are returned.
21572 Each context entry is a list with a symbol naming the context, and
21573 two positions indicating start and end of the context. Possible
21574 contexts are:
21576 :headline anywhere in a headline
21577 :headline-stars on the leading stars in a headline
21578 :todo-keyword on a TODO keyword (including DONE) in a headline
21579 :tags on the TAGS in a headline
21580 :priority on the priority cookie in a headline
21581 :item on the first line of a plain list item
21582 :item-bullet on the bullet/number of a plain list item
21583 :checkbox on the checkbox in a plain list item
21584 :table in an org-mode table
21585 :table-special on a special filed in a table
21586 :table-table in a table.el table
21587 :clocktable in a clocktable
21588 :src-block in a source block
21589 :link on a hyperlink
21590 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21591 :target on a <<target>>
21592 :radio-target on a <<<radio-target>>>
21593 :latex-fragment on a LaTeX fragment
21594 :latex-preview on a LaTeX fragment with overlaid preview image
21596 This function expects the position to be visible because it uses font-lock
21597 faces as a help to recognize the following contexts: :table-special, :link,
21598 and :keyword."
21599 (let* ((f (get-text-property (point) 'face))
21600 (faces (if (listp f) f (list f)))
21601 (case-fold-search t)
21602 (p (point)) clist o)
21603 ;; First the large context
21604 (cond
21605 ((org-at-heading-p t)
21606 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21607 (when (progn
21608 (beginning-of-line 1)
21609 (looking-at org-todo-line-tags-regexp))
21610 (push (org-point-in-group p 1 :headline-stars) clist)
21611 (push (org-point-in-group p 2 :todo-keyword) clist)
21612 (push (org-point-in-group p 4 :tags) clist))
21613 (goto-char p)
21614 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21615 (if (looking-at "\\[#[A-Z0-9]\\]")
21616 (push (org-point-in-group p 0 :priority) clist)))
21618 ((org-at-item-p)
21619 (push (org-point-in-group p 2 :item-bullet) clist)
21620 (push (list :item (point-at-bol)
21621 (save-excursion (org-end-of-item) (point)))
21622 clist)
21623 (and (org-at-item-checkbox-p)
21624 (push (org-point-in-group p 0 :checkbox) clist)))
21626 ((org-at-table-p)
21627 (push (list :table (org-table-begin) (org-table-end)) clist)
21628 (if (memq 'org-formula faces)
21629 (push (list :table-special
21630 (previous-single-property-change p 'face)
21631 (next-single-property-change p 'face)) clist)))
21632 ((org-at-table-p 'any)
21633 (push (list :table-table) clist)))
21634 (goto-char p)
21636 (let ((case-fold-search t))
21637 ;; New the "medium" contexts: clocktables, source blocks
21638 (cond ((org-in-clocktable-p)
21639 (push (list :clocktable
21640 (and (or (looking-at "#\\+BEGIN: clocktable")
21641 (search-backward "#+BEGIN: clocktable" nil t))
21642 (match-beginning 0))
21643 (and (re-search-forward "#\\+END:?" nil t)
21644 (match-end 0))) clist))
21645 ((org-in-src-block-p)
21646 (push (list :src-block
21647 (and (or (looking-at "#\\+BEGIN_SRC")
21648 (search-backward "#+BEGIN_SRC" nil t))
21649 (match-beginning 0))
21650 (and (search-forward "#+END_SRC" nil t)
21651 (match-beginning 0))) clist))))
21652 (goto-char p)
21654 ;; Now the small context
21655 (cond
21656 ((org-at-timestamp-p)
21657 (push (org-point-in-group p 0 :timestamp) clist))
21658 ((memq 'org-link faces)
21659 (push (list :link
21660 (previous-single-property-change p 'face)
21661 (next-single-property-change p 'face)) clist))
21662 ((memq 'org-special-keyword faces)
21663 (push (list :keyword
21664 (previous-single-property-change p 'face)
21665 (next-single-property-change p 'face)) clist))
21666 ((org-at-target-p)
21667 (push (org-point-in-group p 0 :target) clist)
21668 (goto-char (1- (match-beginning 0)))
21669 (if (looking-at org-radio-target-regexp)
21670 (push (org-point-in-group p 0 :radio-target) clist))
21671 (goto-char p))
21672 ((setq o (car (delq nil
21673 (mapcar
21674 (lambda (x)
21675 (if (memq x org-latex-fragment-image-overlays) x))
21676 (overlays-at (point))))))
21677 (push (list :latex-fragment
21678 (overlay-start o) (overlay-end o)) clist)
21679 (push (list :latex-preview
21680 (overlay-start o) (overlay-end o)) clist))
21681 ((org-inside-LaTeX-fragment-p)
21682 ;; FIXME: positions wrong.
21683 (push (list :latex-fragment (point) (point)) clist)))
21685 (setq clist (nreverse (delq nil clist)))
21686 clist))
21688 ;; FIXME: Compare with at-regexp-p Do we need both?
21689 (defun org-in-regexp (re &optional nlines visually)
21690 "Check if point is inside a match of regexp.
21691 Normally only the current line is checked, but you can include NLINES extra
21692 lines both before and after point into the search.
21693 If VISUALLY is set, require that the cursor is not after the match but
21694 really on, so that the block visually is on the match."
21695 (catch 'exit
21696 (let ((pos (point))
21697 (eol (point-at-eol (+ 1 (or nlines 0))))
21698 (inc (if visually 1 0)))
21699 (save-excursion
21700 (beginning-of-line (- 1 (or nlines 0)))
21701 (while (re-search-forward re eol t)
21702 (if (and (<= (match-beginning 0) pos)
21703 (>= (+ inc (match-end 0)) pos))
21704 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21706 (defun org-at-regexp-p (regexp)
21707 "Is point inside a match of REGEXP in the current line?"
21708 (catch 'exit
21709 (save-excursion
21710 (let ((pos (point)) (end (point-at-eol)))
21711 (beginning-of-line 1)
21712 (while (re-search-forward regexp end t)
21713 (if (and (<= (match-beginning 0) pos)
21714 (>= (match-end 0) pos))
21715 (throw 'exit t)))
21716 nil))))
21718 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21719 "Non-nil when point is between matches of START-RE and END-RE.
21721 Also return a non-nil value when point is on one of the matches.
21723 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21724 buffer positions. Default values are the positions of headlines
21725 surrounding the point.
21727 The functions returns a cons cell whose car (resp. cdr) is the
21728 position before START-RE (resp. after END-RE)."
21729 (save-match-data
21730 (let ((pos (point))
21731 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21732 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21733 beg end)
21734 (save-excursion
21735 ;; Point is on a block when on START-RE or if START-RE can be
21736 ;; found before it...
21737 (and (or (org-at-regexp-p start-re)
21738 (re-search-backward start-re limit-up t))
21739 (setq beg (match-beginning 0))
21740 ;; ... and END-RE after it...
21741 (goto-char (match-end 0))
21742 (re-search-forward end-re limit-down t)
21743 (> (setq end (match-end 0)) pos)
21744 ;; ... without another START-RE in-between.
21745 (goto-char (match-beginning 0))
21746 (not (re-search-backward start-re (1+ beg) t))
21747 ;; Return value.
21748 (cons beg end))))))
21750 (defun org-in-block-p (names)
21751 "Non-nil when point belongs to a block whose name belongs to NAMES.
21753 NAMES is a list of strings containing names of blocks.
21755 Return first block name matched, or nil. Beware that in case of
21756 nested blocks, the returned name may not belong to the closest
21757 block from point."
21758 (save-match-data
21759 (catch 'exit
21760 (let ((case-fold-search t)
21761 (lim-up (save-excursion (outline-previous-heading)))
21762 (lim-down (save-excursion (outline-next-heading))))
21763 (mapc (lambda (name)
21764 (let ((n (regexp-quote name)))
21765 (when (org-between-regexps-p
21766 (concat "^[ \t]*#\\+begin_" n)
21767 (concat "^[ \t]*#\\+end_" n)
21768 lim-up lim-down)
21769 (throw 'exit n))))
21770 names))
21771 nil)))
21773 (defun org-in-drawer-p ()
21774 "Is point within a drawer?"
21775 (save-match-data
21776 (let ((case-fold-search t)
21777 (lim-up (save-excursion (outline-previous-heading)))
21778 (lim-down (save-excursion (outline-next-heading))))
21779 (org-between-regexps-p
21780 (concat "^[ \t]*:" (regexp-opt org-drawers) ":")
21781 "^[ \t]*:end:.*$"
21782 lim-up lim-down))))
21784 (defun org-occur-in-agenda-files (regexp &optional nlines)
21785 "Call `multi-occur' with buffers for all agenda files."
21786 (interactive "sOrg-files matching: \np")
21787 (let* ((files (org-agenda-files))
21788 (tnames (mapcar 'file-truename files))
21789 (extra org-agenda-text-search-extra-files)
21791 (when (eq (car extra) 'agenda-archives)
21792 (setq extra (cdr extra))
21793 (setq files (org-add-archive-files files)))
21794 (while (setq f (pop extra))
21795 (unless (member (file-truename f) tnames)
21796 (add-to-list 'files f 'append)
21797 (add-to-list 'tnames (file-truename f) 'append)))
21798 (multi-occur
21799 (mapcar (lambda (x)
21800 (with-current-buffer
21801 (or (get-file-buffer x) (find-file-noselect x))
21802 (widen)
21803 (current-buffer)))
21804 files)
21805 regexp)))
21807 (if (boundp 'occur-mode-find-occurrence-hook)
21808 ;; Emacs 23
21809 (add-hook 'occur-mode-find-occurrence-hook
21810 (lambda ()
21811 (when (derived-mode-p 'org-mode)
21812 (org-reveal))))
21813 ;; Emacs 22
21814 (defadvice occur-mode-goto-occurrence
21815 (after org-occur-reveal activate)
21816 (and (derived-mode-p 'org-mode) (org-reveal)))
21817 (defadvice occur-mode-goto-occurrence-other-window
21818 (after org-occur-reveal activate)
21819 (and (derived-mode-p 'org-mode) (org-reveal)))
21820 (defadvice occur-mode-display-occurrence
21821 (after org-occur-reveal activate)
21822 (when (derived-mode-p 'org-mode)
21823 (let ((pos (occur-mode-find-occurrence)))
21824 (with-current-buffer (marker-buffer pos)
21825 (save-excursion
21826 (goto-char pos)
21827 (org-reveal)))))))
21829 (defun org-occur-link-in-agenda-files ()
21830 "Create a link and search for it in the agendas.
21831 The link is not stored in `org-stored-links', it is just created
21832 for the search purpose."
21833 (interactive)
21834 (let ((link (condition-case nil
21835 (org-store-link nil)
21836 (error "Unable to create a link to here"))))
21837 (org-occur-in-agenda-files (regexp-quote link))))
21839 (defun org-reverse-string (string)
21840 "Return the reverse of STRING."
21841 (apply 'string (reverse (string-to-list string))))
21843 ;; defsubst org-uniquify must be defined before first use
21845 (defun org-uniquify-alist (alist)
21846 "Merge elements of ALIST with the same key.
21848 For example, in this alist:
21850 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
21851 => '((a 1 3) (b 2))
21853 merge (a 1) and (a 3) into (a 1 3).
21855 The function returns the new ALIST."
21856 (let (rtn)
21857 (mapc
21858 (lambda (e)
21859 (let (n)
21860 (if (not (assoc (car e) rtn))
21861 (push e rtn)
21862 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
21863 (setq rtn (assq-delete-all (car e) rtn))
21864 (push n rtn))))
21865 alist)
21866 rtn))
21868 (defun org-delete-all (elts list)
21869 "Remove all elements in ELTS from LIST."
21870 (while elts
21871 (setq list (delete (pop elts) list)))
21872 list)
21874 (defun org-count (cl-item cl-seq)
21875 "Count the number of occurrences of ITEM in SEQ.
21876 Taken from `count' in cl-seq.el with all keyword arguments removed."
21877 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21878 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21879 (while (< cl-start cl-end)
21880 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21881 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21882 (setq cl-start (1+ cl-start)))
21883 cl-count))
21885 (defun org-remove-if (predicate seq)
21886 "Remove everything from SEQ that fulfills PREDICATE."
21887 (let (res e)
21888 (while seq
21889 (setq e (pop seq))
21890 (if (not (funcall predicate e)) (push e res)))
21891 (nreverse res)))
21893 (defun org-remove-if-not (predicate seq)
21894 "Remove everything from SEQ that does not fulfill PREDICATE."
21895 (let (res e)
21896 (while seq
21897 (setq e (pop seq))
21898 (if (funcall predicate e) (push e res)))
21899 (nreverse res)))
21901 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21902 "Reduce two-argument FUNCTION across SEQ.
21903 Taken from `reduce' in cl-seq.el with all keyword arguments but
21904 \":initial-value\" removed."
21905 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21906 (cadr (memq :initial-value cl-keys)))
21907 (cl-seq (pop cl-seq))
21908 (t (funcall cl-func)))))
21909 (while cl-seq
21910 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21911 cl-accum))
21913 (defun org-every (pred seq)
21914 "Return true if PREDICATE is true of every element of SEQ.
21915 Adapted from `every' in cl.el."
21916 (catch 'org-every
21917 (mapc (lambda (e) (unless (funcall pred e) (throw 'org-every nil))) seq)
21920 (defun org-some (pred seq)
21921 "Return true if PREDICATE is true of any element of SEQ.
21922 Adapted from `some' in cl.el."
21923 (catch 'org-some
21924 (mapc (lambda (e) (when (funcall pred e) (throw 'org-some t))) seq)
21925 nil))
21927 (defun org-back-over-empty-lines ()
21928 "Move backwards over whitespace, to the beginning of the first empty line.
21929 Returns the number of empty lines passed."
21930 (let ((pos (point)))
21931 (if (cdr (assoc 'heading org-blank-before-new-entry))
21932 (skip-chars-backward " \t\n\r")
21933 (unless (eobp)
21934 (forward-line -1)))
21935 (beginning-of-line 2)
21936 (goto-char (min (point) pos))
21937 (count-lines (point) pos)))
21939 (defun org-skip-whitespace ()
21940 (skip-chars-forward " \t\n\r"))
21942 (defun org-point-in-group (point group &optional context)
21943 "Check if POINT is in match-group GROUP.
21944 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21945 match. If the match group does not exist or point is not inside it,
21946 return nil."
21947 (and (match-beginning group)
21948 (>= point (match-beginning group))
21949 (<= point (match-end group))
21950 (if context
21951 (list context (match-beginning group) (match-end group))
21952 t)))
21954 (defun org-switch-to-buffer-other-window (&rest args)
21955 "Switch to buffer in a second window on the current frame.
21956 In particular, do not allow pop-up frames.
21957 Returns the newly created buffer."
21958 (org-no-popups
21959 (apply 'switch-to-buffer-other-window args)))
21961 (defun org-combine-plists (&rest plists)
21962 "Create a single property list from all plists in PLISTS.
21963 The process starts by copying the first list, and then setting properties
21964 from the other lists. Settings in the last list are the most significant
21965 ones and overrule settings in the other lists."
21966 (let ((rtn (copy-sequence (pop plists)))
21967 p v ls)
21968 (while plists
21969 (setq ls (pop plists))
21970 (while ls
21971 (setq p (pop ls) v (pop ls))
21972 (setq rtn (plist-put rtn p v))))
21973 rtn))
21975 (defun org-replace-escapes (string table)
21976 "Replace %-escapes in STRING with values in TABLE.
21977 TABLE is an association list with keys like \"%a\" and string values.
21978 The sequences in STRING may contain normal field width and padding information,
21979 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21980 so values can contain further %-escapes if they are define later in TABLE."
21981 (let ((tbl (copy-alist table))
21982 (case-fold-search nil)
21983 (pchg 0)
21984 e re rpl)
21985 (while (setq e (pop tbl))
21986 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21987 (when (and (cdr e) (string-match re (cdr e)))
21988 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21989 (safe "SREF"))
21990 (add-text-properties 0 3 (list 'sref sref) safe)
21991 (setcdr e (replace-match safe t t (cdr e)))))
21992 (while (string-match re string)
21993 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21994 (cdr e)))
21995 (setq string (replace-match rpl t t string))))
21996 (while (setq pchg (next-property-change pchg string))
21997 (let ((sref (get-text-property pchg 'sref string)))
21998 (when (and sref (string-match "SREF" string pchg))
21999 (setq string (replace-match sref t t string)))))
22000 string))
22002 (defun org-sublist (list start end)
22003 "Return a section of LIST, from START to END.
22004 Counting starts at 1."
22005 (let (rtn (c start))
22006 (setq list (nthcdr (1- start) list))
22007 (while (and list (<= c end))
22008 (push (pop list) rtn)
22009 (setq c (1+ c)))
22010 (nreverse rtn)))
22012 (defun org-find-base-buffer-visiting (file)
22013 "Like `find-buffer-visiting' but always return the base buffer and
22014 not an indirect buffer."
22015 (let ((buf (or (get-file-buffer file)
22016 (find-buffer-visiting file))))
22017 (if buf
22018 (or (buffer-base-buffer buf) buf)
22019 nil)))
22021 (defun org-image-file-name-regexp (&optional extensions)
22022 "Return regexp matching the file names of images.
22023 If EXTENSIONS is given, only match these."
22024 (if (and (not extensions) (fboundp 'image-file-name-regexp))
22025 (image-file-name-regexp)
22026 (let ((image-file-name-extensions
22027 (or extensions
22028 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
22029 "xbm" "xpm" "pbm" "pgm" "ppm"))))
22030 (concat "\\."
22031 (regexp-opt (nconc (mapcar 'upcase
22032 image-file-name-extensions)
22033 image-file-name-extensions)
22035 "\\'"))))
22037 (defun org-file-image-p (file &optional extensions)
22038 "Return non-nil if FILE is an image."
22039 (save-match-data
22040 (string-match (org-image-file-name-regexp extensions) file)))
22042 (defun org-get-cursor-date (&optional with-time)
22043 "Return the date at cursor in as a time.
22044 This works in the calendar and in the agenda, anywhere else it just
22045 returns the current time.
22046 If WITH-TIME is non-nil, returns the time of the event at point (in
22047 the agenda) or the current time of the day."
22048 (let (date day defd tp tm hod mod)
22049 (when with-time
22050 (setq tp (get-text-property (point) 'time))
22051 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22052 (setq hod (string-to-number (match-string 1 tp))
22053 mod (string-to-number (match-string 2 tp))))
22054 (or tp (setq hod (nth 2 (decode-time (current-time)))
22055 mod (nth 1 (decode-time (current-time))))))
22056 (cond
22057 ((eq major-mode 'calendar-mode)
22058 (setq date (calendar-cursor-to-date)
22059 defd (encode-time 0 (or mod 0) (or hod 0)
22060 (nth 1 date) (nth 0 date) (nth 2 date))))
22061 ((eq major-mode 'org-agenda-mode)
22062 (setq day (get-text-property (point) 'day))
22063 (if day
22064 (setq date (calendar-gregorian-from-absolute day)
22065 defd (encode-time 0 (or mod 0) (or hod 0)
22066 (nth 1 date) (nth 0 date) (nth 2 date))))))
22067 (or defd (current-time))))
22069 (defun org-mark-subtree (&optional up)
22070 "Mark the current subtree.
22071 This puts point at the start of the current subtree, and mark at
22072 the end. If a numeric prefix UP is given, move up into the
22073 hierarchy of headlines by UP levels before marking the subtree."
22074 (interactive "P")
22075 (org-with-limited-levels
22076 (cond ((org-at-heading-p) (beginning-of-line))
22077 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22078 (t (outline-previous-visible-heading 1))))
22079 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
22080 (if (org-called-interactively-p 'any)
22081 (call-interactively 'org-mark-element)
22082 (org-mark-element)))
22085 ;;; Indentation
22087 (defun org-indent-line ()
22088 "Indent line depending on context."
22089 (interactive)
22090 (let* ((pos (point))
22091 (itemp (org-at-item-p))
22092 (case-fold-search t)
22093 (org-drawer-regexp (or org-drawer-regexp "\000"))
22094 (inline-task-p (and (featurep 'org-inlinetask)
22095 (org-inlinetask-in-task-p)))
22096 (inline-re (and inline-task-p
22097 (org-inlinetask-outline-regexp)))
22098 column)
22099 (if (and orgstruct-is-++ (eq pos (point)))
22100 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
22101 (indent-according-to-mode))
22102 (beginning-of-line 1)
22103 (cond
22104 ;; Headings
22105 ((looking-at org-outline-regexp) (setq column 0))
22106 ;; Footnote definition
22107 ((looking-at org-footnote-definition-re) (setq column 0))
22108 ;; Literal examples
22109 ((looking-at "[ \t]*:\\( \\|$\\)")
22110 (setq column (org-get-indentation))) ; do nothing
22111 ;; Lists
22112 ((ignore-errors (goto-char (org-in-item-p)))
22113 (setq column (if itemp
22114 (org-get-indentation)
22115 (org-list-item-body-column (point))))
22116 (goto-char pos))
22117 ;; Drawers
22118 ((and (looking-at "[ \t]*:END:")
22119 (save-excursion (re-search-backward org-drawer-regexp nil t)))
22120 (save-excursion
22121 (goto-char (1- (match-beginning 1)))
22122 (setq column (current-column))))
22123 ;; Special blocks
22124 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
22125 (save-excursion
22126 (re-search-backward
22127 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
22128 (setq column (org-get-indentation (match-string 0))))
22129 ((and (not (looking-at "[ \t]*#\\+begin_"))
22130 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
22131 (save-excursion
22132 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
22133 (setq column
22134 (cond ((equal (downcase (match-string 1)) "src")
22135 ;; src blocks: let `org-edit-src-exit' handle them
22136 (org-get-indentation))
22137 ((equal (downcase (match-string 1)) "example")
22138 (max (org-get-indentation)
22139 (org-get-indentation (match-string 0))))
22141 (org-get-indentation (match-string 0))))))
22142 ;; This line has nothing special, look at the previous relevant
22143 ;; line to compute indentation
22145 (beginning-of-line 0)
22146 (while (and (not (bobp))
22147 (not (looking-at org-table-line-regexp))
22148 (not (looking-at org-drawer-regexp))
22149 ;; When point started in an inline task, do not move
22150 ;; above task starting line.
22151 (not (and inline-task-p (looking-at inline-re)))
22152 ;; Skip drawers, blocks, empty lines, verbatim,
22153 ;; comments, tables, footnotes definitions, lists,
22154 ;; inline tasks.
22155 (or (and (looking-at "[ \t]*:END:")
22156 (re-search-backward org-drawer-regexp nil t))
22157 (and (looking-at "[ \t]*#\\+end_")
22158 (re-search-backward "[ \t]*#\\+begin_"nil t))
22159 (looking-at "[ \t]*[\n:#|]")
22160 (looking-at org-footnote-definition-re)
22161 (and (not inline-task-p)
22162 (featurep 'org-inlinetask)
22163 (org-inlinetask-in-task-p)
22164 (or (org-inlinetask-goto-beginning) t))))
22165 (beginning-of-line 0))
22166 (cond
22167 ;; There was a list item above.
22168 ((ignore-errors (goto-char (org-in-item-p)))
22169 (goto-char (org-list-get-top-point (org-list-struct)))
22170 (setq column (org-get-indentation)))
22171 ;; There was an heading above.
22172 ((looking-at "\\*+[ \t]+")
22173 (if (not org-adapt-indentation)
22174 (setq column 0)
22175 (goto-char (match-end 0))
22176 (setq column (current-column))))
22177 ;; A drawer had started and is unfinished
22178 ((looking-at org-drawer-regexp)
22179 (goto-char (1- (match-beginning 1)))
22180 (setq column (current-column)))
22181 ;; Else, nothing noticeable found: get indentation and go on.
22182 (t (setq column (org-get-indentation))))))
22183 ;; Now apply indentation and move cursor accordingly
22184 (goto-char pos)
22185 (if (<= (current-column) (current-indentation))
22186 (org-indent-line-to column)
22187 (save-excursion (org-indent-line-to column)))
22188 ;; Special polishing for properties, see `org-property-format'
22189 (setq column (current-column))
22190 (beginning-of-line 1)
22191 (if (looking-at org-property-re)
22192 (replace-match (concat (match-string 4)
22193 (format org-property-format
22194 (match-string 1) (match-string 3)))
22195 t t))
22196 (org-move-to-column column))))
22198 (defun org-indent-drawer ()
22199 "Indent the drawer at point."
22200 (interactive)
22201 (let ((p (point))
22202 (e (and (save-excursion (re-search-forward ":END:" nil t))
22203 (match-end 0)))
22204 (folded
22205 (save-excursion
22206 (end-of-line)
22207 (when (overlays-at (point))
22208 (member 'invisible (overlay-properties
22209 (car (overlays-at (point)))))))))
22210 (when folded (org-cycle))
22211 (indent-for-tab-command)
22212 (while (and (move-beginning-of-line 2) (< (point) e))
22213 (indent-for-tab-command))
22214 (goto-char p)
22215 (when folded (org-cycle)))
22216 (message "Drawer at point indented"))
22218 (defun org-indent-block ()
22219 "Indent the block at point."
22220 (interactive)
22221 (let ((p (point))
22222 (case-fold-search t)
22223 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
22224 (match-end 0)))
22225 (folded
22226 (save-excursion
22227 (end-of-line)
22228 (when (overlays-at (point))
22229 (member 'invisible (overlay-properties
22230 (car (overlays-at (point)))))))))
22231 (when folded (org-cycle))
22232 (indent-for-tab-command)
22233 (while (and (move-beginning-of-line 2) (< (point) e))
22234 (indent-for-tab-command))
22235 (goto-char p)
22236 (when folded (org-cycle)))
22237 (message "Block at point indented"))
22239 (defun org-indent-region (start end)
22240 "Indent region."
22241 (interactive "r")
22242 (save-excursion
22243 (let ((line-end (org-current-line end)))
22244 (goto-char start)
22245 (while (< (org-current-line) line-end)
22246 (cond ((org-in-src-block-p t) (org-src-native-tab-command-maybe))
22247 (t (call-interactively 'org-indent-line)))
22248 (move-beginning-of-line 2)))))
22251 ;;; Filling
22253 ;; We use our own fill-paragraph and auto-fill functions.
22255 ;; `org-fill-paragraph' relies on adaptive filling and context
22256 ;; checking. Appropriate `fill-prefix' is computed with
22257 ;; `org-adaptive-fill-function'.
22259 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22260 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22261 ;; `org-adaptive-fill-function' value. Internally,
22262 ;; `org-comment-line-break-function' breaks the line.
22264 ;; `org-setup-filling' installs filling and auto-filling related
22265 ;; variables during `org-mode' initialization.
22267 (defvar org-element-paragraph-separate) ; org-element.el
22268 (defun org-setup-filling ()
22269 (require 'org-element)
22270 ;; Prevent auto-fill from inserting unwanted new items.
22271 (when (boundp 'fill-nobreak-predicate)
22272 (org-set-local
22273 'fill-nobreak-predicate
22274 (org-uniquify
22275 (append fill-nobreak-predicate
22276 '(org-fill-line-break-nobreak-p
22277 org-fill-paragraph-with-timestamp-nobreak-p)))))
22278 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22279 (org-set-local 'paragraph-start paragraph-ending)
22280 (org-set-local 'paragraph-separate paragraph-ending))
22281 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22282 (org-set-local 'auto-fill-inhibit-regexp nil)
22283 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22284 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22285 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22287 (defun org-fill-line-break-nobreak-p ()
22288 "Non-nil when a new line at point would create an Org line break."
22289 (save-excursion
22290 (skip-chars-backward "[ \t]")
22291 (skip-chars-backward "\\\\")
22292 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22294 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22295 "Non-nil when a new line at point would split a timestamp."
22296 (and (org-at-timestamp-p t)
22297 (not (looking-at org-ts-regexp-both))))
22299 (declare-function message-in-body-p "message" ())
22300 (defvar orgtbl-line-start-regexp) ; From org-table.el
22301 (defun org-adaptive-fill-function ()
22302 "Compute a fill prefix for the current line.
22303 Return fill prefix, as a string, or nil if current line isn't
22304 meant to be filled. For convenience, if `adaptive-fill-regexp'
22305 matches in paragraphs or comments, use it."
22306 (catch 'exit
22307 (when (derived-mode-p 'message-mode)
22308 (save-excursion
22309 (beginning-of-line)
22310 (cond ((or (not (message-in-body-p))
22311 (looking-at orgtbl-line-start-regexp))
22312 (throw 'exit nil))
22313 ((looking-at message-cite-prefix-regexp)
22314 (throw 'exit (match-string-no-properties 0)))
22315 ((looking-at org-outline-regexp)
22316 (throw 'exit (make-string (length (match-string 0)) ? ))))))
22317 (org-with-wide-buffer
22318 (let* ((p (line-beginning-position))
22319 (element (save-excursion
22320 (beginning-of-line)
22321 (or (ignore-errors (org-element-at-point))
22322 (user-error "An element cannot be parsed line %d"
22323 (line-number-at-pos (point))))))
22324 (type (org-element-type element))
22325 (post-affiliated (org-element-property :post-affiliated element)))
22326 (unless (and post-affiliated (< p post-affiliated))
22327 (case type
22328 (comment
22329 (save-excursion
22330 (beginning-of-line)
22331 (looking-at "[ \t]*")
22332 (concat (match-string 0) "# ")))
22333 (footnote-definition "")
22334 ((item plain-list)
22335 (make-string (org-list-item-body-column
22336 (or post-affiliated
22337 (org-element-property :begin element)))
22338 ? ))
22339 (paragraph
22340 ;; Fill prefix is usually the same as the current line,
22341 ;; unless the paragraph is at the beginning of an item.
22342 (let ((parent (org-element-property :parent element)))
22343 (save-excursion
22344 (beginning-of-line)
22345 (cond ((eq (org-element-type parent) 'item)
22346 (make-string (org-list-item-body-column
22347 (org-element-property :begin parent))
22348 ? ))
22349 ((and adaptive-fill-regexp
22350 ;; Locally disable
22351 ;; `adaptive-fill-function' to let
22352 ;; `fill-context-prefix' handle
22353 ;; `adaptive-fill-regexp' variable.
22354 (let (adaptive-fill-function)
22355 (fill-context-prefix
22356 post-affiliated
22357 (org-element-property :end element)))))
22358 ((looking-at "[ \t]+") (match-string 0))
22359 (t "")))))
22360 (comment-block
22361 ;; Only fill contents if P is within block boundaries.
22362 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22363 (forward-line)
22364 (point)))
22365 (cend (save-excursion
22366 (goto-char (org-element-property :end element))
22367 (skip-chars-backward " \r\t\n")
22368 (line-beginning-position))))
22369 (when (and (>= p cbeg) (< p cend))
22370 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22371 (match-string 0)
22372 ""))))))))))
22374 (declare-function message-goto-body "message" ())
22375 (defvar message-cite-prefix-regexp) ; From message.el
22376 (defun org-fill-paragraph (&optional justify)
22377 "Fill element at point, when applicable.
22379 This function only applies to comment blocks, comments, example
22380 blocks and paragraphs. Also, as a special case, re-align table
22381 when point is at one.
22383 If JUSTIFY is non-nil (interactively, with prefix argument),
22384 justify as well. If `sentence-end-double-space' is non-nil, then
22385 period followed by one space does not end a sentence, so don't
22386 break a line there. The variable `fill-column' controls the
22387 width for filling.
22389 For convenience, when point is at a plain list, an item or
22390 a footnote definition, try to fill the first paragraph within."
22391 (interactive)
22392 (if (and (derived-mode-p 'message-mode)
22393 (or (not (message-in-body-p))
22394 (save-excursion (move-beginning-of-line 1)
22395 (looking-at message-cite-prefix-regexp))))
22396 ;; First ensure filling is correct in message-mode.
22397 (let ((fill-paragraph-function
22398 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22399 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22400 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22401 (paragraph-separate
22402 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22403 (fill-paragraph nil))
22404 (with-syntax-table org-mode-transpose-word-syntax-table
22405 ;; Move to end of line in order to get the first paragraph
22406 ;; within a plain list or a footnote definition.
22407 (let ((element (save-excursion
22408 (end-of-line)
22409 (or (ignore-errors (org-element-at-point))
22410 (user-error "An element cannot be parsed line %d"
22411 (line-number-at-pos (point)))))))
22412 ;; First check if point is in a blank line at the beginning of
22413 ;; the buffer. In that case, ignore filling.
22414 (case (org-element-type element)
22415 ;; Use major mode filling function is src blocks.
22416 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22417 ;; Align Org tables, leave table.el tables as-is.
22418 (table-row (org-table-align) t)
22419 (table
22420 (when (eq (org-element-property :type element) 'org)
22421 (save-excursion
22422 (goto-char (org-element-property :post-affiliated element))
22423 (org-table-align)))
22425 (paragraph
22426 ;; Paragraphs may contain `line-break' type objects.
22427 (let ((beg (max (point-min)
22428 (org-element-property :contents-begin element)))
22429 (end (min (point-max)
22430 (org-element-property :contents-end element))))
22431 ;; Do nothing if point is at an affiliated keyword.
22432 (if (< (line-end-position) beg) t
22433 (when (derived-mode-p 'message-mode)
22434 ;; In `message-mode', do not fill following citation
22435 ;; in current paragraph nor text before message body.
22436 (let ((body-start (save-excursion (message-goto-body))))
22437 (when body-start (setq beg (max body-start beg))))
22438 (when (save-excursion
22439 (re-search-forward
22440 (concat "^" message-cite-prefix-regexp) end t))
22441 (setq end (match-beginning 0))))
22442 ;; Fill paragraph, taking line breaks into account.
22443 ;; For that, slice the paragraph using line breaks as
22444 ;; separators, and fill the parts in reverse order to
22445 ;; avoid messing with markers.
22446 (save-excursion
22447 (goto-char end)
22448 (mapc
22449 (lambda (pos)
22450 (fill-region-as-paragraph pos (point) justify)
22451 (goto-char pos))
22452 ;; Find the list of ending positions for line breaks
22453 ;; in the current paragraph. Add paragraph
22454 ;; beginning to include first slice.
22455 (nreverse
22456 (cons beg
22457 (org-element-map
22458 (org-element--parse-objects
22459 beg end nil (org-element-restriction 'paragraph))
22460 'line-break
22461 (lambda (lb) (org-element-property :end lb)))))))
22462 t)))
22463 ;; Contents of `comment-block' type elements should be
22464 ;; filled as plain text, but only if point is within block
22465 ;; markers.
22466 (comment-block
22467 (let* ((case-fold-search t)
22468 (beg (save-excursion
22469 (goto-char (org-element-property :begin element))
22470 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22471 (forward-line)
22472 (point)))
22473 (end (save-excursion
22474 (goto-char (org-element-property :end element))
22475 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22476 (line-beginning-position))))
22477 (if (or (< (point) beg) (> (point) end)) t
22478 (fill-region-as-paragraph
22479 (save-excursion (end-of-line)
22480 (re-search-backward "^[ \t]*$" beg 'move)
22481 (line-beginning-position))
22482 (save-excursion (beginning-of-line)
22483 (re-search-forward "^[ \t]*$" end 'move)
22484 (line-beginning-position))
22485 justify))))
22486 ;; Fill comments.
22487 (comment
22488 (let ((begin (org-element-property :post-affiliated element))
22489 (end (org-element-property :end element)))
22490 (when (and (>= (point) begin) (<= (point) end))
22491 (let ((begin (save-excursion
22492 (end-of-line)
22493 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22494 (progn (forward-line) (point))
22495 begin)))
22496 (end (save-excursion
22497 (end-of-line)
22498 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22499 (1- (line-beginning-position))
22500 (skip-chars-backward " \r\t\n")
22501 (line-end-position)))))
22502 ;; Do not fill comments when at a blank line.
22503 (when (> end begin)
22504 (let ((fill-prefix
22505 (save-excursion
22506 (beginning-of-line)
22507 (looking-at "[ \t]*#")
22508 (let ((comment-prefix (match-string 0)))
22509 (goto-char (match-end 0))
22510 (if (looking-at adaptive-fill-regexp)
22511 (concat comment-prefix (match-string 0))
22512 (concat comment-prefix " "))))))
22513 (save-excursion
22514 (fill-region-as-paragraph begin end justify))))))
22516 ;; Ignore every other element.
22517 (otherwise t))))))
22519 (defun org-auto-fill-function ()
22520 "Auto-fill function."
22521 ;; Check if auto-filling is meaningful.
22522 (let ((fc (current-fill-column)))
22523 (when (and fc (> (current-column) fc))
22524 (let* ((fill-prefix (org-adaptive-fill-function))
22525 ;; Enforce empty fill prefix, if required. Otherwise, it
22526 ;; will be computed again.
22527 (adaptive-fill-mode (not (equal fill-prefix ""))))
22528 (when fill-prefix (do-auto-fill))))))
22530 (defun org-comment-line-break-function (&optional soft)
22531 "Break line at point and indent, continuing comment if within one.
22532 The inserted newline is marked hard if variable
22533 `use-hard-newlines' is true, unless optional argument SOFT is
22534 non-nil."
22535 (if soft (insert-and-inherit ?\n) (newline 1))
22536 (save-excursion (forward-char -1) (delete-horizontal-space))
22537 (delete-horizontal-space)
22538 (indent-to-left-margin)
22539 (insert-before-markers-and-inherit fill-prefix))
22542 ;;; Comments
22544 ;; Org comments syntax is quite complex. It requires the entire line
22545 ;; to be just a comment. Also, even with the right syntax at the
22546 ;; beginning of line, some some elements (i.e. verse-block or
22547 ;; example-block) don't accept comments. Usual Emacs comment commands
22548 ;; cannot cope with those requirements. Therefore, Org replaces them.
22550 ;; Org still relies on `comment-dwim', but cannot trust
22551 ;; `comment-only-p'. So, `comment-region-function' and
22552 ;; `uncomment-region-function' both point
22553 ;; to`org-comment-or-uncomment-region'. Eventually,
22554 ;; `org-insert-comment' takes care of insertion of comments at the
22555 ;; beginning of line.
22557 ;; `org-setup-comments-handling' install comments related variables
22558 ;; during `org-mode' initialization.
22560 (defun org-setup-comments-handling ()
22561 (interactive)
22562 (org-set-local 'comment-use-syntax nil)
22563 (org-set-local 'comment-start "# ")
22564 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22565 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22566 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22567 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22569 (defun org-insert-comment ()
22570 "Insert an empty comment above current line.
22571 If the line is empty, insert comment at its beginning."
22572 (beginning-of-line)
22573 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
22574 (org-indent-line)
22575 (insert "# "))
22577 (defvar comment-empty-lines) ; From newcomment.el.
22578 (defun org-comment-or-uncomment-region (beg end &rest ignore)
22579 "Comment or uncomment each non-blank line in the region.
22580 Uncomment each non-blank line between BEG and END if it only
22581 contains commented lines. Otherwise, comment them."
22582 (save-restriction
22583 ;; Restrict region
22584 (narrow-to-region (save-excursion (goto-char beg)
22585 (skip-chars-forward " \r\t\n" end)
22586 (line-beginning-position))
22587 (save-excursion (goto-char end)
22588 (skip-chars-backward " \r\t\n" beg)
22589 (line-end-position)))
22590 (let ((uncommentp
22591 ;; UNCOMMENTP is non-nil when every non blank line between
22592 ;; BEG and END is a comment.
22593 (save-excursion
22594 (goto-char (point-min))
22595 (while (and (not (eobp))
22596 (let ((element (org-element-at-point)))
22597 (and (eq (org-element-type element) 'comment)
22598 (goto-char (min (point-max)
22599 (org-element-property
22600 :end element)))))))
22601 (eobp))))
22602 (if uncommentp
22603 ;; Only blank lines and comments in region: uncomment it.
22604 (save-excursion
22605 (goto-char (point-min))
22606 (while (not (eobp))
22607 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22608 (replace-match "" nil nil nil 1))
22609 (forward-line)))
22610 ;; Comment each line in region.
22611 (let ((min-indent (point-max)))
22612 ;; First find the minimum indentation across all lines.
22613 (save-excursion
22614 (goto-char (point-min))
22615 (while (and (not (eobp)) (not (zerop min-indent)))
22616 (unless (looking-at "[ \t]*$")
22617 (setq min-indent (min min-indent (current-indentation))))
22618 (forward-line)))
22619 ;; Then loop over all lines.
22620 (save-excursion
22621 (goto-char (point-min))
22622 (while (not (eobp))
22623 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22624 ;; Don't get fooled by invisible text (e.g. link path)
22625 ;; when moving to column MIN-INDENT.
22626 (let ((buffer-invisibility-spec nil))
22627 (org-move-to-column min-indent t))
22628 (insert comment-start))
22629 (forward-line))))))))
22632 ;;; Planning
22634 ;; This section contains tools to operate on timestamp objects, as
22635 ;; returned by, e.g. `org-element-context'.
22637 (defun org-timestamp-has-time-p (timestamp)
22638 "Non-nil when TIMESTAMP has a time specified."
22639 (org-element-property :hour-start timestamp))
22641 (defun org-timestamp-format (timestamp format &optional end utc)
22642 "Format a TIMESTAMP element into a string.
22644 FORMAT is a format specifier to be passed to
22645 `format-time-string'.
22647 When optional argument END is non-nil, use end of date-range or
22648 time-range, if possible.
22650 When optional argument UTC is non-nil, time will be expressed as
22651 Universal Time."
22652 (format-time-string
22653 format
22654 (apply 'encode-time
22655 (cons 0
22656 (mapcar
22657 (lambda (prop) (or (org-element-property prop timestamp) 0))
22658 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22659 '(:minute-start :hour-start :day-start :month-start
22660 :year-start)))))
22661 utc))
22663 (defun org-timestamp-split-range (timestamp &optional end)
22664 "Extract a timestamp object from a date or time range.
22666 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22667 the end of the range. Otherwise, extract its start.
22669 Return a new timestamp object sharing the same parent as
22670 TIMESTAMP."
22671 (let ((type (org-element-property :type timestamp)))
22672 (if (memq type '(active inactive diary)) timestamp
22673 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22674 ;; Set new type.
22675 (org-element-put-property
22676 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22677 ;; Copy start properties over end properties if END is
22678 ;; non-nil. Otherwise, copy end properties over `start' ones.
22679 (let ((p-alist '((:minute-start . :minute-end)
22680 (:hour-start . :hour-end)
22681 (:day-start . :day-end)
22682 (:month-start . :month-end)
22683 (:year-start . :year-end))))
22684 (dolist (p-cell p-alist)
22685 (org-element-put-property
22686 split-ts
22687 (funcall (if end 'car 'cdr) p-cell)
22688 (org-element-property
22689 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22690 ;; Eventually refresh `:raw-value'.
22691 (org-element-put-property split-ts :raw-value nil)
22692 (org-element-put-property
22693 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22695 (defun org-timestamp-translate (timestamp &optional boundary)
22696 "Apply `org-translate-time' on a TIMESTAMP object.
22697 When optional argument BOUNDARY is non-nil, it is either the
22698 symbol `start' or `end'. In this case, only translate the
22699 starting or ending part of TIMESTAMP if it is a date or time
22700 range. Otherwise, translate both parts."
22701 (if (and (not boundary)
22702 (memq (org-element-property :type timestamp)
22703 '(active-range inactive-range)))
22704 (concat
22705 (org-translate-time
22706 (org-element-property :raw-value
22707 (org-timestamp-split-range timestamp)))
22708 "--"
22709 (org-translate-time
22710 (org-element-property :raw-value
22711 (org-timestamp-split-range timestamp t))))
22712 (org-translate-time
22713 (org-element-property
22714 :raw-value
22715 (if (not boundary) timestamp
22716 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22720 ;;; Other stuff.
22722 (defun org-toggle-fixed-width-section (arg)
22723 "Toggle the fixed-width export.
22724 If there is no active region, the QUOTE keyword at the current headline is
22725 inserted or removed. When present, it causes the text between this headline
22726 and the next to be exported as fixed-width text, and unmodified.
22727 If there is an active region, this command adds or removes a colon as the
22728 first character of this line. If the first character of a line is a colon,
22729 this line is also exported in fixed-width font."
22730 (interactive "P")
22731 (let* ((cc 0)
22732 (regionp (org-region-active-p))
22733 (beg (if regionp (region-beginning) (point)))
22734 (end (if regionp (region-end)))
22735 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22736 (case-fold-search nil)
22737 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22738 off)
22739 (if regionp
22740 (save-excursion
22741 (goto-char beg)
22742 (setq cc (current-column))
22743 (beginning-of-line 1)
22744 (setq off (looking-at re))
22745 (while (> nlines 0)
22746 (setq nlines (1- nlines))
22747 (beginning-of-line 1)
22748 (cond
22749 (arg
22750 (org-move-to-column cc t)
22751 (insert ": \n")
22752 (forward-line -1))
22753 ((and off (looking-at re))
22754 (replace-match "" t t nil 1))
22755 ((not off) (org-move-to-column cc t) (insert ": ")))
22756 (forward-line 1)))
22757 (save-excursion
22758 (org-back-to-heading)
22759 (cond
22760 ((looking-at (format org-heading-keyword-regexp-format
22761 org-quote-string))
22762 (goto-char (match-end 1))
22763 (looking-at (concat " +" org-quote-string))
22764 (replace-match "" t t)
22765 (when (eolp) (insert " ")))
22766 ((looking-at org-outline-regexp)
22767 (goto-char (match-end 0))
22768 (insert org-quote-string " ")))))))
22770 (defun org-reftex-citation ()
22771 "Use reftex-citation to insert a citation into the buffer.
22772 This looks for a line like
22774 #+BIBLIOGRAPHY: foo plain option:-d
22776 and derives from it that foo.bib is the bibliography file relevant
22777 for this document. It then installs the necessary environment for RefTeX
22778 to work in this buffer and calls `reftex-citation' to insert a citation
22779 into the buffer.
22781 Export of such citations to both LaTeX and HTML is handled by the contributed
22782 package ox-bibtex by Taru Karttunen."
22783 (interactive)
22784 (let ((reftex-docstruct-symbol 'rds)
22785 (reftex-cite-format "\\cite{%l}")
22786 rds bib)
22787 (save-excursion
22788 (save-restriction
22789 (widen)
22790 (let ((case-fold-search t)
22791 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22792 (if (not (save-excursion
22793 (or (re-search-forward re nil t)
22794 (re-search-backward re nil t))))
22795 (error "No bibliography defined in file")
22796 (setq bib (concat (match-string 1) ".bib")
22797 rds (list (list 'bib bib)))))))
22798 (call-interactively 'reftex-citation)))
22800 ;;;; Functions extending outline functionality
22802 (defun org-beginning-of-line (&optional arg)
22803 "Go to the beginning of the current line. If that is invisible, continue
22804 to a visible line beginning. This makes the function of C-a more intuitive.
22805 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22806 first attempt, and only move to after the tags when the cursor is already
22807 beyond the end of the headline."
22808 (interactive "P")
22809 (let ((pos (point))
22810 (special (if (consp org-special-ctrl-a/e)
22811 (car org-special-ctrl-a/e)
22812 org-special-ctrl-a/e))
22813 deactivate-mark refpos)
22814 (if (org-bound-and-true-p visual-line-mode)
22815 (beginning-of-visual-line 1)
22816 (beginning-of-line 1))
22817 (if (and arg (fboundp 'move-beginning-of-line))
22818 (call-interactively 'move-beginning-of-line)
22819 (if (bobp)
22821 (backward-char 1)
22822 (if (org-truely-invisible-p)
22823 (while (and (not (bobp)) (org-truely-invisible-p))
22824 (backward-char 1)
22825 (beginning-of-line 1))
22826 (forward-char 1))))
22827 (when special
22828 (cond
22829 ((and (looking-at org-complex-heading-regexp)
22830 (= (char-after (match-end 1)) ?\ ))
22831 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22832 (point-at-eol)))
22833 (goto-char
22834 (if (eq special t)
22835 (cond ((> pos refpos) refpos)
22836 ((= pos (point)) refpos)
22837 (t (point)))
22838 (cond ((> pos (point)) (point))
22839 ((not (eq last-command this-command)) (point))
22840 (t refpos)))))
22841 ((org-at-item-p)
22842 ;; Being at an item and not looking at an the item means point
22843 ;; was previously moved to beginning of a visual line, which
22844 ;; doesn't contain the item. Therefore, do nothing special,
22845 ;; just stay here.
22846 (when (looking-at org-list-full-item-re)
22847 ;; Set special position at first white space character after
22848 ;; bullet, and check-box, if any.
22849 (let ((after-bullet
22850 (let ((box (match-end 3)))
22851 (if (not box) (match-end 1)
22852 (let ((after (char-after box)))
22853 (if (and after (= after ? )) (1+ box) box))))))
22854 ;; Special case: Move point to special position when
22855 ;; currently after it or at beginning of line.
22856 (if (eq special t)
22857 (when (or (> pos after-bullet) (= (point) pos))
22858 (goto-char after-bullet))
22859 ;; Reversed case: Move point to special position when
22860 ;; point was already at beginning of line and command is
22861 ;; repeated.
22862 (when (and (= (point) pos) (eq last-command this-command))
22863 (goto-char after-bullet))))))))
22864 (org-no-warnings
22865 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22866 (setq disable-point-adjustment
22867 (or (not (invisible-p (point)))
22868 (not (invisible-p (max (point-min) (1- (point))))))))
22870 (defun org-end-of-line (&optional arg)
22871 "Go to the end of the line.
22872 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22873 tags on the first attempt, and only move to after the tags when
22874 the cursor is already beyond the end of the headline."
22875 (interactive "P")
22876 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22877 org-special-ctrl-a/e))
22878 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22879 'end-of-visual-line)
22880 ((fboundp 'move-end-of-line) 'move-end-of-line)
22881 (t 'end-of-line)))
22882 deactivate-mark)
22883 (if (or (not special) arg) (call-interactively move-fun)
22884 (let* ((element (save-excursion (beginning-of-line)
22885 (org-element-at-point)))
22886 (type (org-element-type element)))
22887 (cond
22888 ((memq type '(headline inlinetask))
22889 (let ((pos (point)))
22890 (beginning-of-line 1)
22891 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22892 (if (eq special t)
22893 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22894 (goto-char (match-beginning 1))
22895 (goto-char (match-end 0)))
22896 (if (or (< pos (match-end 0))
22897 (not (eq this-command last-command)))
22898 (goto-char (match-end 0))
22899 (goto-char (match-beginning 1))))
22900 (call-interactively move-fun))))
22901 ((org-element-property :hiddenp element)
22902 ;; If element is hidden, `move-end-of-line' would put point
22903 ;; after it. Use `end-of-line' to stay on current line.
22904 (call-interactively 'end-of-line))
22905 (t (call-interactively move-fun)))))
22906 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22907 (setq disable-point-adjustment
22908 (or (not (invisible-p (point)))
22909 (not (invisible-p (max (point-min) (1- (point))))))))
22911 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22912 (define-key org-mode-map "\C-e" 'org-end-of-line)
22914 (defun org-backward-sentence (&optional arg)
22915 "Go to beginning of sentence, or beginning of table field.
22916 This will call `backward-sentence' or `org-table-beginning-of-field',
22917 depending on context."
22918 (interactive "P")
22919 (cond
22920 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22921 (t (call-interactively 'backward-sentence))))
22923 (defun org-forward-sentence (&optional arg)
22924 "Go to end of sentence, or end of table field.
22925 This will call `forward-sentence' or `org-table-end-of-field',
22926 depending on context."
22927 (interactive "P")
22928 (cond
22929 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22930 (t (call-interactively 'forward-sentence))))
22932 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22933 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22935 (defun org-kill-line (&optional arg)
22936 "Kill line, to tags or end of line."
22937 (interactive "P")
22938 (cond
22939 ((or (not org-special-ctrl-k)
22940 (bolp)
22941 (not (org-at-heading-p)))
22942 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22943 org-ctrl-k-protect-subtree)
22944 (if (or (eq org-ctrl-k-protect-subtree 'error)
22945 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22946 (user-error "C-k aborted as it would kill a hidden subtree")))
22947 (call-interactively
22948 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22949 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22950 (kill-region (point) (match-beginning 1))
22951 (org-set-tags nil t))
22952 (t (kill-region (point) (point-at-eol)))))
22954 (define-key org-mode-map "\C-k" 'org-kill-line)
22956 (defun org-yank (&optional arg)
22957 "Yank. If the kill is a subtree, treat it specially.
22958 This command will look at the current kill and check if is a single
22959 subtree, or a series of subtrees[1]. If it passes the test, and if the
22960 cursor is at the beginning of a line or after the stars of a currently
22961 empty headline, then the yank is handled specially. How exactly depends
22962 on the value of the following variables, both set by default.
22964 org-yank-folded-subtrees
22965 When set, the subtree(s) will be folded after insertion, but only
22966 if doing so would now swallow text after the yanked text.
22968 org-yank-adjusted-subtrees
22969 When set, the subtree will be promoted or demoted in order to
22970 fit into the local outline tree structure, which means that the level
22971 will be adjusted so that it becomes the smaller one of the two
22972 *visible* surrounding headings.
22974 Any prefix to this command will cause `yank' to be called directly with
22975 no special treatment. In particular, a simple \\[universal-argument] prefix \
22976 will just
22977 plainly yank the text as it is.
22979 \[1] The test checks if the first non-white line is a heading
22980 and if there are no other headings with fewer stars."
22981 (interactive "P")
22982 (org-yank-generic 'yank arg))
22984 (defun org-yank-generic (command arg)
22985 "Perform some yank-like command.
22987 This function implements the behavior described in the `org-yank'
22988 documentation. However, it has been generalized to work for any
22989 interactive command with similar behavior."
22991 ;; pretend to be command COMMAND
22992 (setq this-command command)
22994 (if arg
22995 (call-interactively command)
22997 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22998 (and (org-kill-is-subtree-p)
22999 (or (bolp)
23000 (and (looking-at "[ \t]*$")
23001 (string-match
23002 "\\`\\*+\\'"
23003 (buffer-substring (point-at-bol) (point)))))))
23004 swallowp)
23005 (cond
23006 ((and subtreep org-yank-folded-subtrees)
23007 (let ((beg (point))
23008 end)
23009 (if (and subtreep org-yank-adjusted-subtrees)
23010 (org-paste-subtree nil nil 'for-yank)
23011 (call-interactively command))
23013 (setq end (point))
23014 (goto-char beg)
23015 (when (and (bolp) subtreep
23016 (not (setq swallowp
23017 (org-yank-folding-would-swallow-text beg end))))
23018 (org-with-limited-levels
23019 (or (looking-at org-outline-regexp)
23020 (re-search-forward org-outline-regexp-bol end t))
23021 (while (and (< (point) end) (looking-at org-outline-regexp))
23022 (hide-subtree)
23023 (org-cycle-show-empty-lines 'folded)
23024 (condition-case nil
23025 (outline-forward-same-level 1)
23026 (error (goto-char end))))))
23027 (when swallowp
23028 (message
23029 "Inserted text not folded because that would swallow text"))
23031 (goto-char end)
23032 (skip-chars-forward " \t\n\r")
23033 (beginning-of-line 1)
23034 (push-mark beg 'nomsg)))
23035 ((and subtreep org-yank-adjusted-subtrees)
23036 (let ((beg (point-at-bol)))
23037 (org-paste-subtree nil nil 'for-yank)
23038 (push-mark beg 'nomsg)))
23040 (call-interactively command))))))
23042 (defun org-yank-folding-would-swallow-text (beg end)
23043 "Would hide-subtree at BEG swallow any text after END?"
23044 (let (level)
23045 (org-with-limited-levels
23046 (save-excursion
23047 (goto-char beg)
23048 (when (or (looking-at org-outline-regexp)
23049 (re-search-forward org-outline-regexp-bol end t))
23050 (setq level (org-outline-level)))
23051 (goto-char end)
23052 (skip-chars-forward " \t\r\n\v\f")
23053 (if (or (eobp)
23054 (and (bolp) (looking-at org-outline-regexp)
23055 (<= (org-outline-level) level)))
23056 nil ; Nothing would be swallowed
23057 t))))) ; something would swallow
23059 (define-key org-mode-map "\C-y" 'org-yank)
23061 (defun org-truely-invisible-p ()
23062 "Check if point is at a character currently not visible.
23063 This version does not only check the character property, but also
23064 `visible-mode'."
23065 ;; Early versions of noutline don't have `outline-invisible-p'.
23066 (if (org-bound-and-true-p visible-mode)
23068 (outline-invisible-p)))
23070 (defun org-invisible-p2 ()
23071 "Check if point is at a character currently not visible."
23072 (save-excursion
23073 (if (and (eolp) (not (bobp))) (backward-char 1))
23074 ;; Early versions of noutline don't have `outline-invisible-p'.
23075 (outline-invisible-p)))
23077 (defun org-back-to-heading (&optional invisible-ok)
23078 "Call `outline-back-to-heading', but provide a better error message."
23079 (condition-case nil
23080 (outline-back-to-heading invisible-ok)
23081 (error (error "Before first headline at position %d in buffer %s"
23082 (point) (current-buffer)))))
23084 (defun org-before-first-heading-p ()
23085 "Before first heading?"
23086 (save-excursion
23087 (end-of-line)
23088 (null (re-search-backward org-outline-regexp-bol nil t))))
23090 (defun org-at-heading-p (&optional ignored)
23091 (outline-on-heading-p t))
23092 ;; Compatibility alias with Org versions < 7.8.03
23093 (defalias 'org-on-heading-p 'org-at-heading-p)
23095 (defun org-at-comment-p nil
23096 "Is cursor in a line starting with a # character?"
23097 (save-excursion
23098 (beginning-of-line)
23099 (looking-at "^#")))
23101 (defun org-at-drawer-p nil
23102 "Is cursor at a drawer keyword?"
23103 (save-excursion
23104 (move-beginning-of-line 1)
23105 (looking-at org-drawer-regexp)))
23107 (defun org-at-block-p nil
23108 "Is cursor at a block keyword?"
23109 (save-excursion
23110 (move-beginning-of-line 1)
23111 (looking-at org-block-regexp)))
23113 (defun org-point-at-end-of-empty-headline ()
23114 "If point is at the end of an empty headline, return t, else nil.
23115 If the heading only contains a TODO keyword, it is still still considered
23116 empty."
23117 (and (looking-at "[ \t]*$")
23118 (when org-todo-line-regexp
23119 (save-excursion
23120 (beginning-of-line 1)
23121 (let ((case-fold-search nil))
23122 (looking-at org-todo-line-regexp)
23123 (string= (match-string 3) ""))))))
23125 (defun org-at-heading-or-item-p ()
23126 (or (org-at-heading-p) (org-at-item-p)))
23128 (defun org-at-target-p ()
23129 (or (org-in-regexp org-radio-target-regexp)
23130 (org-in-regexp org-target-regexp)))
23131 ;; Compatibility alias with Org versions < 7.8.03
23132 (defalias 'org-on-target-p 'org-at-target-p)
23134 (defun org-up-heading-all (arg)
23135 "Move to the heading line of which the present line is a subheading.
23136 This function considers both visible and invisible heading lines.
23137 With argument, move up ARG levels."
23138 (if (fboundp 'outline-up-heading-all)
23139 (outline-up-heading-all arg) ; emacs 21 version of outline.el
23140 (outline-up-heading arg t))) ; emacs 22 version of outline.el
23142 (defun org-up-heading-safe ()
23143 "Move to the heading line of which the present line is a subheading.
23144 This version will not throw an error. It will return the level of the
23145 headline found, or nil if no higher level is found.
23147 Also, this function will be a lot faster than `outline-up-heading',
23148 because it relies on stars being the outline starters. This can really
23149 make a significant difference in outlines with very many siblings."
23150 (let (start-level re)
23151 (org-back-to-heading t)
23152 (setq start-level (funcall outline-level))
23153 (if (equal start-level 1)
23155 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
23156 (if (re-search-backward re nil t)
23157 (funcall outline-level)))))
23159 (defun org-first-sibling-p ()
23160 "Is this heading the first child of its parents?"
23161 (interactive)
23162 (let ((re org-outline-regexp-bol)
23163 level l)
23164 (unless (org-at-heading-p t)
23165 (user-error "Not at a heading"))
23166 (setq level (funcall outline-level))
23167 (save-excursion
23168 (if (not (re-search-backward re nil t))
23170 (setq l (funcall outline-level))
23171 (< l level)))))
23173 (defun org-goto-sibling (&optional previous)
23174 "Goto the next sibling, even if it is invisible.
23175 When PREVIOUS is set, go to the previous sibling instead. Returns t
23176 when a sibling was found. When none is found, return nil and don't
23177 move point."
23178 (let ((fun (if previous 're-search-backward 're-search-forward))
23179 (pos (point))
23180 (re org-outline-regexp-bol)
23181 level l)
23182 (when (condition-case nil (org-back-to-heading t) (error nil))
23183 (setq level (funcall outline-level))
23184 (catch 'exit
23185 (or previous (forward-char 1))
23186 (while (funcall fun re nil t)
23187 (setq l (funcall outline-level))
23188 (when (< l level) (goto-char pos) (throw 'exit nil))
23189 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23190 (goto-char pos)
23191 nil))))
23193 (defun org-show-siblings ()
23194 "Show all siblings of the current headline."
23195 (save-excursion
23196 (while (org-goto-sibling) (org-flag-heading nil)))
23197 (save-excursion
23198 (while (org-goto-sibling 'previous)
23199 (org-flag-heading nil))))
23201 (defun org-goto-first-child ()
23202 "Goto the first child, even if it is invisible.
23203 Return t when a child was found. Otherwise don't move point and
23204 return nil."
23205 (let (level (pos (point)) (re org-outline-regexp-bol))
23206 (when (condition-case nil (org-back-to-heading t) (error nil))
23207 (setq level (outline-level))
23208 (forward-char 1)
23209 (if (and (re-search-forward re nil t) (> (outline-level) level))
23210 (progn (goto-char (match-beginning 0)) t)
23211 (goto-char pos) nil))))
23213 (defun org-show-hidden-entry ()
23214 "Show an entry where even the heading is hidden."
23215 (save-excursion
23216 (org-show-entry)))
23218 (defun org-flag-heading (flag &optional entry)
23219 "Flag the current heading. FLAG non-nil means make invisible.
23220 When ENTRY is non-nil, show the entire entry."
23221 (save-excursion
23222 (org-back-to-heading t)
23223 ;; Check if we should show the entire entry
23224 (if entry
23225 (progn
23226 (org-show-entry)
23227 (save-excursion
23228 (and (outline-next-heading)
23229 (org-flag-heading nil))))
23230 (outline-flag-region (max (point-min) (1- (point)))
23231 (save-excursion (outline-end-of-heading) (point))
23232 flag))))
23234 (defun org-get-next-sibling ()
23235 "Move to next heading of the same level, and return point.
23236 If there is no such heading, return nil.
23237 This is like outline-next-sibling, but invisible headings are ok."
23238 (let ((level (funcall outline-level)))
23239 (outline-next-heading)
23240 (while (and (not (eobp)) (> (funcall outline-level) level))
23241 (outline-next-heading))
23242 (if (or (eobp) (< (funcall outline-level) level))
23244 (point))))
23246 (defun org-get-last-sibling ()
23247 "Move to previous heading of the same level, and return point.
23248 If there is no such heading, return nil."
23249 (let ((opoint (point))
23250 (level (funcall outline-level)))
23251 (outline-previous-heading)
23252 (when (and (/= (point) opoint) (outline-on-heading-p t))
23253 (while (and (> (funcall outline-level) level)
23254 (not (bobp)))
23255 (outline-previous-heading))
23256 (if (< (funcall outline-level) level)
23258 (point)))))
23260 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23261 "Goto to the end of a subtree."
23262 ;; This contains an exact copy of the original function, but it uses
23263 ;; `org-back-to-heading', to make it work also in invisible
23264 ;; trees. And is uses an invisible-ok argument.
23265 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23266 ;; Furthermore, when used inside Org, finding the end of a large subtree
23267 ;; with many children and grandchildren etc, this can be much faster
23268 ;; than the outline version.
23269 (org-back-to-heading invisible-ok)
23270 (let ((first t)
23271 (level (funcall outline-level)))
23272 (if (and (derived-mode-p 'org-mode) (< level 1000))
23273 ;; A true heading (not a plain list item), in Org-mode
23274 ;; This means we can easily find the end by looking
23275 ;; only for the right number of stars. Using a regexp to do
23276 ;; this is so much faster than using a Lisp loop.
23277 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23278 (forward-char 1)
23279 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23280 ;; something else, do it the slow way
23281 (while (and (not (eobp))
23282 (or first (> (funcall outline-level) level)))
23283 (setq first nil)
23284 (outline-next-heading)))
23285 (unless to-heading
23286 (if (memq (preceding-char) '(?\n ?\^M))
23287 (progn
23288 ;; Go to end of line before heading
23289 (forward-char -1)
23290 (if (memq (preceding-char) '(?\n ?\^M))
23291 ;; leave blank line before heading
23292 (forward-char -1))))))
23293 (point))
23295 (defun org-end-of-meta-data-and-drawers ()
23296 "Jump to the first text after meta data and drawers in the current entry.
23297 This will move over empty lines, lines with planning time stamps,
23298 clocking lines, and drawers."
23299 (org-back-to-heading t)
23300 (let ((end (save-excursion (outline-next-heading) (point)))
23301 (re (concat "\\(" org-drawer-regexp "\\)"
23302 "\\|" "[ \t]*" org-keyword-time-regexp)))
23303 (forward-line 1)
23304 (while (re-search-forward re end t)
23305 (if (not (match-end 1))
23306 ;; empty or planning line
23307 (forward-line 1)
23308 ;; a drawer, find the end
23309 (re-search-forward "^[ \t]*:END:" end 'move)
23310 (forward-line 1)))
23311 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23312 (point)))
23314 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23315 "Move forward to the ARG'th subheading at same level as this one.
23316 Stop at the first and last subheadings of a superior heading.
23317 Normally this only looks at visible headings, but when INVISIBLE-OK is
23318 non-nil it will also look at invisible ones."
23319 (interactive "p")
23320 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23321 (if (and arg (< arg 0))
23322 (goto-char (point-min))
23323 (outline-next-heading))
23324 (org-at-heading-p)
23325 (let ((level (- (match-end 0) (match-beginning 0) 1))
23326 (f (if (and arg (< arg 0))
23327 're-search-backward
23328 're-search-forward))
23329 (count (if arg (abs arg) 1))
23330 (result (point)))
23331 (while (and (prog1 (> count 0)
23332 (forward-char (if (and arg (< arg 0)) -1 1)))
23333 (funcall f org-outline-regexp-bol nil 'move))
23334 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23335 (cond ((< l level) (setq count 0))
23336 ((and (= l level)
23337 (or invisible-ok
23338 (progn
23339 (goto-char (line-beginning-position))
23340 (not (outline-invisible-p)))))
23341 (setq count (1- count))
23342 (when (eq l level)
23343 (setq result (point)))))))
23344 (goto-char result))
23345 (beginning-of-line 1)))
23347 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23348 "Move backward to the ARG'th subheading at same level as this one.
23349 Stop at the first and last subheadings of a superior heading."
23350 (interactive "p")
23351 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23353 (defun org-next-block (arg &optional backward block-regexp)
23354 "Jump to the next block.
23355 With a prefix argument ARG, jump forward ARG many source blocks.
23356 When BACKWARD is non-nil, jump to the previous block.
23357 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23358 (interactive "p")
23359 (let ((re (or block-regexp org-block-regexp))
23360 (re-search-fn (or (and backward 're-search-backward)
23361 're-search-forward)))
23362 (if (looking-at re) (forward-char 1))
23363 (condition-case nil
23364 (funcall re-search-fn re nil nil arg)
23365 (error (error "No %s code blocks" (if backward "previous" "further" ))))
23366 (goto-char (match-beginning 0)) (org-show-context)))
23368 (defun org-previous-block (arg &optional block-regexp)
23369 "Jump to the previous block.
23370 With a prefix argument ARG, jump backward ARG many source blocks.
23371 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23372 (interactive "p")
23373 (org-next-block arg t block-regexp))
23375 (defun org-forward-paragraph ()
23376 "Move forward to beginning of next paragraph or equivalent.
23378 The function moves point to the beginning of the next visible
23379 structural element, which can be a paragraph, a table, a list
23380 item, etc. It also provides some special moves for convenience:
23382 - On an affiliated keyword, jump to the beginning of the
23383 relative element.
23384 - On an item or a footnote definition, move to the second
23385 element inside, if any.
23386 - On a table or a property drawer, jump after it.
23387 - On a verse or source block, stop after blank lines."
23388 (interactive)
23389 (when (eobp) (user-error "Cannot move further down"))
23390 (let* ((deactivate-mark nil)
23391 (element (org-element-at-point))
23392 (type (org-element-type element))
23393 (post-affiliated (org-element-property :post-affiliated element))
23394 (contents-begin (org-element-property :contents-begin element))
23395 (contents-end (org-element-property :contents-end element))
23396 (end (let ((end (org-element-property :end element)) (parent element))
23397 (while (and (setq parent (org-element-property :parent parent))
23398 (= (org-element-property :contents-end parent) end))
23399 (setq end (org-element-property :end parent)))
23400 end)))
23401 (cond ((not element)
23402 (skip-chars-forward " \r\t\n")
23403 (or (eobp) (beginning-of-line)))
23404 ;; On affiliated keywords, move to element's beginning.
23405 ((and post-affiliated (< (point) post-affiliated))
23406 (goto-char post-affiliated))
23407 ;; At a table row, move to the end of the table. Similarly,
23408 ;; at a node property, move to the end of the property
23409 ;; drawer.
23410 ((memq type '(node-property table-row))
23411 (goto-char (org-element-property
23412 :end (org-element-property :parent element))))
23413 ((memq type '(property-drawer table)) (goto-char end))
23414 ;; Consider blank lines as separators in verse and source
23415 ;; blocks to ease editing.
23416 ((memq type '(src-block verse-block))
23417 (when (eq type 'src-block)
23418 (setq contents-end
23419 (save-excursion (goto-char end)
23420 (skip-chars-backward " \r\t\n")
23421 (line-beginning-position))))
23422 (beginning-of-line)
23423 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23424 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23425 (goto-char end)
23426 (skip-chars-forward " \r\t\n")
23427 (if (= (point) contents-end) (goto-char end)
23428 (beginning-of-line))))
23429 ;; With no contents, just skip element.
23430 ((not contents-begin) (goto-char end))
23431 ;; If contents are invisible, skip the element altogether.
23432 ((outline-invisible-p (line-end-position))
23433 (case type
23434 (headline
23435 (org-with-limited-levels (outline-next-visible-heading 1)))
23436 ;; At a plain list, make sure we move to the next item
23437 ;; instead of skipping the whole list.
23438 (plain-list (forward-char)
23439 (org-forward-paragraph))
23440 (otherwise (goto-char end))))
23441 ((>= (point) contents-end) (goto-char end))
23442 ((>= (point) contents-begin)
23443 ;; This can only happen on paragraphs and plain lists.
23444 (case type
23445 (paragraph (goto-char end))
23446 ;; At a plain list, try to move to second element in
23447 ;; first item, if possible.
23448 (plain-list (end-of-line)
23449 (org-forward-paragraph))))
23450 ;; When contents start on the middle of a line (e.g. in
23451 ;; items and footnote definitions), try to reach first
23452 ;; element starting after current line.
23453 ((> (line-end-position) contents-begin)
23454 (end-of-line)
23455 (org-forward-paragraph))
23456 (t (goto-char contents-begin)))))
23458 (defun org-backward-paragraph ()
23459 "Move backward to start of previous paragraph or equivalent.
23461 The function moves point to the beginning of the current
23462 structural element, which can be a paragraph, a table, a list
23463 item, etc., or to the beginning of the previous visible one if
23464 point is already there. It also provides some special moves for
23465 convenience:
23467 - On an affiliated keyword, jump to the first one.
23468 - On a table or a property drawer, move to its beginning.
23469 - On a verse or source block, stop before blank lines."
23470 (interactive)
23471 (when (bobp) (user-error "Cannot move further up"))
23472 (let* ((deactivate-mark nil)
23473 (element (org-element-at-point))
23474 (type (org-element-type element))
23475 (contents-begin (org-element-property :contents-begin element))
23476 (contents-end (org-element-property :contents-end element))
23477 (post-affiliated (org-element-property :post-affiliated element))
23478 (begin (org-element-property :begin element)))
23479 (cond
23480 ((not element) (goto-char (point-min)))
23481 ((= (point) begin)
23482 (backward-char)
23483 (org-backward-paragraph))
23484 ((and post-affiliated (<= (point) post-affiliated)) (goto-char begin))
23485 ((memq type '(node-property table-row))
23486 (goto-char (org-element-property
23487 :post-affiliated (org-element-property :parent element))))
23488 ((memq type '(property-drawer table)) (goto-char begin))
23489 ((memq type '(src-block verse-block))
23490 (when (eq type 'src-block)
23491 (setq contents-begin
23492 (save-excursion (goto-char begin) (forward-line) (point))))
23493 (if (= (point) contents-begin) (goto-char post-affiliated)
23494 ;; Inside a verse block, see blank lines as paragraph
23495 ;; separators.
23496 (let ((origin (point)))
23497 (skip-chars-backward " \r\t\n" contents-begin)
23498 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
23499 (skip-chars-forward " \r\t\n" origin)
23500 (if (= (point) origin) (goto-char contents-begin)
23501 (beginning-of-line))))))
23502 ((not contents-begin) (goto-char (or post-affiliated begin)))
23503 ((eq type 'paragraph)
23504 (goto-char contents-begin)
23505 ;; When at first paragraph in an item or a footnote definition,
23506 ;; move directly to beginning of line.
23507 (let ((parent-contents
23508 (org-element-property
23509 :contents-begin (org-element-property :parent element))))
23510 (when (and parent-contents (= parent-contents contents-begin))
23511 (beginning-of-line))))
23512 ;; At the end of a greater element, move to the beginning of the
23513 ;; last element within.
23514 ((>= (point) contents-end)
23515 (goto-char (1- contents-end))
23516 (org-backward-paragraph))
23517 (t (goto-char (or post-affiliated begin))))
23518 ;; Ensure we never leave point invisible.
23519 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
23521 (defun org-forward-element ()
23522 "Move forward by one element.
23523 Move to the next element at the same level, when possible."
23524 (interactive)
23525 (cond ((eobp) (user-error "Cannot move further down"))
23526 ((org-with-limited-levels (org-at-heading-p))
23527 (let ((origin (point)))
23528 (goto-char (org-end-of-subtree nil t))
23529 (unless (org-with-limited-levels (org-at-heading-p))
23530 (goto-char origin)
23531 (user-error "Cannot move further down"))))
23533 (let* ((elem (org-element-at-point))
23534 (end (org-element-property :end elem))
23535 (parent (org-element-property :parent elem)))
23536 (cond ((and parent (= (org-element-property :contents-end parent) end))
23537 (goto-char (org-element-property :end parent)))
23538 ((integer-or-marker-p end) (goto-char end))
23539 (t (message "No element at point")))))))
23541 (defun org-backward-element ()
23542 "Move backward by one element.
23543 Move to the previous element at the same level, when possible."
23544 (interactive)
23545 (cond ((bobp) (user-error "Cannot move further up"))
23546 ((org-with-limited-levels (org-at-heading-p))
23547 ;; At a headline, move to the previous one, if any, or stay
23548 ;; here.
23549 (let ((origin (point)))
23550 (org-with-limited-levels (org-backward-heading-same-level 1))
23551 ;; When current headline has no sibling above, move to its
23552 ;; parent.
23553 (when (= (point) origin)
23554 (or (org-with-limited-levels (org-up-heading-safe))
23555 (progn (goto-char origin)
23556 (user-error "Cannot move further up"))))))
23558 (let* ((trail (org-element-at-point 'keep-trail))
23559 (elem (car trail))
23560 (prev-elem (nth 1 trail))
23561 (beg (org-element-property :begin elem)))
23562 (cond
23563 ;; Move to beginning of current element if point isn't
23564 ;; there already.
23565 ((null beg) (message "No element at point"))
23566 ((/= (point) beg) (goto-char beg))
23567 (prev-elem (goto-char (org-element-property :begin prev-elem)))
23568 ((org-before-first-heading-p) (goto-char (point-min)))
23569 (t (org-back-to-heading)))))))
23571 (defun org-up-element ()
23572 "Move to upper element."
23573 (interactive)
23574 (if (org-with-limited-levels (org-at-heading-p))
23575 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23576 (let* ((elem (org-element-at-point))
23577 (parent (org-element-property :parent elem)))
23578 (if parent (goto-char (org-element-property :begin parent))
23579 (if (org-with-limited-levels (org-before-first-heading-p))
23580 (user-error "No surrounding element")
23581 (org-with-limited-levels (org-back-to-heading)))))))
23583 (defvar org-element-greater-elements)
23584 (defun org-down-element ()
23585 "Move to inner element."
23586 (interactive)
23587 (let ((element (org-element-at-point)))
23588 (cond
23589 ((memq (org-element-type element) '(plain-list table))
23590 (goto-char (org-element-property :contents-begin element))
23591 (forward-char))
23592 ((memq (org-element-type element) org-element-greater-elements)
23593 ;; If contents are hidden, first disclose them.
23594 (when (org-element-property :hiddenp element) (org-cycle))
23595 (goto-char (or (org-element-property :contents-begin element)
23596 (user-error "No content for this element"))))
23597 (t (user-error "No inner element")))))
23599 (defun org-drag-element-backward ()
23600 "Move backward element at point."
23601 (interactive)
23602 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
23603 (let* ((trail (org-element-at-point 'keep-trail))
23604 (elem (car trail))
23605 (prev-elem (nth 1 trail)))
23606 ;; Error out if no previous element or previous element is
23607 ;; a parent of the current one.
23608 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23609 (user-error "Cannot drag element backward")
23610 (let ((pos (point)))
23611 (org-element-swap-A-B prev-elem elem)
23612 (goto-char (+ (org-element-property :begin prev-elem)
23613 (- pos (org-element-property :begin elem)))))))))
23615 (defun org-drag-element-forward ()
23616 "Move forward element at point."
23617 (interactive)
23618 (let* ((pos (point))
23619 (elem (org-element-at-point)))
23620 (when (= (point-max) (org-element-property :end elem))
23621 (user-error "Cannot drag element forward"))
23622 (goto-char (org-element-property :end elem))
23623 (let ((next-elem (org-element-at-point)))
23624 (when (or (org-element-nested-p elem next-elem)
23625 (and (eq (org-element-type next-elem) 'headline)
23626 (not (eq (org-element-type elem) 'headline))))
23627 (goto-char pos)
23628 (user-error "Cannot drag element forward"))
23629 ;; Compute new position of point: it's shifted by NEXT-ELEM
23630 ;; body's length (without final blanks) and by the length of
23631 ;; blanks between ELEM and NEXT-ELEM.
23632 (let ((size-next (- (save-excursion
23633 (goto-char (org-element-property :end next-elem))
23634 (skip-chars-backward " \r\t\n")
23635 (forward-line)
23636 ;; Small correction if buffer doesn't end
23637 ;; with a newline character.
23638 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23639 (org-element-property :begin next-elem)))
23640 (size-blank (- (org-element-property :end elem)
23641 (save-excursion
23642 (goto-char (org-element-property :end elem))
23643 (skip-chars-backward " \r\t\n")
23644 (forward-line)
23645 (point)))))
23646 (org-element-swap-A-B elem next-elem)
23647 (goto-char (+ pos size-next size-blank))))))
23649 (defun org-drag-line-forward (arg)
23650 "Drag the line at point ARG lines forward."
23651 (interactive "p")
23652 (dotimes (n (abs arg))
23653 (let ((c (current-column)))
23654 (if (< 0 arg)
23655 (progn
23656 (beginning-of-line 2)
23657 (transpose-lines 1)
23658 (beginning-of-line 0))
23659 (transpose-lines 1)
23660 (beginning-of-line -1))
23661 (org-move-to-column c))))
23663 (defun org-drag-line-backward (arg)
23664 "Drag the line at point ARG lines backward."
23665 (interactive "p")
23666 (org-drag-line-forward (- arg)))
23668 (defun org-mark-element ()
23669 "Put point at beginning of this element, mark at end.
23671 Interactively, if this command is repeated or (in Transient Mark
23672 mode) if the mark is active, it marks the next element after the
23673 ones already marked."
23674 (interactive)
23675 (let (deactivate-mark)
23676 (if (and (org-called-interactively-p 'any)
23677 (or (and (eq last-command this-command) (mark t))
23678 (and transient-mark-mode mark-active)))
23679 (set-mark
23680 (save-excursion
23681 (goto-char (mark))
23682 (goto-char (org-element-property :end (org-element-at-point)))))
23683 (let ((element (org-element-at-point)))
23684 (end-of-line)
23685 (push-mark (org-element-property :end element) t t)
23686 (goto-char (org-element-property :begin element))))))
23688 (defun org-narrow-to-element ()
23689 "Narrow buffer to current element."
23690 (interactive)
23691 (let ((elem (org-element-at-point)))
23692 (cond
23693 ((eq (car elem) 'headline)
23694 (narrow-to-region
23695 (org-element-property :begin elem)
23696 (org-element-property :end elem)))
23697 ((memq (car elem) org-element-greater-elements)
23698 (narrow-to-region
23699 (org-element-property :contents-begin elem)
23700 (org-element-property :contents-end elem)))
23702 (narrow-to-region
23703 (org-element-property :begin elem)
23704 (org-element-property :end elem))))))
23706 (defun org-transpose-element ()
23707 "Transpose current and previous elements, keeping blank lines between.
23708 Point is moved after both elements."
23709 (interactive)
23710 (org-skip-whitespace)
23711 (let ((end (org-element-property :end (org-element-at-point))))
23712 (org-drag-element-backward)
23713 (goto-char end)))
23715 (defun org-unindent-buffer ()
23716 "Un-indent the visible part of the buffer.
23717 Relative indentation (between items, inside blocks, etc.) isn't
23718 modified."
23719 (interactive)
23720 (unless (eq major-mode 'org-mode)
23721 (user-error "Cannot un-indent a buffer not in Org mode"))
23722 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
23723 unindent-tree ; For byte-compiler.
23724 (unindent-tree
23725 (function
23726 (lambda (contents)
23727 (mapc
23728 (lambda (element)
23729 (if (memq (org-element-type element) '(headline section))
23730 (funcall unindent-tree (org-element-contents element))
23731 (save-excursion
23732 (save-restriction
23733 (narrow-to-region
23734 (org-element-property :begin element)
23735 (org-element-property :end element))
23736 (org-do-remove-indentation)))))
23737 (reverse contents))))))
23738 (funcall unindent-tree (org-element-contents parse-tree))))
23740 (defun org-show-subtree ()
23741 "Show everything after this heading at deeper levels."
23742 (interactive)
23743 (outline-flag-region
23744 (point)
23745 (save-excursion
23746 (org-end-of-subtree t t))
23747 nil))
23749 (defun org-show-entry ()
23750 "Show the body directly following this heading.
23751 Show the heading too, if it is currently invisible."
23752 (interactive)
23753 (save-excursion
23754 (condition-case nil
23755 (progn
23756 (org-back-to-heading t)
23757 (outline-flag-region
23758 (max (point-min) (1- (point)))
23759 (save-excursion
23760 (if (re-search-forward
23761 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23762 (match-beginning 1)
23763 (point-max)))
23764 nil)
23765 (org-cycle-hide-drawers 'children))
23766 (error nil))))
23768 (defun org-make-options-regexp (kwds &optional extra)
23769 "Make a regular expression for keyword lines."
23770 (concat
23771 "^#\\+\\("
23772 (mapconcat 'regexp-quote kwds "\\|")
23773 (if extra (concat "\\|" extra))
23774 "\\):[ \t]*\\(.*\\)"))
23776 ;; Make isearch reveal the necessary context
23777 (defun org-isearch-end ()
23778 "Reveal context after isearch exits."
23779 (when isearch-success ; only if search was successful
23780 (if (featurep 'xemacs)
23781 ;; Under XEmacs, the hook is run in the correct place,
23782 ;; we directly show the context.
23783 (org-show-context 'isearch)
23784 ;; In Emacs the hook runs *before* restoring the overlays.
23785 ;; So we have to use a one-time post-command-hook to do this.
23786 ;; (Emacs 22 has a special variable, see function `org-mode')
23787 (unless (and (boundp 'isearch-mode-end-hook-quit)
23788 isearch-mode-end-hook-quit)
23789 ;; Only when the isearch was not quitted.
23790 (org-add-hook 'post-command-hook 'org-isearch-post-command
23791 'append 'local)))))
23793 (defun org-isearch-post-command ()
23794 "Remove self from hook, and show context."
23795 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23796 (org-show-context 'isearch))
23799 ;;;; Integration with and fixes for other packages
23801 ;;; Imenu support
23803 (defvar org-imenu-markers nil
23804 "All markers currently used by Imenu.")
23805 (make-variable-buffer-local 'org-imenu-markers)
23807 (defun org-imenu-new-marker (&optional pos)
23808 "Return a new marker for use by Imenu, and remember the marker."
23809 (let ((m (make-marker)))
23810 (move-marker m (or pos (point)))
23811 (push m org-imenu-markers)
23814 (defun org-imenu-get-tree ()
23815 "Produce the index for Imenu."
23816 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23817 (setq org-imenu-markers nil)
23818 (let* ((n org-imenu-depth)
23819 (re (concat "^" (org-get-limited-outline-regexp)))
23820 (subs (make-vector (1+ n) nil))
23821 (last-level 0)
23822 m level head0 head)
23823 (save-excursion
23824 (save-restriction
23825 (widen)
23826 (goto-char (point-max))
23827 (while (re-search-backward re nil t)
23828 (setq level (org-reduced-level (funcall outline-level)))
23829 (when (and (<= level n)
23830 (looking-at org-complex-heading-regexp)
23831 (setq head0 (org-match-string-no-properties 4)))
23832 (setq head (org-link-display-format head0)
23833 m (org-imenu-new-marker))
23834 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23835 (if (>= level last-level)
23836 (push (cons head m) (aref subs level))
23837 (push (cons head (aref subs (1+ level))) (aref subs level))
23838 (loop for i from (1+ level) to n do (aset subs i nil)))
23839 (setq last-level level)))))
23840 (aref subs 1)))
23842 (eval-after-load "imenu"
23843 '(progn
23844 (add-hook 'imenu-after-jump-hook
23845 (lambda ()
23846 (if (derived-mode-p 'org-mode)
23847 (org-show-context 'org-goto))))))
23849 (defun org-link-display-format (link)
23850 "Replace a link with its the description.
23851 If there is no description, use the link target."
23852 (save-match-data
23853 (if (string-match org-bracket-link-analytic-regexp link)
23854 (replace-match (if (match-end 5)
23855 (match-string 5 link)
23856 (concat (match-string 1 link)
23857 (match-string 3 link)))
23858 nil t link)
23859 link)))
23861 (defun org-toggle-link-display ()
23862 "Toggle the literal or descriptive display of links."
23863 (interactive)
23864 (if org-descriptive-links
23865 (progn (org-remove-from-invisibility-spec '(org-link))
23866 (org-restart-font-lock)
23867 (setq org-descriptive-links nil))
23868 (progn (add-to-invisibility-spec '(org-link))
23869 (org-restart-font-lock)
23870 (setq org-descriptive-links t))))
23872 ;; Speedbar support
23874 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23875 "Overlay marking the agenda restriction line in speedbar.")
23876 (overlay-put org-speedbar-restriction-lock-overlay
23877 'face 'org-agenda-restriction-lock)
23878 (overlay-put org-speedbar-restriction-lock-overlay
23879 'help-echo "Agendas are currently limited to this item.")
23880 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23882 (defun org-speedbar-set-agenda-restriction ()
23883 "Restrict future agenda commands to the location at point in speedbar.
23884 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23885 (interactive)
23886 (require 'org-agenda)
23887 (let (p m tp np dir txt)
23888 (cond
23889 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23890 'org-imenu t))
23891 (setq m (get-text-property p 'org-imenu-marker))
23892 (with-current-buffer (marker-buffer m)
23893 (goto-char m)
23894 (org-agenda-set-restriction-lock 'subtree)))
23895 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23896 'speedbar-function 'speedbar-find-file))
23897 (setq tp (previous-single-property-change
23898 (1+ p) 'speedbar-function)
23899 np (next-single-property-change
23900 tp 'speedbar-function)
23901 dir (speedbar-line-directory)
23902 txt (buffer-substring-no-properties (or tp (point-min))
23903 (or np (point-max))))
23904 (with-current-buffer (find-file-noselect
23905 (let ((default-directory dir))
23906 (expand-file-name txt)))
23907 (unless (derived-mode-p 'org-mode)
23908 (user-error "Cannot restrict to non-Org-mode file"))
23909 (org-agenda-set-restriction-lock 'file)))
23910 (t (user-error "Don't know how to restrict Org-mode's agenda")))
23911 (move-overlay org-speedbar-restriction-lock-overlay
23912 (point-at-bol) (point-at-eol))
23913 (setq current-prefix-arg nil)
23914 (org-agenda-maybe-redo)))
23916 (defvar speedbar-file-key-map)
23917 (declare-function speedbar-add-supported-extension "speedbar" (extension))
23918 (eval-after-load "speedbar"
23919 '(progn
23920 (speedbar-add-supported-extension ".org")
23921 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23922 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23923 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23924 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23925 (add-hook 'speedbar-visiting-tag-hook
23926 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23928 ;;; Fixes and Hacks for problems with other packages
23930 ;; Make flyspell not check words in links, to not mess up our keymap
23931 (defvar org-element-affiliated-keywords) ; From org-element.el
23932 (defvar org-element-block-name-alist) ; From org-element.el
23933 (defun org-mode-flyspell-verify ()
23934 "Don't let flyspell put overlays at active buttons, or on
23935 {todo,all-time,additional-option-like}-keywords."
23936 (require 'org-element) ; For `org-element-affiliated-keywords'
23937 (let ((pos (max (1- (point)) (point-min)))
23938 (word (thing-at-point 'word)))
23939 (and (not (get-text-property pos 'keymap))
23940 (not (get-text-property pos 'org-no-flyspell))
23941 (not (member word org-todo-keywords-1))
23942 (not (member word org-all-time-keywords))
23943 (not (member word org-options-keywords))
23944 (not (member word (mapcar 'car org-startup-options)))
23945 (not (member-ignore-case word org-element-affiliated-keywords))
23946 (not (member-ignore-case word (org-get-export-keywords)))
23947 (not (member-ignore-case
23948 word (mapcar 'car org-element-block-name-alist)))
23949 (not (member-ignore-case word '("BEGIN" "END" "ATTR")))
23950 (not (org-in-src-block-p)))))
23952 (defun org-remove-flyspell-overlays-in (beg end)
23953 "Remove flyspell overlays in region."
23954 (and (org-bound-and-true-p flyspell-mode)
23955 (fboundp 'flyspell-delete-region-overlays)
23956 (flyspell-delete-region-overlays beg end))
23957 (add-text-properties beg end '(org-no-flyspell t)))
23959 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23960 (eval-after-load "bookmark"
23961 '(if (boundp 'bookmark-after-jump-hook)
23962 ;; We can use the hook
23963 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23964 ;; Hook not available, use advice
23965 (defadvice bookmark-jump (after org-make-visible activate)
23966 "Make the position visible."
23967 (org-bookmark-jump-unhide))))
23969 ;; Make sure saveplace shows the location if it was hidden
23970 (eval-after-load "saveplace"
23971 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23972 "Make the position visible."
23973 (org-bookmark-jump-unhide)))
23975 ;; Make sure ecb shows the location if it was hidden
23976 (eval-after-load "ecb"
23977 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23978 "Make hierarchy visible when jumping into location from ECB tree buffer."
23979 (if (derived-mode-p 'org-mode)
23980 (org-show-context))))
23982 (defun org-bookmark-jump-unhide ()
23983 "Unhide the current position, to show the bookmark location."
23984 (and (derived-mode-p 'org-mode)
23985 (or (outline-invisible-p)
23986 (save-excursion (goto-char (max (point-min) (1- (point))))
23987 (outline-invisible-p)))
23988 (org-show-context 'bookmark-jump)))
23990 ;; Make session.el ignore our circular variable
23991 (defvar session-globals-exclude)
23992 (eval-after-load "session"
23993 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23995 ;;;; Finish up
23997 (provide 'org)
23999 (run-hooks 'org-load-hook)
24001 ;;; org.el ends here