org: add forward declarations
[org-mode.git] / lisp / org.el
blob235019cadcbcaa72e8e744092600eb646ecbb31a
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)))
5431 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5433 ;; Setup the pcomplete hooks
5434 (set (make-local-variable 'pcomplete-command-completion-function)
5435 'org-pcomplete-initial)
5436 (set (make-local-variable 'pcomplete-command-name-function)
5437 'org-command-at-point)
5438 (set (make-local-variable 'pcomplete-default-completion-function)
5439 'ignore)
5440 (set (make-local-variable 'pcomplete-parse-arguments-function)
5441 'org-parse-arguments)
5442 (set (make-local-variable 'pcomplete-termination-string) "")
5443 (when (>= emacs-major-version 23)
5444 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5446 ;; If empty file that did not turn on org-mode automatically, make it to.
5447 (if (and org-insert-mode-line-in-empty-file
5448 (org-called-interactively-p 'any)
5449 (= (point-min) (point-max)))
5450 (insert "# -*- mode: org -*-\n\n"))
5451 (unless org-inhibit-startup
5452 (org-unmodified
5453 (and org-startup-with-beamer-mode (org-beamer-mode))
5454 (when org-startup-align-all-tables
5455 (org-table-map-tables 'org-table-align 'quietly))
5456 (when org-startup-with-inline-images
5457 (org-display-inline-images))
5458 (when org-startup-with-latex-preview
5459 (org-preview-latex-fragment))
5460 (unless org-inhibit-startup-visibility-stuff
5461 (org-set-startup-visibility))))
5462 ;; Try to set org-hide correctly
5463 (let ((foreground (org-find-invisible-foreground)))
5464 (if foreground
5465 (set-face-foreground 'org-hide foreground))))
5467 ;; Update `customize-package-emacs-version-alist'
5468 (add-to-list 'customize-package-emacs-version-alist
5469 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5470 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5471 ("8.2.6" . "24.4")))
5473 (defvar org-mode-transpose-word-syntax-table
5474 (let ((st (make-syntax-table)))
5475 (mapc (lambda(c) (modify-syntax-entry
5476 (string-to-char (car c)) "w p" st))
5477 org-emphasis-alist)
5478 st))
5480 (when (fboundp 'abbrev-table-put)
5481 (abbrev-table-put org-mode-abbrev-table
5482 :parents (list text-mode-abbrev-table)))
5484 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5486 (defsubst org-fix-ellipsis-at-bol ()
5487 (save-excursion (goto-char (window-start)) (recenter 0)))
5489 (defun org-find-invisible-foreground ()
5490 (let ((candidates (remove
5491 "unspecified-bg"
5492 (nconc
5493 (list (face-background 'default)
5494 (face-background 'org-default))
5495 (mapcar
5496 (lambda (alist)
5497 (when (boundp alist)
5498 (cdr (assoc 'background-color (symbol-value alist)))))
5499 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5500 (list (face-foreground 'org-hide))))))
5501 (car (remove nil candidates))))
5503 (defun org-current-time (&optional rounding-minutes past)
5504 "Current time, possibly rounded to ROUNDING-MINUTES.
5505 When ROUNDING-MINUTES is not an integer, fall back on the car of
5506 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5507 the rounding returns a past time."
5508 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5509 (car org-time-stamp-rounding-minutes)))
5510 (time (decode-time)) res)
5511 (if (< r 1)
5512 (current-time)
5513 (setq res
5514 (apply 'encode-time
5515 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5516 (nthcdr 2 time))))
5517 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5518 (seconds-to-time (- (org-float-time res) (* r 60)))
5519 res))))
5521 (defun org-today ()
5522 "Return today date, considering `org-extend-today-until'."
5523 (time-to-days
5524 (time-subtract (current-time)
5525 (list 0 (* 3600 org-extend-today-until) 0))))
5527 ;;;; Font-Lock stuff, including the activators
5529 (defvar org-mouse-map (make-sparse-keymap))
5530 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5531 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5532 (when org-mouse-1-follows-link
5533 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5534 (when org-tab-follows-link
5535 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5536 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5538 (require 'font-lock)
5540 (defconst org-non-link-chars "]\t\n\r<>")
5541 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5542 "shell" "elisp" "doi" "message"))
5543 (defvar org-link-types-re nil
5544 "Matches a link that has a url-like prefix like \"http:\"")
5545 (defvar org-link-re-with-space nil
5546 "Matches a link with spaces, optional angular brackets around it.")
5547 (defvar org-link-re-with-space2 nil
5548 "Matches a link with spaces, optional angular brackets around it.")
5549 (defvar org-link-re-with-space3 nil
5550 "Matches a link with spaces, only for internal part in bracket links.")
5551 (defvar org-angle-link-re nil
5552 "Matches link with angular brackets, spaces are allowed.")
5553 (defvar org-plain-link-re nil
5554 "Matches plain link, without spaces.")
5555 (defvar org-bracket-link-regexp nil
5556 "Matches a link in double brackets.")
5557 (defvar org-bracket-link-analytic-regexp nil
5558 "Regular expression used to analyze links.
5559 Here is what the match groups contain after a match:
5560 1: http:
5561 2: http
5562 3: path
5563 4: [desc]
5564 5: desc")
5565 (defvar org-bracket-link-analytic-regexp++ nil
5566 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5567 (defvar org-any-link-re nil
5568 "Regular expression matching any link.")
5570 (defconst org-match-sexp-depth 3
5571 "Number of stacked braces for sub/superscript matching.")
5573 (defun org-create-multibrace-regexp (left right n)
5574 "Create a regular expression which will match a balanced sexp.
5575 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5576 as single character strings.
5577 The regexp returned will match the entire expression including the
5578 delimiters. It will also define a single group which contains the
5579 match except for the outermost delimiters. The maximum depth of
5580 stacked delimiters is N. Escaping delimiters is not possible."
5581 (let* ((nothing (concat "[^" left right "]*?"))
5582 (or "\\|")
5583 (re nothing)
5584 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5585 (while (> n 1)
5586 (setq n (1- n)
5587 re (concat re or next)
5588 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5589 (concat left "\\(" re "\\)" right)))
5591 (defvar org-match-substring-regexp
5592 (concat
5593 "\\(\\S-\\)\\([_^]\\)\\("
5594 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5595 "\\|"
5596 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5597 "\\|"
5598 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5599 "The regular expression matching a sub- or superscript.")
5601 (defvar org-match-substring-with-braces-regexp
5602 (concat
5603 "\\(\\S-\\)\\([_^]\\)\\("
5604 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5605 "\\)")
5606 "The regular expression matching a sub- or superscript, forcing braces.")
5608 (defun org-make-link-regexps ()
5609 "Update the link regular expressions.
5610 This should be called after the variable `org-link-types' has changed."
5611 (let ((types-re (regexp-opt org-link-types t)))
5612 (setq org-link-types-re
5613 (concat "\\`" types-re ":")
5614 org-link-re-with-space
5615 (concat "<?" types-re ":"
5616 "\\([^" org-non-link-chars " ]"
5617 "[^" org-non-link-chars "]*"
5618 "[^" org-non-link-chars " ]\\)>?")
5619 org-link-re-with-space2
5620 (concat "<?" types-re ":"
5621 "\\([^" org-non-link-chars " ]"
5622 "[^\t\n\r]*"
5623 "[^" org-non-link-chars " ]\\)>?")
5624 org-link-re-with-space3
5625 (concat "<?" types-re ":"
5626 "\\([^" org-non-link-chars " ]"
5627 "[^\t\n\r]*\\)")
5628 org-angle-link-re
5629 (concat "<" types-re ":"
5630 "\\([^" org-non-link-chars " ]"
5631 "[^" org-non-link-chars "]*"
5632 "\\)>")
5633 org-plain-link-re
5634 (concat
5635 "\\<" types-re ":"
5636 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5637 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5638 org-bracket-link-regexp
5639 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5640 org-bracket-link-analytic-regexp
5641 (concat
5642 "\\[\\["
5643 "\\(" types-re ":\\)?"
5644 "\\([^]]+\\)"
5645 "\\]"
5646 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5647 "\\]")
5648 org-bracket-link-analytic-regexp++
5649 (concat
5650 "\\[\\["
5651 "\\(" (regexp-opt (cons "coderef" org-link-types) t) ":\\)?"
5652 "\\([^]]+\\)"
5653 "\\]"
5654 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5655 "\\]")
5656 org-any-link-re
5657 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5658 org-angle-link-re "\\)\\|\\("
5659 org-plain-link-re "\\)"))))
5661 (org-make-link-regexps)
5663 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5664 "Regular expression for fast time stamp matching.")
5665 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5666 "Regular expression for fast time stamp matching.")
5667 (defconst org-ts-regexp0
5668 "\\(\\([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 This one does not require the space after the date, so it can be used
5671 on a string that terminates immediately after the date.")
5672 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5673 "Regular expression matching time strings for analysis.")
5674 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5675 "Regular expression matching time stamps, with groups.")
5676 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5677 "Regular expression matching time stamps (also [..]), with groups.")
5678 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5679 "Regular expression matching a time stamp range.")
5680 (defconst org-tr-regexp-both
5681 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5682 "Regular expression matching a time stamp range.")
5683 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5684 org-ts-regexp "\\)?")
5685 "Regular expression matching a time stamp or time stamp range.")
5686 (defconst org-tsr-regexp-both
5687 (concat org-ts-regexp-both "\\(--?-?"
5688 org-ts-regexp-both "\\)?")
5689 "Regular expression matching a time stamp or time stamp range.
5690 The time stamps may be either active or inactive.")
5692 (defvar org-emph-face nil)
5694 (defun org-do-emphasis-faces (limit)
5695 "Run through the buffer and add overlays to emphasized strings."
5696 (let (rtn a)
5697 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5698 (let* ((border (char-after (match-beginning 3)))
5699 (bre (regexp-quote (char-to-string border))))
5700 (if (and (not (= border (char-after (match-beginning 4))))
5701 (not (save-match-data
5702 (string-match (concat bre ".*" bre)
5703 (replace-regexp-in-string
5704 "\n" " "
5705 (substring (match-string 2) 1 -1))))))
5706 (progn
5707 (setq rtn t)
5708 (setq a (assoc (match-string 3) org-emphasis-alist))
5709 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5710 'face
5711 (nth 1 a))
5712 (and (nth 2 a)
5713 (org-remove-flyspell-overlays-in
5714 (match-beginning 0) (match-end 0)))
5715 (add-text-properties (match-beginning 2) (match-end 2)
5716 '(font-lock-multiline t org-emphasis t))
5717 (when org-hide-emphasis-markers
5718 (add-text-properties (match-end 4) (match-beginning 5)
5719 '(invisible org-link))
5720 (add-text-properties (match-beginning 3) (match-end 3)
5721 '(invisible org-link))))))
5722 (goto-char (1+ (match-beginning 0))))
5723 rtn))
5725 (defun org-emphasize (&optional char)
5726 "Insert or change an emphasis, i.e. a font like bold or italic.
5727 If there is an active region, change that region to a new emphasis.
5728 If there is no region, just insert the marker characters and position
5729 the cursor between them.
5730 CHAR should be the marker character. If it is a space, it means to
5731 remove the emphasis of the selected region.
5732 If CHAR is not given (for example in an interactive call) it will be
5733 prompted for."
5734 (interactive)
5735 (let ((erc org-emphasis-regexp-components)
5736 (prompt "")
5737 (string "") beg end move c s)
5738 (if (org-region-active-p)
5739 (setq beg (region-beginning) end (region-end)
5740 string (buffer-substring beg end))
5741 (setq move t))
5743 (unless char
5744 (message "Emphasis marker or tag: [%s]"
5745 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5746 (setq char (read-char-exclusive)))
5747 (if (equal char ?\ )
5748 (setq s "" move nil)
5749 (unless (assoc (char-to-string char) org-emphasis-alist)
5750 (user-error "No such emphasis marker: \"%c\"" char))
5751 (setq s (char-to-string char)))
5752 (while (and (> (length string) 1)
5753 (equal (substring string 0 1) (substring string -1))
5754 (assoc (substring string 0 1) org-emphasis-alist))
5755 (setq string (substring string 1 -1)))
5756 (setq string (concat s string s))
5757 (if beg (delete-region beg end))
5758 (unless (or (bolp)
5759 (string-match (concat "[" (nth 0 erc) "\n]")
5760 (char-to-string (char-before (point)))))
5761 (insert " "))
5762 (unless (or (eobp)
5763 (string-match (concat "[" (nth 1 erc) "\n]")
5764 (char-to-string (char-after (point)))))
5765 (insert " ") (backward-char 1))
5766 (insert string)
5767 (and move (backward-char 1))))
5769 (defconst org-nonsticky-props
5770 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5772 (defsubst org-rear-nonsticky-at (pos)
5773 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5775 (defun org-activate-plain-links (limit)
5776 "Run through the buffer and add overlays to links."
5777 (let (f hl)
5778 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5779 (not (org-in-src-block-p)))
5780 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5781 (setq f (get-text-property (match-beginning 0) 'face))
5782 (setq hl (org-match-string-no-properties 0))
5783 (if (or (eq f 'org-tag)
5784 (and (listp f) (memq 'org-tag f)))
5786 (add-text-properties (match-beginning 0) (match-end 0)
5787 (list 'mouse-face 'highlight
5788 'face 'org-link
5789 'htmlize-link `(:uri ,hl)
5790 'keymap org-mouse-map))
5791 (org-rear-nonsticky-at (match-end 0)))
5792 t)))
5794 (defun org-activate-code (limit)
5795 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5796 (progn
5797 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5798 (remove-text-properties (match-beginning 0) (match-end 0)
5799 '(display t invisible t intangible t))
5800 t)))
5802 (defcustom org-src-fontify-natively nil
5803 "When non-nil, fontify code in code blocks."
5804 :type 'boolean
5805 :version "24.1"
5806 :group 'org-appearance
5807 :group 'org-babel)
5809 (defcustom org-allow-promoting-top-level-subtree nil
5810 "When non-nil, allow promoting a top level subtree.
5811 The leading star of the top level headline will be replaced
5812 by a #."
5813 :type 'boolean
5814 :version "24.1"
5815 :group 'org-appearance)
5817 (defun org-fontify-meta-lines-and-blocks (limit)
5818 (condition-case nil
5819 (org-fontify-meta-lines-and-blocks-1 limit)
5820 (error (message "org-mode fontification error"))))
5822 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5823 "Fontify #+ lines and blocks."
5824 (let ((case-fold-search t))
5825 (if (re-search-forward
5826 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5827 limit t)
5828 (let ((beg (match-beginning 0))
5829 (block-start (match-end 0))
5830 (block-end nil)
5831 (lang (match-string 7))
5832 (beg1 (line-beginning-position 2))
5833 (dc1 (downcase (match-string 2)))
5834 (dc3 (downcase (match-string 3)))
5835 end end1 quoting block-type ovl)
5836 (cond
5837 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5838 ;; a single line of backend-specific content
5839 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5840 (remove-text-properties (match-beginning 0) (match-end 0)
5841 '(display t invisible t intangible t))
5842 (add-text-properties (match-beginning 1) (match-end 3)
5843 '(font-lock-fontified t face org-meta-line))
5844 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5845 '(font-lock-fontified t face org-block))
5846 ; for backend-specific code
5848 ((and (match-end 4) (equal dc3 "+begin"))
5849 ;; Truly a block
5850 (setq block-type (downcase (match-string 5))
5851 quoting (member block-type org-protecting-blocks))
5852 (when (re-search-forward
5853 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5854 nil t) ;; on purpose, we look further than LIMIT
5855 (setq end (min (point-max) (match-end 0))
5856 end1 (min (point-max) (1- (match-beginning 0))))
5857 (setq block-end (match-beginning 0))
5858 (when quoting
5859 (remove-text-properties beg end
5860 '(display t invisible t intangible t)))
5861 (add-text-properties
5862 beg end
5863 '(font-lock-fontified t font-lock-multiline t))
5864 (add-text-properties beg beg1 '(face org-meta-line))
5865 (add-text-properties end1 (min (point-max) (1+ end))
5866 '(face org-meta-line)) ; for end_src
5867 (cond
5868 ((and lang (not (string= lang "")) org-src-fontify-natively)
5869 (org-src-font-lock-fontify-block lang block-start block-end)
5870 ;; remove old background overlays
5871 (mapc (lambda (ov)
5872 (if (eq (overlay-get ov 'face) 'org-block-background)
5873 (delete-overlay ov)))
5874 (overlays-at (/ (+ beg1 block-end) 2)))
5875 ;; add a background overlay
5876 (setq ovl (make-overlay beg1 block-end))
5877 (overlay-put ovl 'face 'org-block-background)
5878 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5879 (quoting
5880 (add-text-properties beg1 (min (point-max) (1+ end1))
5881 '(face org-block))) ; end of source block
5882 ((not org-fontify-quote-and-verse-blocks))
5883 ((string= block-type "quote")
5884 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5885 ((string= block-type "verse")
5886 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5887 (add-text-properties beg beg1 '(face org-block-begin-line))
5888 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5889 '(face org-block-end-line))
5891 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5892 (add-text-properties
5893 beg (match-end 3)
5894 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5895 '(font-lock-fontified t invisible t)
5896 '(font-lock-fontified t face org-document-info-keyword)))
5897 (add-text-properties
5898 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5899 (if (string-equal dc1 "+title:")
5900 '(font-lock-fontified t face org-document-title)
5901 '(font-lock-fontified t face org-document-info))))
5902 ((or (equal dc1 "+results")
5903 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5904 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5905 "+call:" "+header:" "+headers:" "+name:"))
5906 (and (match-end 4) (equal dc3 "+attr")))
5907 (add-text-properties
5908 beg (match-end 0)
5909 '(font-lock-fontified t face org-meta-line))
5911 ((member dc3 '(" " ""))
5912 (add-text-properties
5913 beg (match-end 0)
5914 '(font-lock-fontified t face font-lock-comment-face)))
5915 ((not (member (char-after beg) '(?\ ?\t)))
5916 ;; just any other in-buffer setting, but not indented
5917 (add-text-properties
5918 beg (match-end 0)
5919 '(font-lock-fontified t face org-meta-line))
5921 (t nil))))))
5923 (defun org-activate-angle-links (limit)
5924 "Run through the buffer and add overlays to links."
5925 (if (and (re-search-forward org-angle-link-re limit t)
5926 (not (org-in-src-block-p)))
5927 (progn
5928 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5929 (add-text-properties (match-beginning 0) (match-end 0)
5930 (list 'mouse-face 'highlight
5931 'keymap org-mouse-map))
5932 (org-rear-nonsticky-at (match-end 0))
5933 t)))
5935 (defun org-activate-footnote-links (limit)
5936 "Run through the buffer and add overlays to footnotes."
5937 (let ((fn (org-footnote-next-reference-or-definition limit)))
5938 (when fn
5939 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5940 (org-remove-flyspell-overlays-in beg end)
5941 (add-text-properties beg end
5942 (list 'mouse-face 'highlight
5943 'keymap org-mouse-map
5944 'help-echo
5945 (if (= (point-at-bol) beg)
5946 "Footnote definition"
5947 "Footnote reference")
5948 'font-lock-fontified t
5949 'font-lock-multiline t
5950 'face 'org-footnote))))))
5952 (defun org-activate-bracket-links (limit)
5953 "Run through the buffer and add overlays to bracketed links."
5954 (if (and (re-search-forward org-bracket-link-regexp limit t)
5955 (not (org-in-src-block-p)))
5956 (let* ((hl (org-match-string-no-properties 1))
5957 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
5958 (ip (org-maybe-intangible
5959 (list 'invisible 'org-link
5960 'keymap org-mouse-map 'mouse-face 'highlight
5961 'font-lock-multiline t 'help-echo help
5962 'htmlize-link `(:uri ,hl))))
5963 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5964 'font-lock-multiline t 'help-echo help
5965 'htmlize-link `(:uri ,hl))))
5966 ;; We need to remove the invisible property here. Table narrowing
5967 ;; may have made some of this invisible.
5968 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5969 (remove-text-properties (match-beginning 0) (match-end 0)
5970 '(invisible nil))
5971 (if (match-end 3)
5972 (progn
5973 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5974 (org-rear-nonsticky-at (match-beginning 3))
5975 (add-text-properties (match-beginning 3) (match-end 3) vp)
5976 (org-rear-nonsticky-at (match-end 3))
5977 (add-text-properties (match-end 3) (match-end 0) ip)
5978 (org-rear-nonsticky-at (match-end 0)))
5979 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5980 (org-rear-nonsticky-at (match-beginning 1))
5981 (add-text-properties (match-beginning 1) (match-end 1) vp)
5982 (org-rear-nonsticky-at (match-end 1))
5983 (add-text-properties (match-end 1) (match-end 0) ip)
5984 (org-rear-nonsticky-at (match-end 0)))
5985 t)))
5987 (defun org-activate-dates (limit)
5988 "Run through the buffer and add overlays to dates."
5989 (if (and (re-search-forward org-tsr-regexp-both limit t)
5990 (not (equal (char-before (match-beginning 0)) 91)))
5991 (progn
5992 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5993 (add-text-properties (match-beginning 0) (match-end 0)
5994 (list 'mouse-face 'highlight
5995 'keymap org-mouse-map))
5996 (org-rear-nonsticky-at (match-end 0))
5997 (when org-display-custom-times
5998 (if (match-end 3)
5999 (org-display-custom-time (match-beginning 3) (match-end 3)))
6000 (org-display-custom-time (match-beginning 1) (match-end 1)))
6001 t)))
6003 (defvar org-target-link-regexp nil
6004 "Regular expression matching radio targets in plain text.")
6005 (make-variable-buffer-local 'org-target-link-regexp)
6006 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
6007 "Regular expression matching a link target.")
6008 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
6009 "Regular expression matching a radio target.")
6010 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
6011 "Regular expression matching any target.")
6013 (defun org-activate-target-links (limit)
6014 "Run through the buffer and add overlays to target matches."
6015 (when org-target-link-regexp
6016 (let ((case-fold-search t))
6017 (if (re-search-forward org-target-link-regexp limit t)
6018 (progn
6019 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6020 (add-text-properties (match-beginning 0) (match-end 0)
6021 (list 'mouse-face 'highlight
6022 'keymap org-mouse-map
6023 'help-echo "Radio target link"
6024 'org-linked-text t))
6025 (org-rear-nonsticky-at (match-end 0))
6026 t)))))
6028 (defun org-update-radio-target-regexp ()
6029 "Find all radio targets in this file and update the regular expression."
6030 (interactive)
6031 (when (memq 'radio org-activate-links)
6032 (setq org-target-link-regexp
6033 (org-make-target-link-regexp (org-all-targets 'radio)))
6034 (org-restart-font-lock)))
6036 (defun org-hide-wide-columns (limit)
6037 (let (s e)
6038 (setq s (text-property-any (point) (or limit (point-max))
6039 'org-cwidth t))
6040 (when s
6041 (setq e (next-single-property-change s 'org-cwidth))
6042 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6043 (goto-char e)
6044 t)))
6046 (defvar org-latex-and-related-regexp nil
6047 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6048 (defvar org-match-substring-regexp)
6049 (defvar org-match-substring-with-braces-regexp)
6051 (defun org-compute-latex-and-related-regexp ()
6052 "Compute regular expression for LaTeX, entities and sub/superscript.
6053 Result depends on variable `org-highlight-latex-and-related'."
6054 (org-set-local
6055 'org-latex-and-related-regexp
6056 (let* ((re-sub
6057 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6058 ((eq org-use-sub-superscripts '{})
6059 (list org-match-substring-with-braces-regexp))
6060 (org-use-sub-superscripts (list org-match-substring-regexp))))
6061 (re-latex
6062 (when (memq 'latex org-highlight-latex-and-related)
6063 (let ((matchers (plist-get org-format-latex-options :matchers)))
6064 (delq nil
6065 (mapcar (lambda (x)
6066 (and (member (car x) matchers) (nth 1 x)))
6067 org-latex-regexps)))))
6068 (re-entities
6069 (when (memq 'entities org-highlight-latex-and-related)
6070 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6071 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6073 (defun org-do-latex-and-related (limit)
6074 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6075 LIMIT bounds the search for syntax to highlight. Stop at first
6076 highlighted object, if any. Return t if some highlighting was
6077 done, nil otherwise."
6078 (when (org-string-nw-p org-latex-and-related-regexp)
6079 (catch 'found
6080 (while (re-search-forward org-latex-and-related-regexp limit t)
6081 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6082 'face))
6083 '(org-code org-verbatim underline))
6084 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6085 '(?_ ?^))
6087 0)))
6088 (font-lock-prepend-text-property
6089 (+ offset (match-beginning 0)) (match-end 0)
6090 'face 'org-latex-and-related)
6091 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6092 '(font-lock-multiline t)))
6093 (throw 'found t)))
6094 nil)))
6096 (defun org-restart-font-lock ()
6097 "Restart `font-lock-mode', to force refontification."
6098 (when (and (boundp 'font-lock-mode) font-lock-mode)
6099 (font-lock-mode -1)
6100 (font-lock-mode 1)))
6102 (defun org-all-targets (&optional radio)
6103 "Return a list of all targets in this file.
6104 When optional argument RADIO is non-nil, only find radio
6105 targets."
6106 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
6107 (save-excursion
6108 (goto-char (point-min))
6109 (while (re-search-forward re nil t)
6110 ;; Make sure point is really within the object.
6111 (backward-char)
6112 (let ((obj (org-element-context)))
6113 (when (memq (org-element-type obj) '(radio-target target))
6114 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
6115 rtn)))
6117 (defun org-make-target-link-regexp (targets)
6118 "Make regular expression matching all strings in TARGETS.
6119 The regular expression finds the targets also if there is a line break
6120 between words."
6121 (and targets
6122 (concat
6123 "\\_<\\("
6124 (mapconcat
6125 (lambda (x)
6126 (setq x (regexp-quote x))
6127 (while (string-match " +" x)
6128 (setq x (replace-match "\\s-+" t t x)))
6130 targets
6131 "\\|")
6132 "\\)\\_>")))
6134 (defun org-activate-tags (limit)
6135 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6136 (progn
6137 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6138 (add-text-properties (match-beginning 1) (match-end 1)
6139 (list 'mouse-face 'highlight
6140 'keymap org-mouse-map))
6141 (org-rear-nonsticky-at (match-end 1))
6142 t)))
6144 (defun org-outline-level ()
6145 "Compute the outline level of the heading at point.
6146 If this is called at a normal headline, the level is the number of stars.
6147 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6148 (save-excursion
6149 (if (not (condition-case nil
6150 (org-back-to-heading t)
6151 (error nil)))
6153 (looking-at org-outline-regexp)
6154 (1- (- (match-end 0) (match-beginning 0))))))
6156 (defvar org-font-lock-keywords nil)
6158 (defsubst org-re-property (property &optional literal)
6159 "Return a regexp matching a PROPERTY line.
6160 Match group 3 will be set to the value if it exists."
6161 (concat "^\\(?4:[ \t]*\\)\\(?1::\\(?2:"
6162 (if literal property (regexp-quote property))
6163 "\\):\\)[ \t]+\\(?3:[^ \t\r\n].*?\\)\\(?5:[ \t]*\\)$"))
6165 (defconst org-property-re
6166 (org-re-property ".*?" 'literal)
6167 "Regular expression matching a property line.
6168 There are four matching groups:
6169 1: :PROPKEY: including the leading and trailing colon,
6170 2: PROPKEY without the leading and trailing colon,
6171 3: PROPVAL without leading or trailing spaces,
6172 4: the indentation of the current line,
6173 5: trailing whitespace.")
6175 (defvar org-font-lock-hook nil
6176 "Functions to be called for special font lock stuff.")
6178 (defvar org-font-lock-set-keywords-hook nil
6179 "Functions that can manipulate `org-font-lock-extra-keywords'.
6180 This is called after `org-font-lock-extra-keywords' is defined, but before
6181 it is installed to be used by font lock. This can be useful if something
6182 needs to be inserted at a specific position in the font-lock sequence.")
6184 (defun org-font-lock-hook (limit)
6185 "Run `org-font-lock-hook' within LIMIT."
6186 (run-hook-with-args 'org-font-lock-hook limit))
6188 (defun org-set-font-lock-defaults ()
6189 "Set font lock defaults for the current buffer."
6190 (let* ((em org-fontify-emphasized-text)
6191 (lk org-activate-links)
6192 (org-font-lock-extra-keywords
6193 (list
6194 ;; Call the hook
6195 '(org-font-lock-hook)
6196 ;; Headlines
6197 `(,(if org-fontify-whole-heading-line
6198 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6199 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6200 (1 (org-get-level-face 1))
6201 (2 (org-get-level-face 2))
6202 (3 (org-get-level-face 3)))
6203 ;; Table lines
6204 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6205 (1 'org-table t))
6206 ;; Table internals
6207 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6208 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6209 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6210 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6211 ;; Drawers
6212 (list org-drawer-regexp '(0 'org-special-keyword t))
6213 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
6214 ;; Properties
6215 (list org-property-re
6216 '(1 'org-special-keyword t)
6217 '(3 'org-property-value t))
6218 ;; Links
6219 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6220 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6221 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6222 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6223 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6224 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6225 (if (memq 'footnote lk) '(org-activate-footnote-links))
6226 ;; Targets.
6227 (list org-any-target-regexp '(0 'org-target t))
6228 ;; Diary sexps.
6229 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6230 ;; Macro
6231 '("{{{.+}}}" (0 'org-macro t))
6232 '(org-hide-wide-columns (0 nil append))
6233 ;; TODO keyword
6234 (list (format org-heading-keyword-regexp-format
6235 org-todo-regexp)
6236 '(2 (org-get-todo-face 2) t))
6237 ;; DONE
6238 (if org-fontify-done-headline
6239 (list (format org-heading-keyword-regexp-format
6240 (concat
6241 "\\(?:"
6242 (mapconcat 'regexp-quote org-done-keywords "\\|")
6243 "\\)"))
6244 '(2 'org-headline-done t))
6245 nil)
6246 ;; Priorities
6247 '(org-font-lock-add-priority-faces)
6248 ;; Tags
6249 '(org-font-lock-add-tag-faces)
6250 ;; Tags groups
6251 (if (and org-group-tags org-tag-groups-alist)
6252 (list (concat org-outline-regexp-bol ".+\\(:"
6253 (regexp-opt (mapcar 'car org-tag-groups-alist))
6254 ":\\).*$")
6255 '(1 'org-tag-group prepend)))
6256 ;; Special keywords
6257 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6258 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6259 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6260 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6261 ;; Emphasis
6262 (if em
6263 (if (featurep 'xemacs)
6264 '(org-do-emphasis-faces (0 nil append))
6265 '(org-do-emphasis-faces)))
6266 ;; Checkboxes
6267 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6268 1 'org-checkbox prepend)
6269 (if (cdr (assq 'checkbox org-list-automatic-rules))
6270 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6271 (0 (org-get-checkbox-statistics-face) t)))
6272 ;; Description list items
6273 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6274 1 'org-list-dt prepend)
6275 ;; ARCHIVEd headings
6276 (list (concat
6277 org-outline-regexp-bol
6278 "\\(.*:" org-archive-tag ":.*\\)")
6279 '(1 'org-archived prepend))
6280 ;; Specials
6281 '(org-do-latex-and-related)
6282 '(org-fontify-entities)
6283 '(org-raise-scripts)
6284 ;; Code
6285 '(org-activate-code (1 'org-code t))
6286 ;; COMMENT
6287 (list (format org-heading-keyword-regexp-format
6288 (concat "\\("
6289 org-comment-string "\\|" org-quote-string
6290 "\\)"))
6291 '(2 'org-special-keyword t))
6292 ;; Blocks and meta lines
6293 '(org-fontify-meta-lines-and-blocks))))
6294 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6295 (run-hooks 'org-font-lock-set-keywords-hook)
6296 ;; Now set the full font-lock-keywords
6297 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6298 (org-set-local 'font-lock-defaults
6299 '(org-font-lock-keywords t nil nil backward-paragraph))
6300 (kill-local-variable 'font-lock-keywords) nil))
6302 (defun org-toggle-pretty-entities ()
6303 "Toggle the composition display of entities as UTF8 characters."
6304 (interactive)
6305 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6306 (org-restart-font-lock)
6307 (if org-pretty-entities
6308 (message "Entities are now displayed as UTF8 characters")
6309 (save-restriction
6310 (widen)
6311 (org-decompose-region (point-min) (point-max))
6312 (message "Entities are now displayed as plain text"))))
6314 (defvar org-custom-properties-overlays nil
6315 "List of overlays used for custom properties.")
6316 (make-variable-buffer-local 'org-custom-properties-overlays)
6318 (defun org-toggle-custom-properties-visibility ()
6319 "Display or hide properties in `org-custom-properties'."
6320 (interactive)
6321 (if org-custom-properties-overlays
6322 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6323 (setq org-custom-properties-overlays nil))
6324 (unless (not org-custom-properties)
6325 (save-excursion
6326 (save-restriction
6327 (widen)
6328 (goto-char (point-min))
6329 (while (re-search-forward org-property-re nil t)
6330 (mapc (lambda(p)
6331 (when (equal p (substring (match-string 1) 1 -1))
6332 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6333 (overlay-put o 'invisible t)
6334 (overlay-put o 'org-custom-property t)
6335 (push o org-custom-properties-overlays))))
6336 org-custom-properties)))))))
6338 (defun org-fontify-entities (limit)
6339 "Find an entity to fontify."
6340 (let (ee)
6341 (when org-pretty-entities
6342 (catch 'match
6343 (while (re-search-forward
6344 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6345 limit t)
6346 (if (and (not (org-in-indented-comment-line))
6347 (setq ee (org-entity-get (match-string 1)))
6348 (= (length (nth 6 ee)) 1))
6349 (let*
6350 ((end (if (equal (match-string 2) "{}")
6351 (match-end 2)
6352 (match-end 1))))
6353 (add-text-properties
6354 (match-beginning 0) end
6355 (list 'font-lock-fontified t))
6356 (compose-region (match-beginning 0) end
6357 (nth 6 ee) nil)
6358 (backward-char 1)
6359 (throw 'match t))))
6360 nil))))
6362 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6363 "Fontify string S like in Org-mode."
6364 (with-temp-buffer
6365 (insert s)
6366 (let ((org-odd-levels-only odd-levels))
6367 (org-mode)
6368 (font-lock-fontify-buffer)
6369 (buffer-string))))
6371 (defvar org-m nil)
6372 (defvar org-l nil)
6373 (defvar org-f nil)
6374 (defun org-get-level-face (n)
6375 "Get the right face for match N in font-lock matching of headlines."
6376 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6377 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6378 (if org-cycle-level-faces
6379 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6380 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6381 (cond
6382 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6383 ((eq n 2) org-f)
6384 (t (if org-level-color-stars-only nil org-f))))
6387 (defun org-get-todo-face (kwd)
6388 "Get the right face for a TODO keyword KWD.
6389 If KWD is a number, get the corresponding match group."
6390 (if (numberp kwd) (setq kwd (match-string kwd)))
6391 (or (org-face-from-face-or-color
6392 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6393 (and (member kwd org-done-keywords) 'org-done)
6394 'org-todo))
6396 (defun org-face-from-face-or-color (context inherit face-or-color)
6397 "Create a face list that inherits INHERIT, but sets the foreground color.
6398 When FACE-OR-COLOR is not a string, just return it."
6399 (if (stringp face-or-color)
6400 (list :inherit inherit
6401 (cdr (assoc context org-faces-easy-properties))
6402 face-or-color)
6403 face-or-color))
6405 (defun org-font-lock-add-tag-faces (limit)
6406 "Add the special tag faces."
6407 (when (and org-tag-faces org-tags-special-faces-re)
6408 (while (re-search-forward org-tags-special-faces-re limit t)
6409 (add-text-properties (match-beginning 1) (match-end 1)
6410 (list 'face (org-get-tag-face 1)
6411 'font-lock-fontified t))
6412 (backward-char 1))))
6414 (defun org-font-lock-add-priority-faces (limit)
6415 "Add the special priority faces."
6416 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6417 (when (save-match-data (org-at-heading-p))
6418 (add-text-properties
6419 (match-beginning 0) (match-end 0)
6420 (list 'face (or (org-face-from-face-or-color
6421 'priority 'org-priority
6422 (cdr (assoc (char-after (match-beginning 1))
6423 org-priority-faces)))
6424 'org-priority)
6425 'font-lock-fontified t)))))
6427 (defun org-get-tag-face (kwd)
6428 "Get the right face for a TODO keyword KWD.
6429 If KWD is a number, get the corresponding match group."
6430 (if (numberp kwd) (setq kwd (match-string kwd)))
6431 (or (org-face-from-face-or-color
6432 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6433 'org-tag))
6435 (defun org-unfontify-region (beg end &optional maybe_loudly)
6436 "Remove fontification and activation overlays from links."
6437 (font-lock-default-unfontify-region beg end)
6438 (let* ((buffer-undo-list t)
6439 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6440 (inhibit-modification-hooks t)
6441 deactivate-mark buffer-file-name buffer-file-truename)
6442 (org-decompose-region beg end)
6443 (remove-text-properties beg end
6444 '(mouse-face t keymap t org-linked-text t
6445 invisible t intangible t
6446 org-no-flyspell t org-emphasis t))
6447 (org-remove-font-lock-display-properties beg end)))
6449 (defconst org-script-display '(((raise -0.3) (height 0.7))
6450 ((raise 0.3) (height 0.7))
6451 ((raise -0.5))
6452 ((raise 0.5)))
6453 "Display properties for showing superscripts and subscripts.")
6455 (defun org-remove-font-lock-display-properties (beg end)
6456 "Remove specific display properties that have been added by font lock.
6457 The will remove the raise properties that are used to show superscripts
6458 and subscripts."
6459 (let (next prop)
6460 (while (< beg end)
6461 (setq next (next-single-property-change beg 'display nil end)
6462 prop (get-text-property beg 'display))
6463 (if (member prop org-script-display)
6464 (put-text-property beg next 'display nil))
6465 (setq beg next))))
6467 (defun org-raise-scripts (limit)
6468 "Add raise properties to sub/superscripts."
6469 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6470 (if (re-search-forward
6471 (if (eq org-use-sub-superscripts t)
6472 org-match-substring-regexp
6473 org-match-substring-with-braces-regexp)
6474 limit t)
6475 (let* ((pos (point)) table-p comment-p
6476 (mpos (match-beginning 3))
6477 (emph-p (get-text-property mpos 'org-emphasis))
6478 (link-p (get-text-property mpos 'mouse-face))
6479 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6480 (goto-char (point-at-bol))
6481 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6482 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6483 (goto-char pos)
6484 ;; Handle a_b^c
6485 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6486 (if (or comment-p emph-p link-p keyw-p)
6488 (put-text-property (match-beginning 3) (match-end 0)
6489 'display
6490 (if (equal (char-after (match-beginning 2)) ?^)
6491 (nth (if table-p 3 1) org-script-display)
6492 (nth (if table-p 2 0) org-script-display)))
6493 (add-text-properties (match-beginning 2) (match-end 2)
6494 (list 'invisible t
6495 'org-dwidth t 'org-dwidth-n 1))
6496 (if (and (eq (char-after (match-beginning 3)) ?{)
6497 (eq (char-before (match-end 3)) ?}))
6498 (progn
6499 (add-text-properties
6500 (match-beginning 3) (1+ (match-beginning 3))
6501 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6502 (add-text-properties
6503 (1- (match-end 3)) (match-end 3)
6504 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6505 t)))))
6507 ;;;; Visibility cycling, including org-goto and indirect buffer
6509 ;;; Cycling
6511 (defvar org-cycle-global-status nil)
6512 (make-variable-buffer-local 'org-cycle-global-status)
6513 (put 'org-cycle-global-status 'org-state t)
6514 (defvar org-cycle-subtree-status nil)
6515 (make-variable-buffer-local 'org-cycle-subtree-status)
6516 (put 'org-cycle-subtree-status 'org-state t)
6518 (defvar org-inlinetask-min-level)
6520 (defun org-unlogged-message (&rest args)
6521 "Display a message, but avoid logging it in the *Messages* buffer."
6522 (let ((message-log-max nil))
6523 (apply 'message args)))
6525 ;;;###autoload
6526 (defun org-cycle (&optional arg)
6527 "TAB-action and visibility cycling for Org-mode.
6529 This is the command invoked in Org-mode by the TAB key. Its main purpose
6530 is outline visibility cycling, but it also invokes other actions
6531 in special contexts.
6533 - When this function is called with a prefix argument, rotate the entire
6534 buffer through 3 states (global cycling)
6535 1. OVERVIEW: Show only top-level headlines.
6536 2. CONTENTS: Show all headlines of all levels, but no body text.
6537 3. SHOW ALL: Show everything.
6538 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6539 determined by the variable `org-startup-folded', and by any VISIBILITY
6540 properties in the buffer.
6541 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6542 including any drawers.
6544 - When inside a table, re-align the table and move to the next field.
6546 - When point is at the beginning of a headline, rotate the subtree started
6547 by this line through 3 different states (local cycling)
6548 1. FOLDED: Only the main headline is shown.
6549 2. CHILDREN: The main headline and the direct children are shown.
6550 From this state, you can move to one of the children
6551 and zoom in further.
6552 3. SUBTREE: Show the entire subtree, including body text.
6553 If there is no subtree, switch directly from CHILDREN to FOLDED.
6555 - When point is at the beginning of an empty headline and the variable
6556 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6557 of the headline by demoting and promoting it to likely levels. This
6558 speeds up creation document structure by pressing TAB once or several
6559 times right after creating a new headline.
6561 - When there is a numeric prefix, go up to a heading with level ARG, do
6562 a `show-subtree' and return to the previous cursor position. If ARG
6563 is negative, go up that many levels.
6565 - When point is not at the beginning of a headline, execute the global
6566 binding for TAB, which is re-indenting the line. See the option
6567 `org-cycle-emulate-tab' for details.
6569 - Special case: if point is at the beginning of the buffer and there is
6570 no headline in line 1, this function will act as if called with prefix arg
6571 (C-u TAB, same as S-TAB) also when called without prefix arg.
6572 But only if also the variable `org-cycle-global-at-bob' is t."
6573 (interactive "P")
6574 (org-load-modules-maybe)
6575 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6576 (and org-cycle-level-after-item/entry-creation
6577 (or (org-cycle-level)
6578 (org-cycle-item-indentation))))
6579 (let* ((limit-level
6580 (or org-cycle-max-level
6581 (and (boundp 'org-inlinetask-min-level)
6582 org-inlinetask-min-level
6583 (1- org-inlinetask-min-level))))
6584 (nstars (and limit-level
6585 (if org-odd-levels-only
6586 (and limit-level (1- (* limit-level 2)))
6587 limit-level)))
6588 (org-outline-regexp
6589 (if (not (derived-mode-p 'org-mode))
6590 outline-regexp
6591 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6592 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6593 (not (looking-at org-outline-regexp))))
6594 (org-cycle-hook
6595 (if bob-special
6596 (delq 'org-optimize-window-after-visibility-change
6597 (copy-sequence org-cycle-hook))
6598 org-cycle-hook))
6599 (pos (point)))
6601 (if (or bob-special (equal arg '(4)))
6602 ;; special case: use global cycling
6603 (setq arg t))
6605 (cond
6607 ((equal arg '(16))
6608 (setq last-command 'dummy)
6609 (org-set-startup-visibility)
6610 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6612 ((equal arg '(64))
6613 (show-all)
6614 (org-unlogged-message "Entire buffer visible, including drawers"))
6616 ;; Try cdlatex TAB completion
6617 ((org-try-cdlatex-tab))
6619 ;; Table: enter it or move to the next field.
6620 ((org-at-table-p 'any)
6621 (if (org-at-table.el-p)
6622 (message "Use C-c ' to edit table.el tables")
6623 (if arg (org-table-edit-field t)
6624 (org-table-justify-field-maybe)
6625 (call-interactively 'org-table-next-field))))
6627 ((run-hook-with-args-until-success
6628 'org-tab-after-check-for-table-hook))
6630 ;; Global cycling: delegate to `org-cycle-internal-global'.
6631 ((eq arg t) (org-cycle-internal-global))
6633 ;; Drawers: delegate to `org-flag-drawer'.
6634 ((and org-drawers org-drawer-regexp
6635 (save-excursion
6636 (beginning-of-line 1)
6637 (looking-at org-drawer-regexp)))
6638 (org-flag-drawer ; toggle block visibility
6639 (not (get-char-property (match-end 0) 'invisible))))
6641 ;; Show-subtree, ARG levels up from here.
6642 ((integerp arg)
6643 (save-excursion
6644 (org-back-to-heading)
6645 (outline-up-heading (if (< arg 0) (- arg)
6646 (- (funcall outline-level) arg)))
6647 (org-show-subtree)))
6649 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6650 ((and (featurep 'org-inlinetask)
6651 (org-inlinetask-at-task-p)
6652 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6653 (org-inlinetask-toggle-visibility))
6655 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6656 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6657 (save-excursion (beginning-of-line 1)
6658 (looking-at org-outline-regexp)))
6659 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6660 (org-cycle-internal-local))
6662 ;; From there: TAB emulation and template completion.
6663 (buffer-read-only (org-back-to-heading))
6665 ((run-hook-with-args-until-success
6666 'org-tab-after-check-for-cycling-hook))
6668 ((org-try-structure-completion))
6670 ((run-hook-with-args-until-success
6671 'org-tab-before-tab-emulation-hook))
6673 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6674 (or (not (bolp))
6675 (not (looking-at org-outline-regexp))))
6676 (call-interactively (global-key-binding "\t")))
6678 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6679 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6680 (or (and (eq org-cycle-emulate-tab 'white)
6681 (= (match-end 0) (point-at-eol)))
6682 (and (eq org-cycle-emulate-tab 'whitestart)
6683 (>= (match-end 0) pos))))
6685 (eq org-cycle-emulate-tab t))
6686 (call-interactively (global-key-binding "\t")))
6688 (t (save-excursion
6689 (org-back-to-heading)
6690 (org-cycle)))))))
6692 (defun org-cycle-internal-global ()
6693 "Do the global cycling action."
6694 ;; Hack to avoid display of messages for .org attachments in Gnus
6695 (let ((ga (string-match "\\*fontification" (buffer-name))))
6696 (cond
6697 ((and (eq last-command this-command)
6698 (eq org-cycle-global-status 'overview))
6699 ;; We just created the overview - now do table of contents
6700 ;; This can be slow in very large buffers, so indicate action
6701 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6702 (unless ga (org-unlogged-message "CONTENTS..."))
6703 (org-content)
6704 (unless ga (org-unlogged-message "CONTENTS...done"))
6705 (setq org-cycle-global-status 'contents)
6706 (run-hook-with-args 'org-cycle-hook 'contents))
6708 ((and (eq last-command this-command)
6709 (eq org-cycle-global-status 'contents))
6710 ;; We just showed the table of contents - now show everything
6711 (run-hook-with-args 'org-pre-cycle-hook 'all)
6712 (show-all)
6713 (unless ga (org-unlogged-message "SHOW ALL"))
6714 (setq org-cycle-global-status 'all)
6715 (run-hook-with-args 'org-cycle-hook 'all))
6718 ;; Default action: go to overview
6719 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6720 (org-overview)
6721 (unless ga (org-unlogged-message "OVERVIEW"))
6722 (setq org-cycle-global-status 'overview)
6723 (run-hook-with-args 'org-cycle-hook 'overview)))))
6725 (defvar org-called-with-limited-levels);Dyn-bound in ̀org-with-limited-levels'.
6727 (defun org-cycle-internal-local ()
6728 "Do the local cycling action."
6729 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6730 ;; First, determine end of headline (EOH), end of subtree or item
6731 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6732 (save-excursion
6733 (if (org-at-item-p)
6734 (progn
6735 (beginning-of-line)
6736 (setq struct (org-list-struct))
6737 (setq eoh (point-at-eol))
6738 (setq eos (org-list-get-item-end-before-blank (point) struct))
6739 (setq has-children (org-list-has-child-p (point) struct)))
6740 (org-back-to-heading)
6741 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6742 (setq eos (save-excursion (org-end-of-subtree t t)
6743 (when (bolp) (backward-char)) (point)))
6744 (setq has-children
6745 (or (save-excursion
6746 (let ((level (funcall outline-level)))
6747 (outline-next-heading)
6748 (and (org-at-heading-p t)
6749 (> (funcall outline-level) level))))
6750 (save-excursion
6751 (org-list-search-forward (org-item-beginning-re) eos t)))))
6752 ;; Determine end invisible part of buffer (EOL)
6753 (beginning-of-line 2)
6754 ;; XEmacs doesn't have `next-single-char-property-change'
6755 (if (featurep 'xemacs)
6756 (while (and (not (eobp)) ;; this is like `next-line'
6757 (get-char-property (1- (point)) 'invisible))
6758 (beginning-of-line 2))
6759 (while (and (not (eobp)) ;; this is like `next-line'
6760 (get-char-property (1- (point)) 'invisible))
6761 (goto-char (next-single-char-property-change (point) 'invisible))
6762 (and (eolp) (beginning-of-line 2))))
6763 (setq eol (point)))
6764 ;; Find out what to do next and set `this-command'
6765 (cond
6766 ((= eos eoh)
6767 ;; Nothing is hidden behind this heading
6768 (unless (org-before-first-heading-p)
6769 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6770 (org-unlogged-message "EMPTY ENTRY")
6771 (setq org-cycle-subtree-status nil)
6772 (save-excursion
6773 (goto-char eos)
6774 (outline-next-heading)
6775 (if (outline-invisible-p) (org-flag-heading nil))))
6776 ((and (or (>= eol eos)
6777 (not (string-match "\\S-" (buffer-substring eol eos))))
6778 (or has-children
6779 (not (setq children-skipped
6780 org-cycle-skip-children-state-if-no-children))))
6781 ;; Entire subtree is hidden in one line: children view
6782 (unless (org-before-first-heading-p)
6783 (run-hook-with-args 'org-pre-cycle-hook 'children))
6784 (if (org-at-item-p)
6785 (org-list-set-item-visibility (point-at-bol) struct 'children)
6786 (org-show-entry)
6787 (org-with-limited-levels (show-children))
6788 ;; FIXME: This slows down the func way too much.
6789 ;; How keep drawers hidden in subtree anyway?
6790 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6791 ;; (org-cycle-hide-drawers 'subtree))
6793 ;; Fold every list in subtree to top-level items.
6794 (when (eq org-cycle-include-plain-lists 'integrate)
6795 (save-excursion
6796 (org-back-to-heading)
6797 (while (org-list-search-forward (org-item-beginning-re) eos t)
6798 (beginning-of-line 1)
6799 (let* ((struct (org-list-struct))
6800 (prevs (org-list-prevs-alist struct))
6801 (end (org-list-get-bottom-point struct)))
6802 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6803 (org-list-get-all-items (point) struct prevs))
6804 (goto-char (if (< end eos) end eos)))))))
6805 (org-unlogged-message "CHILDREN")
6806 (save-excursion
6807 (goto-char eos)
6808 (outline-next-heading)
6809 (if (outline-invisible-p) (org-flag-heading nil)))
6810 (setq org-cycle-subtree-status 'children)
6811 (unless (org-before-first-heading-p)
6812 (run-hook-with-args 'org-cycle-hook 'children)))
6813 ((or children-skipped
6814 (and (eq last-command this-command)
6815 (eq org-cycle-subtree-status 'children)))
6816 ;; We just showed the children, or no children are there,
6817 ;; now show everything.
6818 (unless (org-before-first-heading-p)
6819 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6820 (outline-flag-region eoh eos nil)
6821 (org-unlogged-message
6822 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6823 (setq org-cycle-subtree-status 'subtree)
6824 (unless (org-before-first-heading-p)
6825 (run-hook-with-args 'org-cycle-hook 'subtree)))
6827 ;; Default action: hide the subtree.
6828 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6829 (outline-flag-region eoh eos t)
6830 (org-unlogged-message "FOLDED")
6831 (setq org-cycle-subtree-status 'folded)
6832 (unless (org-before-first-heading-p)
6833 (run-hook-with-args 'org-cycle-hook 'folded))))))
6835 ;;;###autoload
6836 (defun org-global-cycle (&optional arg)
6837 "Cycle the global visibility. For details see `org-cycle'.
6838 With \\[universal-argument] prefix arg, switch to startup visibility.
6839 With a numeric prefix, show all headlines up to that level."
6840 (interactive "P")
6841 (let ((org-cycle-include-plain-lists
6842 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6843 (cond
6844 ((integerp arg)
6845 (show-all)
6846 (hide-sublevels arg)
6847 (setq org-cycle-global-status 'contents))
6848 ((equal arg '(4))
6849 (org-set-startup-visibility)
6850 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6852 (org-cycle '(4))))))
6854 (defun org-set-startup-visibility ()
6855 "Set the visibility required by startup options and properties."
6856 (cond
6857 ((eq org-startup-folded t)
6858 (org-overview))
6859 ((eq org-startup-folded 'content)
6860 (org-content))
6861 ((or (eq org-startup-folded 'showeverything)
6862 (eq org-startup-folded nil))
6863 (show-all)))
6864 (unless (eq org-startup-folded 'showeverything)
6865 (if org-hide-block-startup (org-hide-block-all))
6866 (org-set-visibility-according-to-property 'no-cleanup)
6867 (org-cycle-hide-archived-subtrees 'all)
6868 (org-cycle-hide-drawers 'all)
6869 (org-cycle-show-empty-lines t)))
6871 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6872 "Switch subtree visibilities according to :VISIBILITY: property."
6873 (interactive)
6874 (let (org-show-entry-below state)
6875 (save-excursion
6876 (goto-char (point-min))
6877 (while (re-search-forward
6878 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6879 nil t)
6880 (setq state (match-string 1))
6881 (save-excursion
6882 (org-back-to-heading t)
6883 (hide-subtree)
6884 (org-reveal)
6885 (cond
6886 ((equal state '("fold" "folded"))
6887 (hide-subtree))
6888 ((equal state "children")
6889 (org-show-hidden-entry)
6890 (show-children))
6891 ((equal state "content")
6892 (save-excursion
6893 (save-restriction
6894 (org-narrow-to-subtree)
6895 (org-content))))
6896 ((member state '("all" "showall"))
6897 (show-subtree)))))
6898 (unless no-cleanup
6899 (org-cycle-hide-archived-subtrees 'all)
6900 (org-cycle-hide-drawers 'all)
6901 (org-cycle-show-empty-lines 'all)))))
6903 ;; This function uses outline-regexp instead of the more fundamental
6904 ;; org-outline-regexp so that org-cycle-global works outside of Org
6905 ;; buffers, where outline-regexp is needed.
6906 (defun org-overview ()
6907 "Switch to overview mode, showing only top-level headlines.
6908 Really, this shows all headlines with level equal or greater than the level
6909 of the first headline in the buffer. This is important, because if the
6910 first headline is not level one, then (hide-sublevels 1) gives confusing
6911 results."
6912 (interactive)
6913 (let ((pos (point))
6914 (level (save-excursion
6915 (goto-char (point-min))
6916 (if (re-search-forward (concat "^" outline-regexp) nil t)
6917 (progn
6918 (goto-char (match-beginning 0))
6919 (funcall outline-level))))))
6920 (and level (hide-sublevels level))
6921 (recenter '(4))
6922 (goto-char pos)))
6924 (defun org-content (&optional arg)
6925 "Show all headlines in the buffer, like a table of contents.
6926 With numerical argument N, show content up to level N."
6927 (interactive "P")
6928 (org-overview)
6929 (save-excursion
6930 ;; Visit all headings and show their offspring
6931 (and (integerp arg) (org-overview))
6932 (goto-char (point-max))
6933 (catch 'exit
6934 (while (and (progn (condition-case nil
6935 (outline-previous-visible-heading 1)
6936 (error (goto-char (point-min))))
6938 (looking-at org-outline-regexp))
6939 (if (integerp arg)
6940 (show-children (1- arg))
6941 (show-branches))
6942 (if (bobp) (throw 'exit nil))))))
6944 (defun org-optimize-window-after-visibility-change (state)
6945 "Adjust the window after a change in outline visibility.
6946 This function is the default value of the hook `org-cycle-hook'."
6947 (when (get-buffer-window (current-buffer))
6948 (cond
6949 ((eq state 'content) nil)
6950 ((eq state 'all) nil)
6951 ((eq state 'folded) nil)
6952 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6953 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6955 (defun org-remove-empty-overlays-at (pos)
6956 "Remove outline overlays that do not contain non-white stuff."
6957 (mapc
6958 (lambda (o)
6959 (and (eq 'outline (overlay-get o 'invisible))
6960 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6961 (overlay-end o))))
6962 (delete-overlay o)))
6963 (overlays-at pos)))
6965 (defun org-clean-visibility-after-subtree-move ()
6966 "Fix visibility issues after moving a subtree."
6967 ;; First, find a reasonable region to look at:
6968 ;; Start two siblings above, end three below
6969 (let* ((beg (save-excursion
6970 (and (org-get-last-sibling)
6971 (org-get-last-sibling))
6972 (point)))
6973 (end (save-excursion
6974 (and (org-get-next-sibling)
6975 (org-get-next-sibling)
6976 (org-get-next-sibling))
6977 (if (org-at-heading-p)
6978 (point-at-eol)
6979 (point))))
6980 (level (looking-at "\\*+"))
6981 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6982 (save-excursion
6983 (save-restriction
6984 (narrow-to-region beg end)
6985 (when re
6986 ;; Properly fold already folded siblings
6987 (goto-char (point-min))
6988 (while (re-search-forward re nil t)
6989 (if (and (not (outline-invisible-p))
6990 (save-excursion
6991 (goto-char (point-at-eol)) (outline-invisible-p)))
6992 (hide-entry))))
6993 (org-cycle-show-empty-lines 'overview)
6994 (org-cycle-hide-drawers 'overview)))))
6996 (defun org-cycle-show-empty-lines (state)
6997 "Show empty lines above all visible headlines.
6998 The region to be covered depends on STATE when called through
6999 `org-cycle-hook'. Lisp program can use t for STATE to get the
7000 entire buffer covered. Note that an empty line is only shown if there
7001 are at least `org-cycle-separator-lines' empty lines before the headline."
7002 (when (not (= org-cycle-separator-lines 0))
7003 (save-excursion
7004 (let* ((n (abs org-cycle-separator-lines))
7005 (re (cond
7006 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7007 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7008 (t (let ((ns (number-to-string (- n 2))))
7009 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7010 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7011 beg end b e)
7012 (cond
7013 ((memq state '(overview contents t))
7014 (setq beg (point-min) end (point-max)))
7015 ((memq state '(children folded))
7016 (setq beg (point) end (progn (org-end-of-subtree t t)
7017 (beginning-of-line 2)
7018 (point)))))
7019 (when beg
7020 (goto-char beg)
7021 (while (re-search-forward re end t)
7022 (unless (get-char-property (match-end 1) 'invisible)
7023 (setq e (match-end 1))
7024 (if (< org-cycle-separator-lines 0)
7025 (setq b (save-excursion
7026 (goto-char (match-beginning 0))
7027 (org-back-over-empty-lines)
7028 (if (save-excursion
7029 (goto-char (max (point-min) (1- (point))))
7030 (org-at-heading-p))
7031 (1- (point))
7032 (point))))
7033 (setq b (match-beginning 1)))
7034 (outline-flag-region b e nil)))))))
7035 ;; Never hide empty lines at the end of the file.
7036 (save-excursion
7037 (goto-char (point-max))
7038 (outline-previous-heading)
7039 (outline-end-of-heading)
7040 (if (and (looking-at "[ \t\n]+")
7041 (= (match-end 0) (point-max)))
7042 (outline-flag-region (point) (match-end 0) nil))))
7044 (defun org-show-empty-lines-in-parent ()
7045 "Move to the parent and re-show empty lines before visible headlines."
7046 (save-excursion
7047 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7048 (org-cycle-show-empty-lines context))))
7050 (defun org-files-list ()
7051 "Return `org-agenda-files' list, plus all open org-mode files.
7052 This is useful for operations that need to scan all of a user's
7053 open and agenda-wise Org files."
7054 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7055 (dolist (buf (buffer-list))
7056 (with-current-buffer buf
7057 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7058 (let ((file (expand-file-name (buffer-file-name))))
7059 (unless (member file files)
7060 (push file files))))))
7061 files))
7063 (defsubst org-entry-beginning-position ()
7064 "Return the beginning position of the current entry."
7065 (save-excursion (outline-back-to-heading t) (point)))
7067 (defsubst org-entry-end-position ()
7068 "Return the end position of the current entry."
7069 (save-excursion (outline-next-heading) (point)))
7071 (defun org-cycle-hide-drawers (state)
7072 "Re-hide all drawers after a visibility state change."
7073 (when (and (derived-mode-p 'org-mode)
7074 (not (memq state '(overview folded contents))))
7075 (save-excursion
7076 (let* ((globalp (memq state '(contents all)))
7077 (beg (if globalp (point-min) (point)))
7078 (end (if globalp (point-max)
7079 (if (eq state 'children)
7080 (save-excursion (outline-next-heading) (point))
7081 (org-end-of-subtree t)))))
7082 (goto-char beg)
7083 (while (re-search-forward org-drawer-regexp end t)
7084 (org-flag-drawer t))))))
7086 (defun org-cycle-hide-inline-tasks (state)
7087 "Re-hide inline tasks when switching to 'contents or 'children
7088 visibility state."
7089 (case state
7090 (contents
7091 (when (org-bound-and-true-p org-inlinetask-min-level)
7092 (hide-sublevels (1- org-inlinetask-min-level))))
7093 (children
7094 (when (featurep 'org-inlinetask)
7095 (save-excursion
7096 (while (and (outline-next-heading)
7097 (org-inlinetask-at-task-p))
7098 (org-inlinetask-toggle-visibility)
7099 (org-inlinetask-goto-end)))))))
7101 (defun org-flag-drawer (flag)
7102 "When FLAG is non-nil, hide the drawer we are within.
7103 Otherwise make it visible."
7104 (save-excursion
7105 (beginning-of-line 1)
7106 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
7107 (let ((b (match-end 0)))
7108 (if (re-search-forward
7109 "^[ \t]*:END:"
7110 (save-excursion (outline-next-heading) (point)) t)
7111 (outline-flag-region b (point-at-eol) flag)
7112 (user-error ":END: line missing at position %s" b))))))
7114 (defun org-subtree-end-visible-p ()
7115 "Is the end of the current subtree visible?"
7116 (pos-visible-in-window-p
7117 (save-excursion (org-end-of-subtree t) (point))))
7119 (defun org-first-headline-recenter (&optional N)
7120 "Move cursor to the first headline and recenter the headline.
7121 Optional argument N means put the headline into the Nth line of the window."
7122 (goto-char (point-min))
7123 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7124 (beginning-of-line)
7125 (recenter (prefix-numeric-value N))))
7127 ;;; Saving and restoring visibility
7129 (defun org-outline-overlay-data (&optional use-markers)
7130 "Return a list of the locations of all outline overlays.
7131 These are overlays with the `invisible' property value `outline'.
7132 The return value is a list of cons cells, with start and stop
7133 positions for each overlay.
7134 If USE-MARKERS is set, return the positions as markers."
7135 (let (beg end)
7136 (save-excursion
7137 (save-restriction
7138 (widen)
7139 (delq nil
7140 (mapcar (lambda (o)
7141 (when (eq (overlay-get o 'invisible) 'outline)
7142 (setq beg (overlay-start o)
7143 end (overlay-end o))
7144 (and beg end (> end beg)
7145 (if use-markers
7146 (cons (move-marker (make-marker) beg)
7147 (move-marker (make-marker) end))
7148 (cons beg end)))))
7149 (overlays-in (point-min) (point-max))))))))
7151 (defun org-set-outline-overlay-data (data)
7152 "Create visibility overlays for all positions in DATA.
7153 DATA should have been made by `org-outline-overlay-data'."
7154 (let (o)
7155 (save-excursion
7156 (save-restriction
7157 (widen)
7158 (show-all)
7159 (mapc (lambda (c)
7160 (outline-flag-region (car c) (cdr c) t))
7161 data)))))
7163 ;;; Folding of blocks
7165 (defvar org-hide-block-overlays nil
7166 "Overlays hiding blocks.")
7167 (make-variable-buffer-local 'org-hide-block-overlays)
7169 (defun org-block-map (function &optional start end)
7170 "Call FUNCTION at the head of all source blocks in the current buffer.
7171 Optional arguments START and END can be used to limit the range."
7172 (let ((start (or start (point-min)))
7173 (end (or end (point-max))))
7174 (save-excursion
7175 (goto-char start)
7176 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7177 (save-excursion
7178 (save-match-data
7179 (goto-char (match-beginning 0))
7180 (funcall function)))))))
7182 (defun org-hide-block-toggle-all ()
7183 "Toggle the visibility of all blocks in the current buffer."
7184 (org-block-map #'org-hide-block-toggle))
7186 (defun org-hide-block-all ()
7187 "Fold all blocks in the current buffer."
7188 (interactive)
7189 (org-show-block-all)
7190 (org-block-map #'org-hide-block-toggle-maybe))
7192 (defun org-show-block-all ()
7193 "Unfold all blocks in the current buffer."
7194 (interactive)
7195 (mapc 'delete-overlay org-hide-block-overlays)
7196 (setq org-hide-block-overlays nil))
7198 (defun org-hide-block-toggle-maybe ()
7199 "Toggle visibility of block at point."
7200 (interactive)
7201 (let ((case-fold-search t))
7202 (if (save-excursion
7203 (beginning-of-line 1)
7204 (looking-at org-block-regexp))
7205 (progn (org-hide-block-toggle)
7206 t) ;; to signal that we took action
7207 nil))) ;; to signal that we did not
7209 (defun org-hide-block-toggle (&optional force)
7210 "Toggle the visibility of the current block."
7211 (interactive)
7212 (save-excursion
7213 (beginning-of-line)
7214 (if (re-search-forward org-block-regexp nil t)
7215 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7216 (end (match-end 0)) ;; end of entire body
7218 (if (memq t (mapcar (lambda (overlay)
7219 (eq (overlay-get overlay 'invisible)
7220 'org-hide-block))
7221 (overlays-at start)))
7222 (if (or (not force) (eq force 'off))
7223 (mapc (lambda (ov)
7224 (when (member ov org-hide-block-overlays)
7225 (setq org-hide-block-overlays
7226 (delq ov org-hide-block-overlays)))
7227 (when (eq (overlay-get ov 'invisible)
7228 'org-hide-block)
7229 (delete-overlay ov)))
7230 (overlays-at start)))
7231 (setq ov (make-overlay start end))
7232 (overlay-put ov 'invisible 'org-hide-block)
7233 ;; make the block accessible to isearch
7234 (overlay-put
7235 ov 'isearch-open-invisible
7236 (lambda (ov)
7237 (when (member ov org-hide-block-overlays)
7238 (setq org-hide-block-overlays
7239 (delq ov org-hide-block-overlays)))
7240 (when (eq (overlay-get ov 'invisible)
7241 'org-hide-block)
7242 (delete-overlay ov))))
7243 (push ov org-hide-block-overlays)))
7244 (user-error "Not looking at a source block"))))
7246 ;; org-tab-after-check-for-cycling-hook
7247 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7248 ;; Remove overlays when changing major mode
7249 (add-hook 'org-mode-hook
7250 (lambda () (org-add-hook 'change-major-mode-hook
7251 'org-show-block-all 'append 'local)))
7253 ;;; Org-goto
7255 (defvar org-goto-window-configuration nil)
7256 (defvar org-goto-marker nil)
7257 (defvar org-goto-map)
7258 (defun org-goto-map ()
7259 "Set the keymap `org-goto'."
7260 (setq org-goto-map
7261 (let ((map (make-sparse-keymap)))
7262 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7263 mouse-drag-region universal-argument org-occur))
7264 cmd)
7265 (while (setq cmd (pop cmds))
7266 (substitute-key-definition cmd cmd map global-map)))
7267 (suppress-keymap map)
7268 (org-defkey map "\C-m" 'org-goto-ret)
7269 (org-defkey map [(return)] 'org-goto-ret)
7270 (org-defkey map [(left)] 'org-goto-left)
7271 (org-defkey map [(right)] 'org-goto-right)
7272 (org-defkey map [(control ?g)] 'org-goto-quit)
7273 (org-defkey map "\C-i" 'org-cycle)
7274 (org-defkey map [(tab)] 'org-cycle)
7275 (org-defkey map [(down)] 'outline-next-visible-heading)
7276 (org-defkey map [(up)] 'outline-previous-visible-heading)
7277 (if org-goto-auto-isearch
7278 (if (fboundp 'define-key-after)
7279 (define-key-after map [t] 'org-goto-local-auto-isearch)
7280 nil)
7281 (org-defkey map "q" 'org-goto-quit)
7282 (org-defkey map "n" 'outline-next-visible-heading)
7283 (org-defkey map "p" 'outline-previous-visible-heading)
7284 (org-defkey map "f" 'outline-forward-same-level)
7285 (org-defkey map "b" 'outline-backward-same-level)
7286 (org-defkey map "u" 'outline-up-heading))
7287 (org-defkey map "/" 'org-occur)
7288 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7289 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7290 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7291 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7292 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7293 map)))
7295 (defconst org-goto-help
7296 "Browse buffer copy, to find location or copy text.%s
7297 RET=jump to location C-g=quit and return to previous location
7298 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7300 (defvar org-goto-start-pos) ; dynamically scoped parameter
7302 (defun org-goto (&optional alternative-interface)
7303 "Look up a different location in the current file, keeping current visibility.
7305 When you want look-up or go to a different location in a
7306 document, the fastest way is often to fold the entire buffer and
7307 then dive into the tree. This method has the disadvantage, that
7308 the previous location will be folded, which may not be what you
7309 want.
7311 This command works around this by showing a copy of the current
7312 buffer in an indirect buffer, in overview mode. You can dive
7313 into the tree in that copy, use org-occur and incremental search
7314 to find a location. When pressing RET or `Q', the command
7315 returns to the original buffer in which the visibility is still
7316 unchanged. After RET it will also jump to the location selected
7317 in the indirect buffer and expose the headline hierarchy above.
7319 With a prefix argument, use the alternative interface: e.g. if
7320 `org-goto-interface' is 'outline use 'outline-path-completion."
7321 (interactive "P")
7322 (org-goto-map)
7323 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7324 (org-refile-use-outline-path t)
7325 (org-refile-target-verify-function nil)
7326 (interface
7327 (if (not alternative-interface)
7328 org-goto-interface
7329 (if (eq org-goto-interface 'outline)
7330 'outline-path-completion
7331 'outline)))
7332 (org-goto-start-pos (point))
7333 (selected-point
7334 (if (eq interface 'outline)
7335 (car (org-get-location (current-buffer) org-goto-help))
7336 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7337 (org-refile-check-position pa)
7338 (nth 3 pa)))))
7339 (if selected-point
7340 (progn
7341 (org-mark-ring-push org-goto-start-pos)
7342 (goto-char selected-point)
7343 (if (or (outline-invisible-p) (org-invisible-p2))
7344 (org-show-context 'org-goto)))
7345 (message "Quit"))))
7347 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7348 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7349 (defvar org-goto-local-auto-isearch-map) ; defined below
7351 (defun org-get-location (buf help)
7352 "Let the user select a location in the Org-mode buffer BUF.
7353 This function uses a recursive edit. It returns the selected position
7354 or nil."
7355 (org-no-popups
7356 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7357 (isearch-hide-immediately nil)
7358 (isearch-search-fun-function
7359 (lambda () 'org-goto-local-search-headings))
7360 (org-goto-selected-point org-goto-exit-command))
7361 (save-excursion
7362 (save-window-excursion
7363 (delete-other-windows)
7364 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7365 (org-pop-to-buffer-same-window
7366 (condition-case nil
7367 (make-indirect-buffer (current-buffer) "*org-goto*")
7368 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7369 (with-output-to-temp-buffer "*Org Help*"
7370 (princ (format help (if org-goto-auto-isearch
7371 " Just type for auto-isearch."
7372 " n/p/f/b/u to navigate, q to quit."))))
7373 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7374 (setq buffer-read-only nil)
7375 (let ((org-startup-truncated t)
7376 (org-startup-folded nil)
7377 (org-startup-align-all-tables nil))
7378 (org-mode)
7379 (org-overview))
7380 (setq buffer-read-only t)
7381 (if (and (boundp 'org-goto-start-pos)
7382 (integer-or-marker-p org-goto-start-pos))
7383 (let ((org-show-hierarchy-above t)
7384 (org-show-siblings t)
7385 (org-show-following-heading t))
7386 (goto-char org-goto-start-pos)
7387 (and (outline-invisible-p) (org-show-context)))
7388 (goto-char (point-min)))
7389 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7390 (message "Select location and press RET")
7391 (use-local-map org-goto-map)
7392 (recursive-edit)))
7393 (kill-buffer "*org-goto*")
7394 (cons org-goto-selected-point org-goto-exit-command))))
7396 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7397 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7398 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7399 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7401 (defun org-goto-local-search-headings (string bound noerror)
7402 "Search and make sure that any matches are in headlines."
7403 (catch 'return
7404 (while (if isearch-forward
7405 (search-forward string bound noerror)
7406 (search-backward string bound noerror))
7407 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7408 (and (member :headline context)
7409 (not (member :tags context))))
7410 (throw 'return (point))))))
7412 (defun org-goto-local-auto-isearch ()
7413 "Start isearch."
7414 (interactive)
7415 (goto-char (point-min))
7416 (let ((keys (this-command-keys)))
7417 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7418 (isearch-mode t)
7419 (isearch-process-search-char (string-to-char keys)))))
7421 (defun org-goto-ret (&optional arg)
7422 "Finish `org-goto' by going to the new location."
7423 (interactive "P")
7424 (setq org-goto-selected-point (point)
7425 org-goto-exit-command 'return)
7426 (throw 'exit nil))
7428 (defun org-goto-left ()
7429 "Finish `org-goto' by going to the new location."
7430 (interactive)
7431 (if (org-at-heading-p)
7432 (progn
7433 (beginning-of-line 1)
7434 (setq org-goto-selected-point (point)
7435 org-goto-exit-command 'left)
7436 (throw 'exit nil))
7437 (user-error "Not on a heading")))
7439 (defun org-goto-right ()
7440 "Finish `org-goto' by going to the new location."
7441 (interactive)
7442 (if (org-at-heading-p)
7443 (progn
7444 (setq org-goto-selected-point (point)
7445 org-goto-exit-command 'right)
7446 (throw 'exit nil))
7447 (user-error "Not on a heading")))
7449 (defun org-goto-quit ()
7450 "Finish `org-goto' without cursor motion."
7451 (interactive)
7452 (setq org-goto-selected-point nil)
7453 (setq org-goto-exit-command 'quit)
7454 (throw 'exit nil))
7456 ;;; Indirect buffer display of subtrees
7458 (defvar org-indirect-dedicated-frame nil
7459 "This is the frame being used for indirect tree display.")
7460 (defvar org-last-indirect-buffer nil)
7462 (defun org-tree-to-indirect-buffer (&optional arg)
7463 "Create indirect buffer and narrow it to current subtree.
7464 With a numerical prefix ARG, go up to this level and then take that tree.
7465 If ARG is negative, go up that many levels.
7467 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7468 indirect buffer previously made with this command, to avoid proliferation of
7469 indirect buffers. However, when you call the command with a \
7470 \\[universal-argument] prefix, or
7471 when `org-indirect-buffer-display' is `new-frame', the last buffer
7472 is kept so that you can work with several indirect buffers at the same time.
7473 If `org-indirect-buffer-display' is `dedicated-frame', the \
7474 \\[universal-argument] prefix also
7475 requests that a new frame be made for the new buffer, so that the dedicated
7476 frame is not changed."
7477 (interactive "P")
7478 (let ((cbuf (current-buffer))
7479 (cwin (selected-window))
7480 (pos (point))
7481 beg end level heading ibuf)
7482 (save-excursion
7483 (org-back-to-heading t)
7484 (when (numberp arg)
7485 (setq level (org-outline-level))
7486 (if (< arg 0) (setq arg (+ level arg)))
7487 (while (> (setq level (org-outline-level)) arg)
7488 (org-up-heading-safe)))
7489 (setq beg (point)
7490 heading (org-get-heading))
7491 (org-end-of-subtree t t)
7492 (if (org-at-heading-p) (backward-char 1))
7493 (setq end (point)))
7494 (if (and (buffer-live-p org-last-indirect-buffer)
7495 (not (eq org-indirect-buffer-display 'new-frame))
7496 (not arg))
7497 (kill-buffer org-last-indirect-buffer))
7498 (setq ibuf (org-get-indirect-buffer cbuf)
7499 org-last-indirect-buffer ibuf)
7500 (cond
7501 ((or (eq org-indirect-buffer-display 'new-frame)
7502 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7503 (select-frame (make-frame))
7504 (delete-other-windows)
7505 (org-pop-to-buffer-same-window ibuf)
7506 (org-set-frame-title heading))
7507 ((eq org-indirect-buffer-display 'dedicated-frame)
7508 (raise-frame
7509 (select-frame (or (and org-indirect-dedicated-frame
7510 (frame-live-p org-indirect-dedicated-frame)
7511 org-indirect-dedicated-frame)
7512 (setq org-indirect-dedicated-frame (make-frame)))))
7513 (delete-other-windows)
7514 (org-pop-to-buffer-same-window ibuf)
7515 (org-set-frame-title (concat "Indirect: " heading)))
7516 ((eq org-indirect-buffer-display 'current-window)
7517 (org-pop-to-buffer-same-window ibuf))
7518 ((eq org-indirect-buffer-display 'other-window)
7519 (pop-to-buffer ibuf))
7520 (t (error "Invalid value")))
7521 (if (featurep 'xemacs)
7522 (save-excursion (org-mode) (turn-on-font-lock)))
7523 (narrow-to-region beg end)
7524 (show-all)
7525 (goto-char pos)
7526 (run-hook-with-args 'org-cycle-hook 'all)
7527 (and (window-live-p cwin) (select-window cwin))))
7529 (defun org-get-indirect-buffer (&optional buffer)
7530 (setq buffer (or buffer (current-buffer)))
7531 (let ((n 1) (base (buffer-name buffer)) bname)
7532 (while (buffer-live-p
7533 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7534 (setq n (1+ n)))
7535 (condition-case nil
7536 (make-indirect-buffer buffer bname 'clone)
7537 (error (make-indirect-buffer buffer bname)))))
7539 (defun org-set-frame-title (title)
7540 "Set the title of the current frame to the string TITLE."
7541 ;; FIXME: how to name a single frame in XEmacs???
7542 (unless (featurep 'xemacs)
7543 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7545 ;;;; Structure editing
7547 ;;; Inserting headlines
7549 (defun org-previous-line-empty-p (&optional next)
7550 "Is the previous line a blank line?
7551 When NEXT is non-nil, check the next line instead."
7552 (save-excursion
7553 (and (not (bobp))
7554 (or (beginning-of-line (if next 2 0)) t)
7555 (save-match-data
7556 (looking-at "[ \t]*$")))))
7558 (defun org-insert-heading (&optional arg invisible-ok)
7559 "Insert a new heading or item with same depth at point.
7561 If point is at the beginning of a heading or a list item, insert
7562 a heading or a list item before it.
7564 If point is at the beginning of a normal line, turn this line
7565 into a heading.
7567 If point is in the middle of a headline or a list item, split the
7568 headline or the item and create a new headline/item with the text
7569 in the current line after point \(see `org-M-RET-may-split-line'
7570 on how to modify this behavior).
7572 With one universal prefix argument: If point is within a list,
7573 insert a heading instead of a list item. Otherwise, set the
7574 value of `org-insert-heading-respect-content' to `t' for the
7575 duration of the command.
7577 With two universal prefix arguments, insert the heading at the
7578 end of the grandparent subtree. For example, if point is within
7579 a 2nd-level heading, then it will insert a 2nd-level heading at
7580 the end of the 1st-level parent heading.
7582 When INVISIBLE-OK is set, stop at invisible headlines when going
7583 back. This is important for non-interactive uses of the
7584 command."
7585 (interactive "P")
7586 (if (org-called-interactively-p 'any) (org-reveal))
7587 (let ((itemp (org-in-item-p))
7588 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7589 (respect-content (or org-insert-heading-respect-content
7590 (equal arg '(4))))
7591 (initial-content "")
7592 (adjust-empty-lines t))
7594 (cond
7596 ((or (= (buffer-size) 0)
7597 (and (not (save-excursion
7598 (and (ignore-errors (org-back-to-heading invisible-ok))
7599 (org-at-heading-p))))
7600 (or arg (not itemp))))
7601 ;; At beginning of buffer or so high up that only a heading
7602 ;; makes sense.
7603 (when (and (org-before-first-heading-p) (not (bolp)))
7604 (re-search-forward org-outline-regexp-bol)
7605 (beginning-of-line 0))
7606 (insert
7607 (if (or (bobp) (org-previous-line-empty-p)) "" "\n")
7608 (if (org-in-src-block-p) ",* " "* "))
7609 (run-hooks 'org-insert-heading-hook))
7611 ((and itemp (not (equal arg '(4))))
7612 ;; Insert an item
7613 (org-insert-item))
7616 ;; Maybe move at the end of the subtree
7617 (when (equal arg '(16))
7618 (org-up-heading-safe)
7619 (org-end-of-subtree t))
7620 ;; Insert a heading
7621 (save-restriction
7622 (widen)
7623 (let* ((level nil)
7624 (on-heading (org-at-heading-p))
7625 (empty-line-p (if on-heading
7626 (org-previous-line-empty-p)
7627 ;; We will decide later
7628 nil))
7629 ;; Get a level string to fall back on
7630 (fix-level
7631 (if (org-before-first-heading-p) "*"
7632 (save-excursion
7633 (org-back-to-heading t)
7634 (if (org-previous-line-empty-p) (setq empty-line-p t))
7635 (looking-at org-outline-regexp)
7636 (make-string (1- (length (match-string 0))) ?*))))
7637 (stars
7638 (save-excursion
7639 (condition-case nil
7640 (progn
7641 (org-back-to-heading invisible-ok)
7642 (when (and (not on-heading)
7643 (featurep 'org-inlinetask)
7644 (integerp org-inlinetask-min-level)
7645 (>= (length (match-string 0))
7646 org-inlinetask-min-level))
7647 ;; Find a heading level before the inline task
7648 (while (and (setq level (org-up-heading-safe))
7649 (>= level org-inlinetask-min-level)))
7650 (if (org-at-heading-p)
7651 (org-back-to-heading invisible-ok)
7652 (error "This should not happen")))
7653 (unless (and (save-excursion
7654 (save-match-data
7655 (org-backward-heading-same-level
7656 1 invisible-ok))
7657 (= (point) (match-beginning 0)))
7658 (not (org-previous-line-empty-p t)))
7659 (setq empty-line-p (or empty-line-p
7660 (org-previous-line-empty-p))))
7661 (match-string 0))
7662 (error (or fix-level "* ")))))
7663 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7664 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7665 pos hide-previous previous-pos)
7667 ;; If we insert after content, move there and clean up whitespace
7668 (when (and respect-content
7669 (not (org-looking-at-p org-outline-regexp-bol))
7670 (not (bolp)))
7671 (if (not (org-before-first-heading-p))
7672 (org-end-of-subtree nil t)
7673 (re-search-forward org-outline-regexp-bol)
7674 (beginning-of-line 0))
7675 (skip-chars-backward " \r\n")
7676 (and (not (looking-back "^\*+"))
7677 (looking-at "[ \t]+") (replace-match ""))
7678 (unless (eobp) (forward-char 1))
7679 (when (looking-at "^\\*")
7680 (unless (bobp) (backward-char 1))
7681 (insert "\n")))
7683 ;; If we are splitting, grab the text that should be moved to the new headline
7684 (when may-split
7685 (if (org-on-heading-p)
7686 ;; This is a heading, we split intelligently (keeping tags)
7687 (let ((pos (point)))
7688 (goto-char (point-at-bol))
7689 (unless (looking-at org-complex-heading-regexp)
7690 (error "This should not happen"))
7691 (when (and (match-beginning 4)
7692 (> pos (match-beginning 4))
7693 (< pos (match-end 4)))
7694 (setq initial-content (buffer-substring pos (match-end 4)))
7695 (goto-char pos)
7696 (delete-region (point) (match-end 4))
7697 (if (looking-at "[ \t]*$")
7698 (replace-match "")
7699 (insert (make-string (length initial-content) ?\ )))
7700 (setq initial-content (org-trim initial-content)))
7701 (goto-char pos))
7702 ;; a normal line
7703 (setq initial-content
7704 (org-trim (buffer-substring (point) (point-at-eol))))
7705 (delete-region (point) (point-at-eol))))
7707 ;; If we are at the beginning of the line, insert before it. Else after
7708 (cond
7709 ((and (bolp) (looking-at "[ \t]*$")))
7710 ((and (bolp) (not (looking-at "[ \t]*$")))
7711 (open-line 1))
7713 (goto-char (point-at-eol))
7714 (insert "\n")))
7716 ;; Insert the new heading
7717 (insert stars)
7718 (just-one-space)
7719 (insert initial-content)
7720 (when adjust-empty-lines
7721 (if (or (not blank)
7722 (and blank (not (org-previous-line-empty-p))))
7723 (org-N-empty-lines-before-current (if blank 1 0))))
7724 (run-hooks 'org-insert-heading-hook)))))))
7726 (defun org-N-empty-lines-before-current (N)
7727 "Make the number of empty lines before current exactly N.
7728 So this will delete or add empty lines."
7729 (save-excursion
7730 (goto-char (point-at-bol))
7731 (if (looking-back "\\s-+" nil 'greedy)
7732 (replace-match ""))
7733 (or (bobp) (insert "\n"))
7734 (while (> N 0)
7735 (insert "\n")
7736 (setq N (1- N)))))
7738 (defun org-get-heading (&optional no-tags no-todo)
7739 "Return the heading of the current entry, without the stars.
7740 When NO-TAGS is non-nil, don't include tags.
7741 When NO-TODO is non-nil, don't include TODO keywords."
7742 (save-excursion
7743 (org-back-to-heading t)
7744 (cond
7745 ((and no-tags no-todo)
7746 (looking-at org-complex-heading-regexp)
7747 (match-string 4))
7748 (no-tags
7749 (looking-at (concat org-outline-regexp
7750 "\\(.*?\\)"
7751 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7752 (match-string 1))
7753 (no-todo
7754 (looking-at org-todo-line-regexp)
7755 (match-string 3))
7756 (t (looking-at org-heading-regexp)
7757 (match-string 2)))))
7759 (defvar orgstruct-mode) ; defined below
7761 (defun org-heading-components ()
7762 "Return the components of the current heading.
7763 This is a list with the following elements:
7764 - the level as an integer
7765 - the reduced level, different if `org-odd-levels-only' is set.
7766 - the TODO keyword, or nil
7767 - the priority character, like ?A, or nil if no priority is given
7768 - the headline text itself, or the tags string if no headline text
7769 - the tags string, or nil."
7770 (save-excursion
7771 (org-back-to-heading t)
7772 (if (let (case-fold-search)
7773 (looking-at
7774 (if orgstruct-mode
7775 org-heading-regexp
7776 org-complex-heading-regexp)))
7777 (if orgstruct-mode
7778 (list (length (match-string 1))
7779 (org-reduced-level (length (match-string 1)))
7782 (match-string 2)
7783 nil)
7784 (list (length (match-string 1))
7785 (org-reduced-level (length (match-string 1)))
7786 (org-match-string-no-properties 2)
7787 (and (match-end 3) (aref (match-string 3) 2))
7788 (org-match-string-no-properties 4)
7789 (org-match-string-no-properties 5))))))
7791 (defun org-get-entry ()
7792 "Get the entry text, after heading, entire subtree."
7793 (save-excursion
7794 (org-back-to-heading t)
7795 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7797 (defun org-insert-heading-after-current ()
7798 "Insert a new heading with same level as current, after current subtree."
7799 (interactive)
7800 (org-back-to-heading)
7801 (org-insert-heading)
7802 (org-move-subtree-down)
7803 (end-of-line 1))
7805 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7806 "Insert heading with `org-insert-heading-respect-content' set to t."
7807 (interactive "P")
7808 (let ((org-insert-heading-respect-content t))
7809 (org-insert-heading '(4) invisible-ok)))
7811 (defun org-insert-todo-heading-respect-content (&optional force-state)
7812 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7813 (interactive "P")
7814 (let ((org-insert-heading-respect-content t))
7815 (org-insert-todo-heading force-state '(4))))
7817 (defun org-insert-todo-heading (arg &optional force-heading)
7818 "Insert a new heading with the same level and TODO state as current heading.
7819 If the heading has no TODO state, or if the state is DONE, use the first
7820 state (TODO by default). Also with one prefix arg, force first state. With
7821 two prefix args, force inserting at the end of the parent subtree."
7822 (interactive "P")
7823 (when (or force-heading (not (org-insert-item 'checkbox)))
7824 (org-insert-heading (or (and (equal arg '(16)) '(16))
7825 force-heading))
7826 (save-excursion
7827 (org-back-to-heading)
7828 (outline-previous-heading)
7829 (looking-at org-todo-line-regexp))
7830 (let*
7831 ((new-mark-x
7832 (if (or (equal arg '(4))
7833 (not (match-beginning 2))
7834 (member (match-string 2) org-done-keywords))
7835 (car org-todo-keywords-1)
7836 (match-string 2)))
7837 (new-mark
7839 (run-hook-with-args-until-success
7840 'org-todo-get-default-hook new-mark-x nil)
7841 new-mark-x)))
7842 (beginning-of-line 1)
7843 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7844 (if org-treat-insert-todo-heading-as-state-change
7845 (org-todo new-mark)
7846 (insert new-mark " "))))
7847 (when org-provide-todo-statistics
7848 (org-update-parent-todo-statistics))))
7850 (defun org-insert-subheading (arg)
7851 "Insert a new subheading and demote it.
7852 Works for outline headings and for plain lists alike."
7853 (interactive "P")
7854 (org-insert-heading arg)
7855 (cond
7856 ((org-at-heading-p) (org-do-demote))
7857 ((org-at-item-p) (org-indent-item))))
7859 (defun org-insert-todo-subheading (arg)
7860 "Insert a new subheading with TODO keyword or checkbox and demote it.
7861 Works for outline headings and for plain lists alike."
7862 (interactive "P")
7863 (org-insert-todo-heading arg)
7864 (cond
7865 ((org-at-heading-p) (org-do-demote))
7866 ((org-at-item-p) (org-indent-item))))
7868 ;;; Promotion and Demotion
7870 (defvar org-after-demote-entry-hook nil
7871 "Hook run after an entry has been demoted.
7872 The cursor will be at the beginning of the entry.
7873 When a subtree is being demoted, the hook will be called for each node.")
7875 (defvar org-after-promote-entry-hook nil
7876 "Hook run after an entry has been promoted.
7877 The cursor will be at the beginning of the entry.
7878 When a subtree is being promoted, the hook will be called for each node.")
7880 (defun org-promote-subtree ()
7881 "Promote the entire subtree.
7882 See also `org-promote'."
7883 (interactive)
7884 (save-excursion
7885 (org-with-limited-levels (org-map-tree 'org-promote)))
7886 (org-fix-position-after-promote))
7888 (defun org-demote-subtree ()
7889 "Demote the entire subtree. See `org-demote'.
7890 See also `org-promote'."
7891 (interactive)
7892 (save-excursion
7893 (org-with-limited-levels (org-map-tree 'org-demote)))
7894 (org-fix-position-after-promote))
7897 (defun org-do-promote ()
7898 "Promote the current heading higher up the tree.
7899 If the region is active in `transient-mark-mode', promote all headings
7900 in the region."
7901 (interactive)
7902 (save-excursion
7903 (if (org-region-active-p)
7904 (org-map-region 'org-promote (region-beginning) (region-end))
7905 (org-promote)))
7906 (org-fix-position-after-promote))
7908 (defun org-do-demote ()
7909 "Demote the current heading lower down the tree.
7910 If the region is active in `transient-mark-mode', demote all headings
7911 in the region."
7912 (interactive)
7913 (save-excursion
7914 (if (org-region-active-p)
7915 (org-map-region 'org-demote (region-beginning) (region-end))
7916 (org-demote)))
7917 (org-fix-position-after-promote))
7919 (defun org-fix-position-after-promote ()
7920 "Make sure that after pro/demotion cursor position is right."
7921 (let ((pos (point)))
7922 (when (save-excursion
7923 (beginning-of-line 1)
7924 (looking-at org-todo-line-regexp)
7925 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7926 (cond ((eobp) (insert " "))
7927 ((eolp) (insert " "))
7928 ((equal (char-after) ?\ ) (forward-char 1))))))
7930 (defun org-current-level ()
7931 "Return the level of the current entry, or nil if before the first headline.
7932 The level is the number of stars at the beginning of the headline."
7933 (save-excursion
7934 (org-with-limited-levels
7935 (if (ignore-errors (org-back-to-heading t))
7936 (funcall outline-level)))))
7938 (defun org-get-previous-line-level ()
7939 "Return the outline depth of the last headline before the current line.
7940 Returns 0 for the first headline in the buffer, and nil if before the
7941 first headline."
7942 (and (org-current-level)
7943 (or (and (/= (line-beginning-position) (point-min))
7944 (save-excursion (beginning-of-line 0) (org-current-level)))
7945 0)))
7947 (defun org-reduced-level (l)
7948 "Compute the effective level of a heading.
7949 This takes into account the setting of `org-odd-levels-only'."
7950 (cond
7951 ((zerop l) 0)
7952 (org-odd-levels-only (1+ (floor (/ l 2))))
7953 (t l)))
7955 (defun org-level-increment ()
7956 "Return the number of stars that will be added or removed at a
7957 time to headlines when structure editing, based on the value of
7958 `org-odd-levels-only'."
7959 (if org-odd-levels-only 2 1))
7961 (defun org-get-valid-level (level &optional change)
7962 "Rectify a level change under the influence of `org-odd-levels-only'
7963 LEVEL is a current level, CHANGE is by how much the level should be
7964 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7965 even level numbers will become the next higher odd number."
7966 (if org-odd-levels-only
7967 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7968 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7969 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7970 (max 1 (+ level (or change 0)))))
7972 (if (boundp 'define-obsolete-function-alias)
7973 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7974 (define-obsolete-function-alias 'org-get-legal-level
7975 'org-get-valid-level)
7976 (define-obsolete-function-alias 'org-get-legal-level
7977 'org-get-valid-level "23.1")))
7979 (defun org-promote ()
7980 "Promote the current heading higher up the tree.
7981 If the region is active in `transient-mark-mode', promote all headings
7982 in the region."
7983 (org-back-to-heading t)
7984 (let* ((level (save-match-data (funcall outline-level)))
7985 (after-change-functions (remove 'flyspell-after-change-function
7986 after-change-functions))
7987 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7988 (diff (abs (- level (length up-head) -1))))
7989 (cond ((and (= level 1) org-called-with-limited-levels
7990 org-allow-promoting-top-level-subtree)
7991 (replace-match "# " nil t))
7992 ((= level 1)
7993 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
7994 (t (replace-match up-head nil t)))
7995 ;; Fixup tag positioning
7996 (unless (= level 1)
7997 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
7998 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7999 (run-hooks 'org-after-promote-entry-hook)))
8001 (defun org-demote ()
8002 "Demote the current heading lower down the tree.
8003 If the region is active in `transient-mark-mode', demote all headings
8004 in the region."
8005 (org-back-to-heading t)
8006 (let* ((level (save-match-data (funcall outline-level)))
8007 (after-change-functions (remove 'flyspell-after-change-function
8008 after-change-functions))
8009 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8010 (diff (abs (- level (length down-head) -1))))
8011 (replace-match down-head nil t)
8012 ;; Fixup tag positioning
8013 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
8014 (if org-adapt-indentation (org-fixup-indentation diff))
8015 (run-hooks 'org-after-demote-entry-hook)))
8017 (defun org-cycle-level ()
8018 "Cycle the level of an empty headline through possible states.
8019 This goes first to child, then to parent, level, then up the hierarchy.
8020 After top level, it switches back to sibling level."
8021 (interactive)
8022 (let ((org-adapt-indentation nil))
8023 (when (org-point-at-end-of-empty-headline)
8024 (setq this-command 'org-cycle-level) ; Only needed for caching
8025 (let ((cur-level (org-current-level))
8026 (prev-level (org-get-previous-line-level)))
8027 (cond
8028 ;; If first headline in file, promote to top-level.
8029 ((= prev-level 0)
8030 (loop repeat (/ (- cur-level 1) (org-level-increment))
8031 do (org-do-promote)))
8032 ;; If same level as prev, demote one.
8033 ((= prev-level cur-level)
8034 (org-do-demote))
8035 ;; If parent is top-level, promote to top level if not already.
8036 ((= prev-level 1)
8037 (loop repeat (/ (- cur-level 1) (org-level-increment))
8038 do (org-do-promote)))
8039 ;; If top-level, return to prev-level.
8040 ((= cur-level 1)
8041 (loop repeat (/ (- prev-level 1) (org-level-increment))
8042 do (org-do-demote)))
8043 ;; If less than prev-level, promote one.
8044 ((< cur-level prev-level)
8045 (org-do-promote))
8046 ;; If deeper than prev-level, promote until higher than
8047 ;; prev-level.
8048 ((> cur-level prev-level)
8049 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8050 do (org-do-promote))))
8051 t))))
8053 (defun org-map-tree (fun)
8054 "Call FUN for every heading underneath the current one."
8055 (org-back-to-heading)
8056 (let ((level (funcall outline-level)))
8057 (save-excursion
8058 (funcall fun)
8059 (while (and (progn
8060 (outline-next-heading)
8061 (> (funcall outline-level) level))
8062 (not (eobp)))
8063 (funcall fun)))))
8065 (defun org-map-region (fun beg end)
8066 "Call FUN for every heading between BEG and END."
8067 (let ((org-ignore-region t))
8068 (save-excursion
8069 (setq end (copy-marker end))
8070 (goto-char beg)
8071 (if (and (re-search-forward org-outline-regexp-bol nil t)
8072 (< (point) end))
8073 (funcall fun))
8074 (while (and (progn
8075 (outline-next-heading)
8076 (< (point) end))
8077 (not (eobp)))
8078 (funcall fun)))))
8080 (defvar org-property-end-re) ; silence byte-compiler
8081 (defun org-fixup-indentation (diff)
8082 "Change the indentation in the current entry by DIFF.
8083 However, if any line in the current entry has no indentation, or if it
8084 would end up with no indentation after the change, nothing at all is done."
8085 (save-excursion
8086 (let ((end (save-excursion (outline-next-heading)
8087 (point-marker)))
8088 (prohibit (if (> diff 0)
8089 "^\\S-"
8090 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8091 col)
8092 (unless (save-excursion (end-of-line 1)
8093 (re-search-forward prohibit end t))
8094 (while (and (< (point) end)
8095 (re-search-forward "^[ \t]+" end t))
8096 (goto-char (match-end 0))
8097 (setq col (current-column))
8098 (if (< diff 0) (replace-match ""))
8099 (org-indent-to-column (+ diff col))))
8100 (move-marker end nil))))
8102 (defun org-convert-to-odd-levels ()
8103 "Convert an org-mode file with all levels allowed to one with odd levels.
8104 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8105 level 5 etc."
8106 (interactive)
8107 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8108 (let ((outline-level 'org-outline-level)
8109 (org-odd-levels-only nil) n)
8110 (save-excursion
8111 (goto-char (point-min))
8112 (while (re-search-forward "^\\*\\*+ " nil t)
8113 (setq n (- (length (match-string 0)) 2))
8114 (while (>= (setq n (1- n)) 0)
8115 (org-demote))
8116 (end-of-line 1))))))
8118 (defun org-convert-to-oddeven-levels ()
8119 "Convert an org-mode file with only odd levels to one with odd/even levels.
8120 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8121 file contains a section with an even level, conversion would
8122 destroy the structure of the file. An error is signaled in this
8123 case."
8124 (interactive)
8125 (goto-char (point-min))
8126 ;; First check if there are no even levels
8127 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8128 (org-show-context t)
8129 (error "Not all levels are odd in this file. Conversion not possible"))
8130 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8131 (let ((outline-regexp org-outline-regexp)
8132 (outline-level 'org-outline-level)
8133 (org-odd-levels-only nil) n)
8134 (save-excursion
8135 (goto-char (point-min))
8136 (while (re-search-forward "^\\*\\*+ " nil t)
8137 (setq n (/ (1- (length (match-string 0))) 2))
8138 (while (>= (setq n (1- n)) 0)
8139 (org-promote))
8140 (end-of-line 1))))))
8142 (defun org-tr-level (n)
8143 "Make N odd if required."
8144 (if org-odd-levels-only (1+ (/ n 2)) n))
8146 ;;; Vertical tree motion, cutting and pasting of subtrees
8148 (defun org-move-subtree-up (&optional arg)
8149 "Move the current subtree up past ARG headlines of the same level."
8150 (interactive "p")
8151 (org-move-subtree-down (- (prefix-numeric-value arg))))
8153 (defun org-move-subtree-down (&optional arg)
8154 "Move the current subtree down past ARG headlines of the same level."
8155 (interactive "p")
8156 (setq arg (prefix-numeric-value arg))
8157 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8158 'org-get-last-sibling))
8159 (ins-point (make-marker))
8160 (cnt (abs arg))
8161 (col (current-column))
8162 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8163 ;; Select the tree
8164 (org-back-to-heading)
8165 (setq beg0 (point))
8166 (save-excursion
8167 (setq ne-beg (org-back-over-empty-lines))
8168 (setq beg (point)))
8169 (save-match-data
8170 (save-excursion (outline-end-of-heading)
8171 (setq folded (outline-invisible-p)))
8172 (progn (org-end-of-subtree nil t)
8173 (unless (eobp) (backward-char))))
8174 (outline-next-heading)
8175 (setq ne-end (org-back-over-empty-lines))
8176 (setq end (point))
8177 (goto-char beg0)
8178 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8179 ;; include less whitespace
8180 (save-excursion
8181 (goto-char beg)
8182 (forward-line (- ne-beg ne-end))
8183 (setq beg (point))))
8184 ;; Find insertion point, with error handling
8185 (while (> cnt 0)
8186 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8187 (progn (goto-char beg0)
8188 (user-error "Cannot move past superior level or buffer limit")))
8189 (setq cnt (1- cnt)))
8190 (if (> arg 0)
8191 ;; Moving forward - still need to move over subtree
8192 (progn (org-end-of-subtree t t)
8193 (save-excursion
8194 (org-back-over-empty-lines)
8195 (or (bolp) (newline)))))
8196 (setq ne-ins (org-back-over-empty-lines))
8197 (move-marker ins-point (point))
8198 (setq txt (buffer-substring beg end))
8199 (org-save-markers-in-region beg end)
8200 (delete-region beg end)
8201 (org-remove-empty-overlays-at beg)
8202 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8203 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8204 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8205 (let ((bbb (point)))
8206 (insert-before-markers txt)
8207 (org-reinstall-markers-in-region bbb)
8208 (move-marker ins-point bbb))
8209 (or (bolp) (insert "\n"))
8210 (setq ins-end (point))
8211 (goto-char ins-point)
8212 (org-skip-whitespace)
8213 (when (and (< arg 0)
8214 (org-first-sibling-p)
8215 (> ne-ins ne-beg))
8216 ;; Move whitespace back to beginning
8217 (save-excursion
8218 (goto-char ins-end)
8219 (let ((kill-whole-line t))
8220 (kill-line (- ne-ins ne-beg)) (point)))
8221 (insert (make-string (- ne-ins ne-beg) ?\n)))
8222 (move-marker ins-point nil)
8223 (if folded
8224 (hide-subtree)
8225 (org-show-entry)
8226 (show-children)
8227 (org-cycle-hide-drawers 'children))
8228 (org-clean-visibility-after-subtree-move)
8229 ;; move back to the initial column we were at
8230 (move-to-column col)))
8232 (defvar org-subtree-clip ""
8233 "Clipboard for cut and paste of subtrees.
8234 This is actually only a copy of the kill, because we use the normal kill
8235 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8237 (defvar org-subtree-clip-folded nil
8238 "Was the last copied subtree folded?
8239 This is used to fold the tree back after pasting.")
8241 (defun org-cut-subtree (&optional n)
8242 "Cut the current subtree into the clipboard.
8243 With prefix arg N, cut this many sequential subtrees.
8244 This is a short-hand for marking the subtree and then cutting it."
8245 (interactive "p")
8246 (org-copy-subtree n 'cut))
8248 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8249 "Copy the current subtree it in the clipboard.
8250 With prefix arg N, copy this many sequential subtrees.
8251 This is a short-hand for marking the subtree and then copying it.
8252 If CUT is non-nil, actually cut the subtree.
8253 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8254 of some markers in the region, even if CUT is non-nil. This is
8255 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8256 (interactive "p")
8257 (let (beg end folded (beg0 (point)))
8258 (if (org-called-interactively-p 'any)
8259 (org-back-to-heading nil) ; take what looks like a subtree
8260 (org-back-to-heading t)) ; take what is really there
8261 (setq beg (point))
8262 (skip-chars-forward " \t\r\n")
8263 (save-match-data
8264 (if nosubtrees
8265 (outline-next-heading)
8266 (save-excursion (outline-end-of-heading)
8267 (setq folded (outline-invisible-p)))
8268 (condition-case nil
8269 (org-forward-heading-same-level (1- n) t)
8270 (error nil))
8271 (org-end-of-subtree t t)))
8272 (setq end (point))
8273 (goto-char beg0)
8274 (when (> end beg)
8275 (setq org-subtree-clip-folded folded)
8276 (when (or cut force-store-markers)
8277 (org-save-markers-in-region beg end))
8278 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8279 (setq org-subtree-clip (current-kill 0))
8280 (message "%s: Subtree(s) with %d characters"
8281 (if cut "Cut" "Copied")
8282 (length org-subtree-clip)))))
8284 (defun org-paste-subtree (&optional level tree for-yank)
8285 "Paste the clipboard as a subtree, with modification of headline level.
8286 The entire subtree is promoted or demoted in order to match a new headline
8287 level.
8289 If the cursor is at the beginning of a headline, the same level as
8290 that headline is used to paste the tree.
8292 If not, the new level is derived from the *visible* headings
8293 before and after the insertion point, and taken to be the inferior headline
8294 level of the two. So if the previous visible heading is level 3 and the
8295 next is level 4 (or vice versa), level 4 will be used for insertion.
8296 This makes sure that the subtree remains an independent subtree and does
8297 not swallow low level entries.
8299 You can also force a different level, either by using a numeric prefix
8300 argument, or by inserting the heading marker by hand. For example, if the
8301 cursor is after \"*****\", then the tree will be shifted to level 5.
8303 If optional TREE is given, use this text instead of the kill ring.
8305 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8306 move back over whitespace before inserting, and move point to the end of
8307 the inserted text when done."
8308 (interactive "P")
8309 (setq tree (or tree (and kill-ring (current-kill 0))))
8310 (unless (org-kill-is-subtree-p tree)
8311 (user-error "%s"
8312 (substitute-command-keys
8313 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8314 (org-with-limited-levels
8315 (let* ((visp (not (outline-invisible-p)))
8316 (txt tree)
8317 (^re_ "\\(\\*+\\)[ \t]*")
8318 (old-level (if (string-match org-outline-regexp-bol txt)
8319 (- (match-end 0) (match-beginning 0) 1)
8320 -1))
8321 (force-level (cond (level (prefix-numeric-value level))
8322 ((and (looking-at "[ \t]*$")
8323 (string-match
8324 "^\\*+$" (buffer-substring
8325 (point-at-bol) (point))))
8326 (- (match-end 1) (match-beginning 1)))
8327 ((and (bolp)
8328 (looking-at org-outline-regexp))
8329 (- (match-end 0) (point) 1))))
8330 (previous-level (save-excursion
8331 (condition-case nil
8332 (progn
8333 (outline-previous-visible-heading 1)
8334 (if (looking-at ^re_)
8335 (- (match-end 0) (match-beginning 0) 1)
8337 (error 1))))
8338 (next-level (save-excursion
8339 (condition-case nil
8340 (progn
8341 (or (looking-at org-outline-regexp)
8342 (outline-next-visible-heading 1))
8343 (if (looking-at ^re_)
8344 (- (match-end 0) (match-beginning 0) 1)
8346 (error 1))))
8347 (new-level (or force-level (max previous-level next-level)))
8348 (shift (if (or (= old-level -1)
8349 (= new-level -1)
8350 (= old-level new-level))
8352 (- new-level old-level)))
8353 (delta (if (> shift 0) -1 1))
8354 (func (if (> shift 0) 'org-demote 'org-promote))
8355 (org-odd-levels-only nil)
8356 beg end newend)
8357 ;; Remove the forced level indicator
8358 (if force-level
8359 (delete-region (point-at-bol) (point)))
8360 ;; Paste
8361 (beginning-of-line (if (bolp) 1 2))
8362 (setq beg (point))
8363 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8364 (insert-before-markers txt)
8365 (unless (string-match "\n\\'" txt) (insert "\n"))
8366 (setq newend (point))
8367 (org-reinstall-markers-in-region beg)
8368 (setq end (point))
8369 (goto-char beg)
8370 (skip-chars-forward " \t\n\r")
8371 (setq beg (point))
8372 (if (and (outline-invisible-p) visp)
8373 (save-excursion (outline-show-heading)))
8374 ;; Shift if necessary
8375 (unless (= shift 0)
8376 (save-restriction
8377 (narrow-to-region beg end)
8378 (while (not (= shift 0))
8379 (org-map-region func (point-min) (point-max))
8380 (setq shift (+ delta shift)))
8381 (goto-char (point-min))
8382 (setq newend (point-max))))
8383 (when (or (org-called-interactively-p 'interactive) for-yank)
8384 (message "Clipboard pasted as level %d subtree" new-level))
8385 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8386 kill-ring
8387 (eq org-subtree-clip (current-kill 0))
8388 org-subtree-clip-folded)
8389 ;; The tree was folded before it was killed/copied
8390 (hide-subtree))
8391 (and for-yank (goto-char newend)))))
8393 (defun org-kill-is-subtree-p (&optional txt)
8394 "Check if the current kill is an outline subtree, or a set of trees.
8395 Returns nil if kill does not start with a headline, or if the first
8396 headline level is not the largest headline level in the tree.
8397 So this will actually accept several entries of equal levels as well,
8398 which is OK for `org-paste-subtree'.
8399 If optional TXT is given, check this string instead of the current kill."
8400 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8401 (re (org-get-limited-outline-regexp))
8402 (^re (concat "^" re))
8403 (start-level (and kill
8404 (string-match
8405 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8406 kill)
8407 (- (match-end 2) (match-beginning 2) 1)))
8408 (start (1+ (or (match-beginning 2) -1))))
8409 (if (not start-level)
8410 (progn
8411 nil) ;; does not even start with a heading
8412 (catch 'exit
8413 (while (setq start (string-match ^re kill (1+ start)))
8414 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8415 (throw 'exit nil)))
8416 t))))
8418 (defvar org-markers-to-move nil
8419 "Markers that should be moved with a cut-and-paste operation.
8420 Those markers are stored together with their positions relative to
8421 the start of the region.")
8423 (defun org-save-markers-in-region (beg end)
8424 "Check markers in region.
8425 If these markers are between BEG and END, record their position relative
8426 to BEG, so that after moving the block of text, we can put the markers back
8427 into place.
8428 This function gets called just before an entry or tree gets cut from the
8429 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8430 called immediately, to move the markers with the entries."
8431 (setq org-markers-to-move nil)
8432 (when (featurep 'org-clock)
8433 (org-clock-save-markers-for-cut-and-paste beg end))
8434 (when (featurep 'org-agenda)
8435 (org-agenda-save-markers-for-cut-and-paste beg end)))
8437 (defun org-check-and-save-marker (marker beg end)
8438 "Check if MARKER is between BEG and END.
8439 If yes, remember the marker and the distance to BEG."
8440 (when (and (marker-buffer marker)
8441 (equal (marker-buffer marker) (current-buffer)))
8442 (if (and (>= marker beg) (< marker end))
8443 (push (cons marker (- marker beg)) org-markers-to-move))))
8445 (defun org-reinstall-markers-in-region (beg)
8446 "Move all remembered markers to their position relative to BEG."
8447 (mapc (lambda (x)
8448 (move-marker (car x) (+ beg (cdr x))))
8449 org-markers-to-move)
8450 (setq org-markers-to-move nil))
8452 (defun org-narrow-to-subtree ()
8453 "Narrow buffer to the current subtree."
8454 (interactive)
8455 (save-excursion
8456 (save-match-data
8457 (org-with-limited-levels
8458 (narrow-to-region
8459 (progn (org-back-to-heading t) (point))
8460 (progn (org-end-of-subtree t t)
8461 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8462 (point)))))))
8464 (defun org-narrow-to-block ()
8465 "Narrow buffer to the current block."
8466 (interactive)
8467 (let* ((case-fold-search t)
8468 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8469 "^[ \t]*#\\+end_.*")))
8470 (if blockp
8471 (narrow-to-region (car blockp) (cdr blockp))
8472 (user-error "Not in a block"))))
8474 (eval-when-compile
8475 (defvar org-property-drawer-re))
8477 (defvar org-property-start-re) ;; defined below
8478 (defun org-clone-subtree-with-time-shift (n &optional shift)
8479 "Clone the task (subtree) at point N times.
8480 The clones will be inserted as siblings.
8482 In interactive use, the user will be prompted for the number of
8483 clones to be produced. If the entry has a timestamp, the user
8484 will also be prompted for a time shift, which may be a repeater
8485 as used in time stamps, for example `+3d'. To disable this,
8486 you can call the function with a universal prefix argument.
8488 When a valid repeater is given and the entry contains any time
8489 stamps, the clones will become a sequence in time, with time
8490 stamps in the subtree shifted for each clone produced. If SHIFT
8491 is nil or the empty string, time stamps will be left alone. The
8492 ID property of the original subtree is removed.
8494 If the original subtree did contain time stamps with a repeater,
8495 the following will happen:
8496 - the repeater will be removed in each clone
8497 - an additional clone will be produced, with the current, unshifted
8498 date(s) in the entry.
8499 - the original entry will be placed *after* all the clones, with
8500 repeater intact.
8501 - the start days in the repeater in the original entry will be shifted
8502 to past the last clone.
8503 In this way you can spell out a number of instances of a repeating task,
8504 and still retain the repeater to cover future instances of the task."
8505 (interactive "nNumber of clones to produce: ")
8506 (let ((shift
8507 (or shift
8508 (if (and (not (equal current-prefix-arg '(4)))
8509 (save-excursion
8510 (re-search-forward org-ts-regexp-both
8511 (save-excursion
8512 (org-end-of-subtree t)
8513 (point)) t)))
8514 (read-from-minibuffer
8515 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8516 ""))) ;; No time shift
8517 (n-no-remove -1)
8518 (drawer-re org-drawer-regexp)
8519 beg end template task idprop
8520 shift-n shift-what doshift nmin nmax)
8521 (if (not (and (integerp n) (> n 0)))
8522 (error "Invalid number of replications %s" n))
8523 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8524 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8525 shift)))
8526 (error "Invalid shift specification %s" shift))
8527 (when doshift
8528 (setq shift-n (string-to-number (match-string 1 shift))
8529 shift-what (cdr (assoc (match-string 2 shift)
8530 '(("d" . day) ("w" . week)
8531 ("m" . month) ("y" . year))))))
8532 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8533 (setq nmin 1 nmax n)
8534 (org-back-to-heading t)
8535 (setq beg (point))
8536 (setq idprop (org-entry-get nil "ID"))
8537 (org-end-of-subtree t t)
8538 (or (bolp) (insert "\n"))
8539 (setq end (point))
8540 (setq template (buffer-substring beg end))
8541 (when (and doshift
8542 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8543 (delete-region beg end)
8544 (setq end beg)
8545 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8546 (goto-char end)
8547 (loop for n from nmin to nmax do
8548 ;; prepare clone
8549 (with-temp-buffer
8550 (insert template)
8551 (org-mode)
8552 (goto-char (point-min))
8553 (org-show-subtree)
8554 (and idprop (if org-clone-delete-id
8555 (org-entry-delete nil "ID")
8556 (org-id-get-create t)))
8557 (unless (= n 0)
8558 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8559 (kill-whole-line))
8560 (goto-char (point-min))
8561 (while (re-search-forward drawer-re nil t)
8562 (mapc (lambda (d)
8563 (org-remove-empty-drawer-at d (point))) org-drawers)))
8564 (goto-char (point-min))
8565 (when doshift
8566 (while (re-search-forward org-ts-regexp-both nil t)
8567 (org-timestamp-change (* n shift-n) shift-what))
8568 (unless (= n n-no-remove)
8569 (goto-char (point-min))
8570 (while (re-search-forward org-ts-regexp nil t)
8571 (save-excursion
8572 (goto-char (match-beginning 0))
8573 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8574 (delete-region (match-beginning 1) (match-end 1)))))))
8575 (setq task (buffer-string)))
8576 (insert task))
8577 (goto-char beg)))
8579 ;;; Outline Sorting
8581 (defun org-sort (with-case)
8582 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8583 Optional argument WITH-CASE means sort case-sensitively."
8584 (interactive "P")
8585 (cond
8586 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8587 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8589 (org-call-with-arg 'org-sort-entries with-case))))
8591 (defun org-sort-remove-invisible (s)
8592 "Remove invisible links from string S."
8593 (remove-text-properties 0 (length s) org-rm-props s)
8594 (while (string-match org-bracket-link-regexp s)
8595 (setq s (replace-match (if (match-end 2)
8596 (match-string 3 s)
8597 (match-string 1 s)) t t s)))
8598 (let ((st (format " %s " s)))
8599 (while (string-match org-emph-re st)
8600 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8601 (setq s (substring st 1 -1)))
8604 (defvar org-priority-regexp) ; defined later in the file
8606 (defvar org-after-sorting-entries-or-items-hook nil
8607 "Hook that is run after a bunch of entries or items have been sorted.
8608 When children are sorted, the cursor is in the parent line when this
8609 hook gets called. When a region or a plain list is sorted, the cursor
8610 will be in the first entry of the sorted region/list.")
8612 (defun org-sort-entries
8613 (&optional with-case sorting-type getkey-func compare-func property)
8614 "Sort entries on a certain level of an outline tree.
8615 If there is an active region, the entries in the region are sorted.
8616 Else, if the cursor is before the first entry, sort the top-level items.
8617 Else, the children of the entry at point are sorted.
8619 Sorting can be alphabetically, numerically, by date/time as given by
8620 a time stamp, by a property, by priority order, or by a custom function.
8622 The command prompts for the sorting type unless it has been given to the
8623 function through the SORTING-TYPE argument, which needs to be a character,
8624 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8625 precise meaning of each character:
8627 n Numerically, by converting the beginning of the entry/item to a number.
8628 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8629 o By order of TODO keywords.
8630 t By date/time, either the first active time stamp in the entry, or, if
8631 none exist, by the first inactive one.
8632 s By the scheduled date/time.
8633 d By deadline date/time.
8634 c By creation time, which is assumed to be the first inactive time stamp
8635 at the beginning of a line.
8636 p By priority according to the cookie.
8637 r By the value of a property.
8639 Capital letters will reverse the sort order.
8641 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8642 called with point at the beginning of the record. It must return either
8643 a string or a number that should serve as the sorting key for that record.
8645 Comparing entries ignores case by default. However, with an optional argument
8646 WITH-CASE, the sorting considers case as well.
8648 Sorting is done against the visible part of the headlines, it ignores hidden
8649 links."
8650 (interactive "P")
8651 (let ((case-func (if with-case 'identity 'downcase))
8652 (cmstr
8653 ;; The clock marker is lost when using `sort-subr', let's
8654 ;; store the clocking string.
8655 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8656 (save-excursion
8657 (goto-char org-clock-marker)
8658 (looking-back "^.*") (match-string-no-properties 0))))
8659 start beg end stars re re2
8660 txt what tmp)
8661 ;; Find beginning and end of region to sort
8662 (cond
8663 ((org-region-active-p)
8664 ;; we will sort the region
8665 (setq end (region-end)
8666 what "region")
8667 (goto-char (region-beginning))
8668 (if (not (org-at-heading-p)) (outline-next-heading))
8669 (setq start (point)))
8670 ((or (org-at-heading-p)
8671 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8672 ;; we will sort the children of the current headline
8673 (org-back-to-heading)
8674 (setq start (point)
8675 end (progn (org-end-of-subtree t t)
8676 (or (bolp) (insert "\n"))
8677 (when (>= (org-back-over-empty-lines) 1)
8678 (forward-line 1))
8679 (point))
8680 what "children")
8681 (goto-char start)
8682 (show-subtree)
8683 (outline-next-heading))
8685 ;; we will sort the top-level entries in this file
8686 (goto-char (point-min))
8687 (or (org-at-heading-p) (outline-next-heading))
8688 (setq start (point))
8689 (goto-char (point-max))
8690 (beginning-of-line 1)
8691 (when (looking-at ".*?\\S-")
8692 ;; File ends in a non-white line
8693 (end-of-line 1)
8694 (insert "\n"))
8695 (setq end (point-max))
8696 (setq what "top-level")
8697 (goto-char start)
8698 (show-all)))
8700 (setq beg (point))
8701 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8703 (looking-at "\\(\\*+\\)")
8704 (setq stars (match-string 1)
8705 re (concat "^" (regexp-quote stars) " +")
8706 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8707 txt (buffer-substring beg end))
8708 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8709 (if (and (not (equal stars "*")) (string-match re2 txt))
8710 (user-error "Region to sort contains a level above the first entry"))
8712 (unless sorting-type
8713 (message
8714 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8715 [t]ime [s]cheduled [d]eadline [c]reated
8716 A/N/P/R/O/F/T/S/D/C means reversed:"
8717 what)
8718 (setq sorting-type (read-char-exclusive))
8720 (unless getkey-func
8721 (and (= (downcase sorting-type) ?f)
8722 (setq getkey-func
8723 (org-icompleting-read "Sort using function: "
8724 obarray 'fboundp t nil nil))
8725 (setq getkey-func (intern getkey-func))))
8727 (and (= (downcase sorting-type) ?r)
8728 (not property)
8729 (setq property
8730 (org-icompleting-read "Property: "
8731 (mapcar 'list (org-buffer-property-keys t))
8732 nil t))))
8734 (message "Sorting entries...")
8736 (save-restriction
8737 (narrow-to-region start end)
8738 (let ((dcst (downcase sorting-type))
8739 (case-fold-search nil)
8740 (now (current-time)))
8741 (sort-subr
8742 (/= dcst sorting-type)
8743 ;; This function moves to the beginning character of the "record" to
8744 ;; be sorted.
8745 (lambda nil
8746 (if (re-search-forward re nil t)
8747 (goto-char (match-beginning 0))
8748 (goto-char (point-max))))
8749 ;; This function moves to the last character of the "record" being
8750 ;; sorted.
8751 (lambda nil
8752 (save-match-data
8753 (condition-case nil
8754 (outline-forward-same-level 1)
8755 (error
8756 (goto-char (point-max))))))
8757 ;; This function returns the value that gets sorted against.
8758 (lambda nil
8759 (cond
8760 ((= dcst ?n)
8761 (if (looking-at org-complex-heading-regexp)
8762 (string-to-number (org-sort-remove-invisible (match-string 4)))
8763 nil))
8764 ((= dcst ?a)
8765 (if (looking-at org-complex-heading-regexp)
8766 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8767 nil))
8768 ((= dcst ?t)
8769 (let ((end (save-excursion (outline-next-heading) (point))))
8770 (if (or (re-search-forward org-ts-regexp end t)
8771 (re-search-forward org-ts-regexp-both end t))
8772 (org-time-string-to-seconds (match-string 0))
8773 (org-float-time now))))
8774 ((= dcst ?c)
8775 (let ((end (save-excursion (outline-next-heading) (point))))
8776 (if (re-search-forward
8777 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8778 end t)
8779 (org-time-string-to-seconds (match-string 0))
8780 (org-float-time now))))
8781 ((= dcst ?s)
8782 (let ((end (save-excursion (outline-next-heading) (point))))
8783 (if (re-search-forward org-scheduled-time-regexp end t)
8784 (org-time-string-to-seconds (match-string 1))
8785 (org-float-time now))))
8786 ((= dcst ?d)
8787 (let ((end (save-excursion (outline-next-heading) (point))))
8788 (if (re-search-forward org-deadline-time-regexp end t)
8789 (org-time-string-to-seconds (match-string 1))
8790 (org-float-time now))))
8791 ((= dcst ?p)
8792 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8793 (string-to-char (match-string 2))
8794 org-default-priority))
8795 ((= dcst ?r)
8796 (or (org-entry-get nil property) ""))
8797 ((= dcst ?o)
8798 (if (looking-at org-complex-heading-regexp)
8799 (- 9999 (length (member (match-string 2)
8800 org-todo-keywords-1)))))
8801 ((= dcst ?f)
8802 (if getkey-func
8803 (progn
8804 (setq tmp (funcall getkey-func))
8805 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8806 tmp)
8807 (error "Invalid key function `%s'" getkey-func)))
8808 (t (error "Invalid sorting type `%c'" sorting-type))))
8810 (cond
8811 ((= dcst ?a) 'string<)
8812 ((= dcst ?f) compare-func)
8813 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8814 (run-hooks 'org-after-sorting-entries-or-items-hook)
8815 ;; Reset the clock marker if needed
8816 (when cmstr
8817 (save-excursion
8818 (goto-char start)
8819 (search-forward cmstr nil t)
8820 (move-marker org-clock-marker (point))))
8821 (message "Sorting entries...done")))
8823 (defun org-do-sort (table what &optional with-case sorting-type)
8824 "Sort TABLE of WHAT according to SORTING-TYPE.
8825 The user will be prompted for the SORTING-TYPE if the call to this
8826 function does not specify it. WHAT is only for the prompt, to indicate
8827 what is being sorted. The sorting key will be extracted from
8828 the car of the elements of the table.
8829 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8830 (unless sorting-type
8831 (message
8832 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8833 what)
8834 (setq sorting-type (read-char-exclusive)))
8835 (let ((dcst (downcase sorting-type))
8836 extractfun comparefun)
8837 ;; Define the appropriate functions
8838 (cond
8839 ((= dcst ?n)
8840 (setq extractfun 'string-to-number
8841 comparefun (if (= dcst sorting-type) '< '>)))
8842 ((= dcst ?a)
8843 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8844 (lambda(x) (downcase (org-sort-remove-invisible x))))
8845 comparefun (if (= dcst sorting-type)
8846 'string<
8847 (lambda (a b) (and (not (string< a b))
8848 (not (string= a b)))))))
8849 ((= dcst ?t)
8850 (setq extractfun
8851 (lambda (x)
8852 (if (or (string-match org-ts-regexp x)
8853 (string-match org-ts-regexp-both x))
8854 (org-float-time
8855 (org-time-string-to-time (match-string 0 x)))
8857 comparefun (if (= dcst sorting-type) '< '>)))
8858 (t (error "Invalid sorting type `%c'" sorting-type)))
8860 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8861 table)
8862 (lambda (a b) (funcall comparefun (car a) (car b))))))
8865 ;;; The orgstruct minor mode
8867 ;; Define a minor mode which can be used in other modes in order to
8868 ;; integrate the org-mode structure editing commands.
8870 ;; This is really a hack, because the org-mode structure commands use
8871 ;; keys which normally belong to the major mode. Here is how it
8872 ;; works: The minor mode defines all the keys necessary to operate the
8873 ;; structure commands, but wraps the commands into a function which
8874 ;; tests if the cursor is currently at a headline or a plain list
8875 ;; item. If that is the case, the structure command is used,
8876 ;; temporarily setting many Org-mode variables like regular
8877 ;; expressions for filling etc. However, when any of those keys is
8878 ;; used at a different location, function uses `key-binding' to look
8879 ;; up if the key has an associated command in another currently active
8880 ;; keymap (minor modes, major mode, global), and executes that
8881 ;; command. There might be problems if any of the keys is otherwise
8882 ;; used as a prefix key.
8884 (defcustom orgstruct-heading-prefix-regexp ""
8885 "Regexp that matches the custom prefix of Org headlines in
8886 orgstruct(++)-mode."
8887 :group 'org
8888 :version "24.4"
8889 :package-version '(Org . "8.3")
8890 :type 'regexp)
8891 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8893 (defcustom orgstruct-setup-hook nil
8894 "Hook run after orgstruct-mode-map is filled."
8895 :group 'org
8896 :version "24.4"
8897 :package-version '(Org . "8.0")
8898 :type 'hook)
8900 (defvar orgstruct-initialized nil)
8902 (defvar org-local-vars nil
8903 "List of local variables, for use by `orgstruct-mode'.")
8905 ;;;###autoload
8906 (define-minor-mode orgstruct-mode
8907 "Toggle the minor mode `orgstruct-mode'.
8908 This mode is for using Org-mode structure commands in other
8909 modes. The following keys behave as if Org-mode were active, if
8910 the cursor is on a headline, or on a plain list item (both as
8911 defined by Org-mode)."
8912 nil " OrgStruct" (make-sparse-keymap)
8913 (funcall (if orgstruct-mode
8914 'add-to-invisibility-spec
8915 'remove-from-invisibility-spec)
8916 '(outline . t))
8917 (when orgstruct-mode
8918 (org-load-modules-maybe)
8919 (unless orgstruct-initialized
8920 (orgstruct-setup)
8921 (setq orgstruct-initialized t))))
8923 ;;;###autoload
8924 (defun turn-on-orgstruct ()
8925 "Unconditionally turn on `orgstruct-mode'."
8926 (orgstruct-mode 1))
8928 (defvar org-fb-vars nil)
8929 (make-variable-buffer-local 'org-fb-vars)
8930 (defun orgstruct++-mode (&optional arg)
8931 "Toggle `orgstruct-mode', the enhanced version of it.
8932 In addition to setting orgstruct-mode, this also exports all
8933 indentation and autofilling variables from org-mode into the
8934 buffer. It will also recognize item context in multiline items."
8935 (interactive "P")
8936 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8937 (if (< arg 1)
8938 (progn (orgstruct-mode -1)
8939 (mapc (lambda(v)
8940 (org-set-local (car v)
8941 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8942 org-fb-vars))
8943 (orgstruct-mode 1)
8944 (setq org-fb-vars nil)
8945 (unless org-local-vars
8946 (setq org-local-vars (org-get-local-variables)))
8947 (let (var val)
8948 (mapc
8949 (lambda (x)
8950 (when (string-match
8951 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8952 (symbol-name (car x)))
8953 (setq var (car x) val (nth 1 x))
8954 (push (list var `(quote ,(eval var))) org-fb-vars)
8955 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8956 org-local-vars)
8957 (org-set-local 'orgstruct-is-++ t))))
8959 (defvar orgstruct-is-++ nil
8960 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8961 (make-variable-buffer-local 'orgstruct-is-++)
8963 ;;;###autoload
8964 (defun turn-on-orgstruct++ ()
8965 "Unconditionally turn on `orgstruct++-mode'."
8966 (orgstruct++-mode 1))
8968 (defun orgstruct-error ()
8969 "Error when there is no default binding for a structure key."
8970 (interactive)
8971 (funcall (if (fboundp 'user-error)
8972 'user-error
8973 'error)
8974 "This key has no function outside structure elements"))
8976 (defun orgstruct-setup ()
8977 "Setup orgstruct keymap."
8978 (dolist (cell '((org-demote . t)
8979 (org-metaleft . t)
8980 (org-metaright . t)
8981 (org-promote . t)
8982 (org-shiftmetaleft . t)
8983 (org-shiftmetaright . t)
8984 org-backward-element
8985 org-backward-heading-same-level
8986 org-ctrl-c-ret
8987 org-ctrl-c-minus
8988 org-ctrl-c-star
8989 org-cycle
8990 org-forward-heading-same-level
8991 org-insert-heading
8992 org-insert-heading-respect-content
8993 org-kill-note-or-show-branches
8994 org-mark-subtree
8995 org-meta-return
8996 org-metadown
8997 org-metaup
8998 org-narrow-to-subtree
8999 org-promote-subtree
9000 org-reveal
9001 org-shiftdown
9002 org-shiftleft
9003 org-shiftmetadown
9004 org-shiftmetaup
9005 org-shiftright
9006 org-shifttab
9007 org-shifttab
9008 org-shiftup
9009 org-show-subtree
9010 org-sort
9011 org-up-element
9012 outline-demote
9013 outline-next-visible-heading
9014 outline-previous-visible-heading
9015 outline-promote
9016 outline-up-heading
9017 show-children))
9018 (let ((f (or (car-safe cell) cell))
9019 (disable-when-heading-prefix (cdr-safe cell)))
9020 (when (fboundp f)
9021 (let ((new-bindings))
9022 (dolist (binding (nconc (where-is-internal f org-mode-map)
9023 (where-is-internal f outline-mode-map)))
9024 (push binding new-bindings)
9025 ;; TODO use local-function-key-map
9026 (dolist (rep '(("<tab>" . "TAB")
9027 ("<return>" . "RET")
9028 ("<escape>" . "ESC")
9029 ("<delete>" . "DEL")))
9030 (setq binding (read-kbd-macro
9031 (let ((case-fold-search))
9032 (replace-regexp-in-string
9033 (regexp-quote (cdr rep))
9034 (car rep)
9035 (key-description binding)))))
9036 (pushnew binding new-bindings :test 'equal)))
9037 (dolist (binding new-bindings)
9038 (let ((key (lookup-key orgstruct-mode-map binding)))
9039 (when (or (not key) (numberp key))
9040 (condition-case nil
9041 (org-defkey orgstruct-mode-map
9042 binding
9043 (orgstruct-make-binding f binding disable-when-heading-prefix))
9044 (error nil)))))))))
9045 (run-hooks 'orgstruct-setup-hook))
9047 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9048 "Create a function for binding in the structure minor mode.
9049 FUN is the command to call inside a table. KEY is the key that
9050 should be checked in for a command to execute outside of tables.
9051 Non-nil `disable-when-heading-prefix' means to disable the command
9052 if `orgstruct-heading-prefix-regexp' is not empty."
9053 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9054 (let ((nname name)
9055 (i 0))
9056 (while (fboundp (intern nname))
9057 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9058 (setq name (intern nname)))
9059 (eval
9060 (let ((bindings '((org-heading-regexp
9061 (concat "^"
9062 orgstruct-heading-prefix-regexp
9063 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9064 (org-outline-regexp
9065 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9066 (org-outline-regexp-bol
9067 (concat "^" org-outline-regexp))
9068 (outline-regexp org-outline-regexp)
9069 (outline-heading-end-regexp "\n")
9070 (outline-level 'org-outline-level)
9071 (outline-heading-alist))))
9072 `(defun ,name (arg)
9073 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9074 "Outside of structure, run the binding of `"
9075 (key-description key) "'."
9076 (when disable-when-heading-prefix
9077 (concat
9078 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9079 "back to the default binding due to limitations of Org's implementation of\n"
9080 "`" (symbol-name fun) "'.")))
9081 (interactive "p")
9082 (let* ((disable
9083 ,(and disable-when-heading-prefix
9084 '(not (string= orgstruct-heading-prefix-regexp ""))))
9085 (fallback
9086 (or disable
9087 (not
9088 (let* ,bindings
9089 (org-context-p 'headline 'item
9090 ,(when (memq fun
9091 '(org-insert-heading
9092 org-insert-heading-respect-content
9093 org-meta-return))
9094 '(when orgstruct-is-++
9095 'item-body))))))))
9096 (if fallback
9097 (let* ((orgstruct-mode)
9098 (binding
9099 (loop with key = ,key
9100 for rep in
9101 '(nil
9102 ("<\\([^>]*\\)tab>" . "\\1TAB")
9103 ("<\\([^>]*\\)return>" . "\\1RET")
9104 ("<\\([^>]*\\)escape>" . "\\1ESC")
9105 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9107 (when rep
9108 (setq key (read-kbd-macro
9109 (let ((case-fold-search))
9110 (replace-regexp-in-string
9111 (car rep)
9112 (cdr rep)
9113 (key-description key))))))
9114 thereis (key-binding key))))
9115 (if (keymapp binding)
9116 (org-set-transient-map binding)
9117 (let ((func (or binding
9118 (unless disable
9119 'orgstruct-error))))
9120 (when func
9121 (call-interactively func)))))
9122 (org-run-like-in-org-mode
9123 (lambda ()
9124 (interactive)
9125 (let* ,bindings
9126 (call-interactively ',fun)))))))))
9127 name))
9129 (defun org-contextualize-keys (alist contexts)
9130 "Return valid elements in ALIST depending on CONTEXTS.
9132 `org-agenda-custom-commands' or `org-capture-templates' are the
9133 values used for ALIST, and `org-agenda-custom-commands-contexts'
9134 or `org-capture-templates-contexts' are the associated contexts
9135 definitions."
9136 (let ((contexts
9137 ;; normalize contexts
9138 (mapcar
9139 (lambda(c) (cond ((listp (cadr c))
9140 (list (car c) (car c) (cadr c)))
9141 ((string= "" (cadr c))
9142 (list (car c) (car c) (caddr c)))
9143 (t c))) contexts))
9144 (a alist) c r s)
9145 ;; loop over all commands or templates
9146 (while (setq c (pop a))
9147 (let (vrules repl)
9148 (cond
9149 ((not (assoc (car c) contexts))
9150 (push c r))
9151 ((and (assoc (car c) contexts)
9152 (setq vrules (org-contextualize-validate-key
9153 (car c) contexts)))
9154 (mapc (lambda (vr)
9155 (when (not (equal (car vr) (cadr vr)))
9156 (setq repl vr))) vrules)
9157 (if (not repl) (push c r)
9158 (push (cadr repl) s)
9159 (push
9160 (cons (car c)
9161 (cdr (or (assoc (cadr repl) alist)
9162 (error "Undefined key `%s' as contextual replacement for `%s'"
9163 (cadr repl) (car c)))))
9164 r))))))
9165 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9166 (delq
9168 (delete-dups
9169 (mapcar (lambda (x)
9170 (let ((tpl (car x)))
9171 (when (not (delq
9173 (mapcar (lambda(y)
9174 (equal y tpl)) s))) x)))
9175 (reverse r))))))
9177 (defun org-contextualize-validate-key (key contexts)
9178 "Check CONTEXTS for agenda or capture KEY."
9179 (let (r rr res)
9180 (while (setq r (pop contexts))
9181 (mapc
9182 (lambda (rr)
9183 (when
9184 (and (equal key (car r))
9185 (if (functionp rr) (funcall rr)
9186 (or (and (eq (car rr) 'in-file)
9187 (buffer-file-name)
9188 (string-match (cdr rr) (buffer-file-name)))
9189 (and (eq (car rr) 'in-mode)
9190 (string-match (cdr rr) (symbol-name major-mode)))
9191 (and (eq (car rr) 'in-buffer)
9192 (string-match (cdr rr) (buffer-name)))
9193 (when (and (eq (car rr) 'not-in-file)
9194 (buffer-file-name))
9195 (not (string-match (cdr rr) (buffer-file-name))))
9196 (when (eq (car rr) 'not-in-mode)
9197 (not (string-match (cdr rr) (symbol-name major-mode))))
9198 (when (eq (car rr) 'not-in-buffer)
9199 (not (string-match (cdr rr) (buffer-name)))))))
9200 (push r res)))
9201 (car (last r))))
9202 (delete-dups (delq nil res))))
9204 (defun org-context-p (&rest contexts)
9205 "Check if local context is any of CONTEXTS.
9206 Possible values in the list of contexts are `table', `headline', and `item'."
9207 (let ((pos (point)))
9208 (goto-char (point-at-bol))
9209 (prog1 (or (and (memq 'table contexts)
9210 (looking-at "[ \t]*|"))
9211 (and (memq 'headline contexts)
9212 (looking-at org-outline-regexp))
9213 (and (memq 'item contexts)
9214 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9215 (and (memq 'item-body contexts)
9216 (org-in-item-p)))
9217 (goto-char pos))))
9219 (defun org-get-local-variables ()
9220 "Return a list of all local variables in an Org mode buffer."
9221 (let (varlist)
9222 (with-current-buffer (get-buffer-create "*Org tmp*")
9223 (erase-buffer)
9224 (org-mode)
9225 (setq varlist (buffer-local-variables)))
9226 (kill-buffer "*Org tmp*")
9227 (delq nil
9228 (mapcar
9229 (lambda (x)
9230 (setq x
9231 (if (symbolp x)
9232 (list x)
9233 (list (car x) (cdr x))))
9234 (if (and (not (get (car x) 'org-state))
9235 (string-match
9236 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9237 (symbol-name (car x))))
9238 x nil))
9239 varlist))))
9241 (defun org-clone-local-variables (from-buffer &optional regexp)
9242 "Clone local variables from FROM-BUFFER.
9243 Optional argument REGEXP selects variables to clone."
9244 (mapc
9245 (lambda (pair)
9246 (and (symbolp (car pair))
9247 (or (null regexp)
9248 (string-match regexp (symbol-name (car pair))))
9249 (set (make-local-variable (car pair))
9250 (cdr pair))))
9251 (buffer-local-variables from-buffer)))
9253 ;;;###autoload
9254 (defun org-run-like-in-org-mode (cmd)
9255 "Run a command, pretending that the current buffer is in Org-mode.
9256 This will temporarily bind local variables that are typically bound in
9257 Org-mode to the values they have in Org-mode, and then interactively
9258 call CMD."
9259 (org-load-modules-maybe)
9260 (unless org-local-vars
9261 (setq org-local-vars (org-get-local-variables)))
9262 (let (binds)
9263 (dolist (var org-local-vars)
9264 (when (or (not (boundp (car var)))
9265 (eq (symbol-value (car var))
9266 (default-value (car var))))
9267 (push (list (car var) `(quote ,(cadr var))) binds)))
9268 (eval `(let ,binds
9269 (call-interactively (quote ,cmd))))))
9271 ;;;; Archiving
9273 (defun org-get-category (&optional pos force-refresh)
9274 "Get the category applying to position POS."
9275 (save-match-data
9276 (if force-refresh (org-refresh-category-properties))
9277 (let ((pos (or pos (point))))
9278 (or (get-text-property pos 'org-category)
9279 (progn (org-refresh-category-properties)
9280 (get-text-property pos 'org-category))))))
9282 (defun org-refresh-category-properties ()
9283 "Refresh category text properties in the buffer."
9284 (let ((case-fold-search t)
9285 (inhibit-read-only t)
9286 (def-cat (cond
9287 ((null org-category)
9288 (if buffer-file-name
9289 (file-name-sans-extension
9290 (file-name-nondirectory buffer-file-name))
9291 "???"))
9292 ((symbolp org-category) (symbol-name org-category))
9293 (t org-category)))
9294 beg end cat pos optionp)
9295 (org-with-silent-modifications
9296 (save-excursion
9297 (save-restriction
9298 (widen)
9299 (goto-char (point-min))
9300 (put-text-property (point) (point-max) 'org-category def-cat)
9301 (while (re-search-forward
9302 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9303 (setq pos (match-end 0)
9304 optionp (equal (char-after (match-beginning 0)) ?#)
9305 cat (org-trim (match-string 2)))
9306 (if optionp
9307 (setq beg (point-at-bol) end (point-max))
9308 (org-back-to-heading t)
9309 (setq beg (point) end (org-end-of-subtree t t)))
9310 (put-text-property beg end 'org-category cat)
9311 (put-text-property beg end 'org-category-position beg)
9312 (goto-char pos)))))))
9314 (defun org-refresh-properties (dprop tprop)
9315 "Refresh buffer text properties.
9316 DPROP is the drawer property and TPROP is the corresponding text
9317 property to set."
9318 (let ((case-fold-search t)
9319 (inhibit-read-only t) p)
9320 (org-with-silent-modifications
9321 (save-excursion
9322 (save-restriction
9323 (widen)
9324 (goto-char (point-min))
9325 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9326 (setq p (org-match-string-no-properties 1))
9327 (save-excursion
9328 (org-back-to-heading t)
9329 (put-text-property
9330 (point-at-bol) (or (outline-next-heading) (point-max)) tprop p))))))))
9333 ;;;; Link Stuff
9335 ;;; Link abbreviations
9337 (defun org-link-expand-abbrev (link)
9338 "Apply replacements as defined in `org-link-abbrev-alist'."
9339 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9340 (let* ((key (match-string 1 link))
9341 (as (or (assoc key org-link-abbrev-alist-local)
9342 (assoc key org-link-abbrev-alist)))
9343 (tag (and (match-end 2) (match-string 3 link)))
9344 rpl)
9345 (if (not as)
9346 link
9347 (setq rpl (cdr as))
9348 (cond
9349 ((symbolp rpl) (funcall rpl tag))
9350 ((string-match "%(\\([^)]+\\))" rpl)
9351 (replace-match
9352 (save-match-data
9353 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9354 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9355 ((string-match "%h" rpl)
9356 (replace-match (url-hexify-string (or tag "")) t t rpl))
9357 (t (concat rpl tag)))))
9358 link))
9360 ;;; Storing and inserting links
9362 (defvar org-insert-link-history nil
9363 "Minibuffer history for links inserted with `org-insert-link'.")
9365 (defvar org-stored-links nil
9366 "Contains the links stored with `org-store-link'.")
9368 (defvar org-store-link-plist nil
9369 "Plist with info about the most recently link created with `org-store-link'.")
9371 (defvar org-link-protocols nil
9372 "Link protocols added to Org-mode using `org-add-link-type'.")
9374 (defvar org-store-link-functions nil
9375 "List of functions that are called to create and store a link.
9376 Each function will be called in turn until one returns a non-nil
9377 value. Each function should check if it is responsible for creating
9378 this link (for example by looking at the major mode).
9379 If not, it must exit and return nil.
9380 If yes, it should return a non-nil value after a calling
9381 `org-store-link-props' with a list of properties and values.
9382 Special properties are:
9384 :type The link prefix, like \"http\". This must be given.
9385 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9386 This is obligatory as well.
9387 :description Optional default description for the second pair
9388 of brackets in an Org-mode link. The user can still change
9389 this when inserting this link into an Org-mode buffer.
9391 In addition to these, any additional properties can be specified
9392 and then used in capture templates.")
9394 (defun org-add-link-type (type &optional follow export)
9395 "Add TYPE to the list of `org-link-types'.
9396 Re-compute all regular expressions depending on `org-link-types'
9398 FOLLOW and EXPORT are two functions.
9400 FOLLOW should take the link path as the single argument and do whatever
9401 is necessary to follow the link, for example find a file or display
9402 a mail message.
9404 EXPORT should format the link path for export to one of the export formats.
9405 It should be a function accepting three arguments:
9407 path the path of the link, the text after the prefix (like \"http:\")
9408 desc the description of the link, if any, or a description added by
9409 org-export-normalize-links if there is none
9410 format the export format, a symbol like `html' or `latex' or `ascii'..
9412 The function may use the FORMAT information to return different values
9413 depending on the format. The return value will be put literally into
9414 the exported file. If the return value is nil, this means Org should
9415 do what it normally does with links which do not have EXPORT defined.
9417 Org-mode has a built-in default for exporting links. If you are happy with
9418 this default, there is no need to define an export function for the link
9419 type. For a simple example of an export function, see `org-bbdb.el'."
9420 (add-to-list 'org-link-types type t)
9421 (org-make-link-regexps)
9422 (if (assoc type org-link-protocols)
9423 (setcdr (assoc type org-link-protocols) (list follow export))
9424 (push (list type follow export) org-link-protocols)))
9426 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9427 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9429 ;;;###autoload
9430 (defun org-store-link (arg)
9431 "\\<org-mode-map>Store an org-link to the current location.
9432 This link is added to `org-stored-links' and can later be inserted
9433 into an org-buffer with \\[org-insert-link].
9435 For some link types, a prefix arg is interpreted.
9436 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9437 For file links, arg negates `org-context-in-file-links'.
9439 A double prefix arg force skipping storing functions that are not
9440 part of Org's core.
9442 A triple prefix arg force storing a link for each line in the
9443 active region."
9444 (interactive "P")
9445 (org-load-modules-maybe)
9446 (if (and (equal arg '(64)) (org-region-active-p))
9447 (save-excursion
9448 (let ((end (region-end)))
9449 (goto-char (region-beginning))
9450 (set-mark (point))
9451 (while (< (point-at-eol) end)
9452 (move-end-of-line 1) (activate-mark)
9453 (let (current-prefix-arg)
9454 (call-interactively 'org-store-link))
9455 (move-beginning-of-line 2)
9456 (set-mark (point)))))
9457 (org-with-limited-levels
9458 (setq org-store-link-plist nil)
9459 (let (link cpltxt desc description search
9460 txt custom-id agenda-link sfuns sfunsn)
9461 (cond
9463 ;; Store a link using an external link type
9464 ((and (not (equal arg '(16)))
9465 (setq sfuns
9466 (delq
9467 nil (mapcar (lambda (f)
9468 (let (fs) (if (funcall f) (push f fs))))
9469 org-store-link-functions))
9470 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9471 (or (and (cdr sfuns)
9472 (funcall (intern
9473 (completing-read
9474 "Which function for creating the link? "
9475 sfunsn nil t (car sfunsn)))))
9476 (funcall (caar sfuns)))
9477 (setq link (plist-get org-store-link-plist :link)
9478 desc (or (plist-get org-store-link-plist
9479 :description) link))))
9481 ;; Store a link from a source code buffer
9482 ((org-src-edit-buffer-p)
9483 (let (label gc)
9484 (while (or (not label)
9485 (save-excursion
9486 (save-restriction
9487 (widen)
9488 (goto-char (point-min))
9489 (re-search-forward
9490 (regexp-quote (format org-coderef-label-format label))
9491 nil t))))
9492 (when label (message "Label exists already") (sit-for 2))
9493 (setq label (read-string "Code line label: " label)))
9494 (end-of-line 1)
9495 (setq link (format org-coderef-label-format label))
9496 (setq gc (- 79 (length link)))
9497 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9498 (insert link)
9499 (setq link (concat "(" label ")") desc nil)))
9501 ;; We are in the agenda, link to referenced location
9502 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9503 (let ((m (or (get-text-property (point) 'org-hd-marker)
9504 (get-text-property (point) 'org-marker))))
9505 (when m
9506 (org-with-point-at m
9507 (setq agenda-link
9508 (if (org-called-interactively-p 'any)
9509 (call-interactively 'org-store-link)
9510 (org-store-link nil)))))))
9512 ((eq major-mode 'calendar-mode)
9513 (let ((cd (calendar-cursor-to-date)))
9514 (setq link
9515 (format-time-string
9516 (car org-time-stamp-formats)
9517 (apply 'encode-time
9518 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9519 nil nil nil))))
9520 (org-store-link-props :type "calendar" :date cd)))
9522 ((eq major-mode 'help-mode)
9523 (setq link (concat "help:" (save-excursion
9524 (goto-char (point-min))
9525 (looking-at "^[^ ]+")
9526 (match-string 0))))
9527 (org-store-link-props :type "help"))
9529 ((eq major-mode 'w3-mode)
9530 (setq cpltxt (if (and (buffer-name)
9531 (not (string-match "Untitled" (buffer-name))))
9532 (buffer-name)
9533 (url-view-url t))
9534 link (url-view-url t))
9535 (org-store-link-props :type "w3" :url (url-view-url t)))
9537 ((eq major-mode 'image-mode)
9538 (setq cpltxt (concat "file:"
9539 (abbreviate-file-name buffer-file-name))
9540 link cpltxt)
9541 (org-store-link-props :type "image" :file buffer-file-name))
9543 ;; In dired, store a link to the file of the current line
9544 ((eq major-mode 'dired-mode)
9545 (let ((file (dired-get-filename nil t)))
9546 (setq file (if file
9547 (abbreviate-file-name
9548 (expand-file-name (dired-get-filename nil t)))
9549 ;; otherwise, no file so use current directory.
9550 default-directory))
9551 (setq cpltxt (concat "file:" file)
9552 link cpltxt)))
9554 ((setq search (run-hook-with-args-until-success
9555 'org-create-file-search-functions))
9556 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9557 "::" search))
9558 (setq cpltxt (or description link)))
9560 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9561 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9562 (cond
9563 ;; Store a link using the target at point
9564 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9565 (setq cpltxt
9566 (concat "file:"
9567 (abbreviate-file-name
9568 (buffer-file-name (buffer-base-buffer)))
9569 "::" (match-string 1))
9570 link cpltxt))
9571 ((and (featurep 'org-id)
9572 (or (eq org-id-link-to-org-use-id t)
9573 (and (org-called-interactively-p 'any)
9574 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9575 (and (eq org-id-link-to-org-use-id
9576 'create-if-interactive-and-no-custom-id)
9577 (not custom-id))))
9578 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9579 ;; Store a link using the ID at point
9580 (setq link (condition-case nil
9581 (prog1 (org-id-store-link)
9582 (setq desc (or (plist-get org-store-link-plist
9583 :description)
9584 "")))
9585 (error
9586 ;; Probably before first headline, link only to file
9587 (concat "file:"
9588 (abbreviate-file-name
9589 (buffer-file-name (buffer-base-buffer))))))))
9591 ;; Just link to current headline
9592 (setq cpltxt (concat "file:"
9593 (abbreviate-file-name
9594 (buffer-file-name (buffer-base-buffer)))))
9595 ;; Add a context search string
9596 (when (org-xor org-context-in-file-links arg)
9597 (let* ((ee (org-element-at-point))
9598 (et (org-element-type ee))
9599 (ev (plist-get (cadr ee) :value))
9600 (ek (plist-get (cadr ee) :key))
9601 (eok (and (stringp ek) (string-match "name" ek))))
9602 (setq txt (cond
9603 ((org-at-heading-p) nil)
9604 ((and (eq et 'keyword) eok) ev)
9605 ((org-region-active-p)
9606 (buffer-substring (region-beginning) (region-end)))))
9607 (when (or (null txt) (string-match "\\S-" txt))
9608 (setq cpltxt
9609 (concat cpltxt "::"
9610 (condition-case nil
9611 (org-make-org-heading-search-string txt)
9612 (error "")))
9613 desc (or (and (eq et 'keyword) eok ev)
9614 (nth 4 (ignore-errors (org-heading-components)))
9615 "NONE")))))
9616 (if (string-match "::\\'" cpltxt)
9617 (setq cpltxt (substring cpltxt 0 -2)))
9618 (setq link cpltxt))))
9620 ((buffer-file-name (buffer-base-buffer))
9621 ;; Just link to this file here.
9622 (setq cpltxt (concat "file:"
9623 (abbreviate-file-name
9624 (buffer-file-name (buffer-base-buffer)))))
9625 ;; Add a context string.
9626 (when (org-xor org-context-in-file-links arg)
9627 (setq txt (if (org-region-active-p)
9628 (buffer-substring (region-beginning) (region-end))
9629 (buffer-substring (point-at-bol) (point-at-eol))))
9630 ;; Only use search option if there is some text.
9631 (when (string-match "\\S-" txt)
9632 (setq cpltxt
9633 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9634 desc "NONE")))
9635 (setq link cpltxt))
9637 ((org-called-interactively-p 'interactive)
9638 (user-error "No method for storing a link from this buffer"))
9640 (t (setq link nil)))
9642 ;; We're done setting link and desc, clean up
9643 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9644 (setq link (or link cpltxt)
9645 desc (or desc cpltxt))
9646 (cond ((equal desc "NONE") (setq desc nil))
9647 ((and desc (string-match org-bracket-link-analytic-regexp desc))
9648 (let ((d0 (match-string 3 desc))
9649 (p0 (match-string 5 desc)))
9650 (setq desc
9651 (replace-regexp-in-string
9652 org-bracket-link-regexp
9653 (concat (or p0 d0)
9654 (if (equal (length (match-string 0 desc))
9655 (length desc)) "*" "")) desc)))))
9657 ;; Return the link
9658 (if (not (and (or (org-called-interactively-p 'any)
9659 executing-kbd-macro) link))
9660 (or agenda-link (and link (org-make-link-string link desc)))
9661 (push (list link desc) org-stored-links)
9662 (message "Stored: %s" (or desc link))
9663 (when custom-id
9664 (setq link (concat "file:" (abbreviate-file-name
9665 (buffer-file-name)) "::#" custom-id))
9666 (push (list link desc) org-stored-links))
9667 (car org-stored-links))))))
9669 (defun org-store-link-props (&rest plist)
9670 "Store link properties, extract names and addresses."
9671 (let (x adr)
9672 (when (setq x (plist-get plist :from))
9673 (setq adr (mail-extract-address-components x))
9674 (setq plist (plist-put plist :fromname (car adr)))
9675 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9676 (when (setq x (plist-get plist :to))
9677 (setq adr (mail-extract-address-components x))
9678 (setq plist (plist-put plist :toname (car adr)))
9679 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9680 (let ((from (plist-get plist :from))
9681 (to (plist-get plist :to)))
9682 (when (and from to org-from-is-user-regexp)
9683 (setq plist
9684 (plist-put plist :fromto
9685 (if (string-match org-from-is-user-regexp from)
9686 (concat "to %t")
9687 (concat "from %f"))))))
9688 (setq org-store-link-plist plist))
9690 (defun org-add-link-props (&rest plist)
9691 "Add these properties to the link property list."
9692 (let (key value)
9693 (while plist
9694 (setq key (pop plist) value (pop plist))
9695 (setq org-store-link-plist
9696 (plist-put org-store-link-plist key value)))))
9698 (defun org-email-link-description (&optional fmt)
9699 "Return the description part of an email link.
9700 This takes information from `org-store-link-plist' and formats it
9701 according to FMT (default from `org-email-link-description-format')."
9702 (setq fmt (or fmt org-email-link-description-format))
9703 (let* ((p org-store-link-plist)
9704 (to (plist-get p :toaddress))
9705 (from (plist-get p :fromaddress))
9706 (table
9707 (list
9708 (cons "%c" (plist-get p :fromto))
9709 (cons "%F" (plist-get p :from))
9710 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9711 (cons "%T" (plist-get p :to))
9712 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9713 (cons "%s" (plist-get p :subject))
9714 (cons "%d" (plist-get p :date))
9715 (cons "%m" (plist-get p :message-id)))))
9716 (when (string-match "%c" fmt)
9717 ;; Check if the user wrote this message
9718 (if (and org-from-is-user-regexp from to
9719 (save-match-data (string-match org-from-is-user-regexp from)))
9720 (setq fmt (replace-match "to %t" t t fmt))
9721 (setq fmt (replace-match "from %f" t t fmt))))
9722 (org-replace-escapes fmt table)))
9724 (defun org-make-org-heading-search-string (&optional string)
9725 "Make search string for the current headline or STRING."
9726 (let ((s (or string
9727 (and (derived-mode-p 'org-mode)
9728 (save-excursion
9729 (org-back-to-heading t)
9730 (org-element-property :raw-value (org-element-at-point))))))
9731 (lines org-context-in-file-links))
9732 (or string (setq s (concat "*" s))) ; Add * for headlines
9733 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9734 (when (and string (integerp lines) (> lines 0))
9735 (let ((slines (org-split-string s "\n")))
9736 (when (< lines (length slines))
9737 (setq s (mapconcat
9738 'identity
9739 (reverse (nthcdr (- (length slines) lines)
9740 (reverse slines))) "\n")))))
9741 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9743 (defun org-make-link-string (link &optional description)
9744 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9745 (unless (string-match "\\S-" link)
9746 (error "Empty link"))
9747 (when (and description
9748 (stringp description)
9749 (not (string-match "\\S-" description)))
9750 (setq description nil))
9751 (when (stringp description)
9752 ;; Remove brackets from the description, they are fatal.
9753 (while (string-match "\\[" description)
9754 (setq description (replace-match "{" t t description)))
9755 (while (string-match "\\]" description)
9756 (setq description (replace-match "}" t t description))))
9757 (when (equal link description)
9758 ;; No description needed, it is identical
9759 (setq description nil))
9760 (when (and (not description)
9761 (not (string-match (org-image-file-name-regexp) link))
9762 (not (equal link (org-link-escape link))))
9763 (setq description (org-extract-attributes link)))
9764 (setq link
9765 (cond ((string-match (org-image-file-name-regexp) link) link)
9766 ((string-match org-link-types-re link)
9767 (concat (match-string 1 link)
9768 (org-link-escape (substring link (match-end 1)))))
9769 (t (org-link-escape link))))
9770 (concat "[[" link "]"
9771 (if description (concat "[" description "]") "")
9772 "]"))
9774 (defconst org-link-escape-chars
9775 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9776 "List of characters that should be escaped in link.
9777 This is the list that is used for internal purposes.")
9779 (defconst org-link-escape-chars-browser
9780 '(?\ ?\")
9781 "List of escapes for characters that are problematic in links.
9782 This is the list that is used before handing over to the browser.")
9784 (defun org-link-escape (text &optional table merge)
9785 "Return percent escaped representation of TEXT.
9786 TEXT is a string with the text to escape.
9787 Optional argument TABLE is a list with characters that should be
9788 escaped. When nil, `org-link-escape-chars' is used.
9789 If optional argument MERGE is set, merge TABLE into
9790 `org-link-escape-chars'."
9791 (cond
9792 ((and table merge)
9793 (mapc (lambda (defchr)
9794 (unless (member defchr table)
9795 (setq table (cons defchr table)))) org-link-escape-chars))
9796 ((null table)
9797 (setq table org-link-escape-chars)))
9798 (mapconcat
9799 (lambda (char)
9800 (if (or (member char table)
9801 (and (or (< char 32) (= char 37) (> char 126))
9802 org-url-hexify-p))
9803 (mapconcat (lambda (sequence-element)
9804 (format "%%%.2X" sequence-element))
9805 (or (encode-coding-char char 'utf-8)
9806 (error "Unable to percent escape character: %s"
9807 (char-to-string char))) "")
9808 (char-to-string char))) text ""))
9810 (defun org-link-unescape (str)
9811 "Unhex hexified Unicode strings as returned from the JavaScript function
9812 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9813 (unless (and (null str) (string= "" str))
9814 (let ((pos 0) (case-fold-search t) unhexed)
9815 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9816 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9817 (setq str (replace-match unhexed t t str))
9818 (setq pos (+ pos (length unhexed))))))
9819 str)
9821 (defun org-link-unescape-compound (hex)
9822 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9823 Note: this function also decodes single byte encodings like
9824 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9825 (save-match-data
9826 (let* ((bytes (cdr (split-string hex "%")))
9827 (ret "")
9828 (eat 0)
9829 (sum 0))
9830 (while bytes
9831 (let* ((val (string-to-number (pop bytes) 16))
9832 (shift-xor
9833 (if (= 0 eat)
9834 (cond
9835 ((>= val 252) (cons 6 252))
9836 ((>= val 248) (cons 5 248))
9837 ((>= val 240) (cons 4 240))
9838 ((>= val 224) (cons 3 224))
9839 ((>= val 192) (cons 2 192))
9840 (t (cons 0 0)))
9841 (cons 6 128))))
9842 (if (>= val 192) (setq eat (car shift-xor)))
9843 (setq val (logxor val (cdr shift-xor)))
9844 (setq sum (+ (lsh sum (car shift-xor)) val))
9845 (if (> eat 0) (setq eat (- eat 1)))
9846 (cond
9847 ((= 0 eat) ;multi byte
9848 (setq ret (concat ret (org-char-to-string sum)))
9849 (setq sum 0))
9850 ((not bytes) ; single byte(s)
9851 (setq ret (org-link-unescape-single-byte-sequence hex))))
9852 )) ;; end (while bytes
9853 ret )))
9855 (defun org-link-unescape-single-byte-sequence (hex)
9856 "Unhexify hex-encoded single byte character sequences."
9857 (mapconcat (lambda (byte)
9858 (char-to-string (string-to-number byte 16)))
9859 (cdr (split-string hex "%")) ""))
9861 (defun org-xor (a b)
9862 "Exclusive or."
9863 (if a (not b) b))
9865 (defun org-fixup-message-id-for-http (s)
9866 "Replace special characters in a message id, so it can be used in an http query."
9867 (when (string-match "%" s)
9868 (setq s (mapconcat (lambda (c)
9869 (if (eq c ?%)
9870 "%25"
9871 (char-to-string c)))
9872 s "")))
9873 (while (string-match "<" s)
9874 (setq s (replace-match "%3C" t t s)))
9875 (while (string-match ">" s)
9876 (setq s (replace-match "%3E" t t s)))
9877 (while (string-match "@" s)
9878 (setq s (replace-match "%40" t t s)))
9881 (defun org-link-prettify (link)
9882 "Return a human-readable representation of LINK.
9883 The car of LINK must be a raw link the cdr of LINK must be either
9884 a link description or nil."
9885 (let ((desc (or (cadr link) "<no description>")))
9886 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9887 "<" (car link) ">")))
9889 ;;;###autoload
9890 (defun org-insert-link-global ()
9891 "Insert a link like Org-mode does.
9892 This command can be called in any mode to insert a link in Org-mode syntax."
9893 (interactive)
9894 (org-load-modules-maybe)
9895 (org-run-like-in-org-mode 'org-insert-link))
9897 (defun org-insert-all-links (&optional keep)
9898 "Insert all links in `org-stored-links'."
9899 (interactive "P")
9900 (let ((links (copy-sequence org-stored-links)) l)
9901 (while (setq l (if keep (pop links) (pop org-stored-links)))
9902 (insert "- ")
9903 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9904 (insert "\n"))))
9906 (defun org-link-fontify-links-to-this-file ()
9907 "Fontify links to the current file in `org-stored-links'."
9908 (let ((f (buffer-file-name)) a b)
9909 (setq a (mapcar (lambda(l)
9910 (let ((ll (car l)))
9911 (when (and (string-match "^file:\\(.+\\)::" ll)
9912 (equal f (expand-file-name (match-string 1 ll))))
9913 ll)))
9914 org-stored-links))
9915 (when (featurep 'org-id)
9916 (setq b (mapcar (lambda(l)
9917 (let ((ll (car l)))
9918 (when (and (string-match "^id:\\(.+\\)$" ll)
9919 (equal f (expand-file-name
9920 (or (org-id-find-id-file
9921 (match-string 1 ll)) ""))))
9922 ll)))
9923 org-stored-links)))
9924 (mapcar (lambda(l)
9925 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9926 (delq nil (append a b)))))
9928 (defvar org-link-links-in-this-file nil)
9929 (defun org-insert-link (&optional complete-file link-location default-description)
9930 "Insert a link. At the prompt, enter the link.
9932 Completion can be used to insert any of the link protocol prefixes like
9933 http or ftp in use.
9935 The history can be used to select a link previously stored with
9936 `org-store-link'. When the empty string is entered (i.e. if you just
9937 press RET at the prompt), the link defaults to the most recently
9938 stored link. As SPC triggers completion in the minibuffer, you need to
9939 use M-SPC or C-q SPC to force the insertion of a space character.
9941 You will also be prompted for a description, and if one is given, it will
9942 be displayed in the buffer instead of the link.
9944 If there is already a link at point, this command will allow you to edit link
9945 and description parts.
9947 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9948 be selected using completion. The path to the file will be relative to the
9949 current directory if the file is in the current directory or a subdirectory.
9950 Otherwise, the link will be the absolute path as completed in the minibuffer
9951 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9952 option `org-link-file-path-type'.
9954 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9955 the current directory or below.
9957 With three \\[universal-argument] prefixes, negate the meaning of
9958 `org-keep-stored-link-after-insertion'.
9960 If `org-make-link-description-function' is non-nil, this function will be
9961 called with the link target, and the result will be the default
9962 link description.
9964 If the LINK-LOCATION parameter is non-nil, this value will be
9965 used as the link location instead of reading one interactively.
9967 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9968 be used as the default description."
9969 (interactive "P")
9970 (let* ((wcf (current-window-configuration))
9971 (origbuf (current-buffer))
9972 (region (if (org-region-active-p)
9973 (buffer-substring (region-beginning) (region-end))))
9974 (remove (and region (list (region-beginning) (region-end))))
9975 (desc region)
9976 tmphist ; byte-compile incorrectly complains about this
9977 (link link-location)
9978 (abbrevs org-link-abbrev-alist-local)
9979 entry file all-prefixes auto-desc)
9980 (cond
9981 (link-location) ; specified by arg, just use it.
9982 ((org-in-regexp org-bracket-link-regexp 1)
9983 ;; We do have a link at point, and we are going to edit it.
9984 (setq remove (list (match-beginning 0) (match-end 0)))
9985 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9986 (setq link (read-string "Link: "
9987 (org-link-unescape
9988 (org-match-string-no-properties 1)))))
9989 ((or (org-in-regexp org-angle-link-re)
9990 (org-in-regexp org-plain-link-re))
9991 ;; Convert to bracket link
9992 (setq remove (list (match-beginning 0) (match-end 0))
9993 link (read-string "Link: "
9994 (org-remove-angle-brackets (match-string 0)))))
9995 ((member complete-file '((4) (16)))
9996 ;; Completing read for file names.
9997 (setq link (org-file-complete-link complete-file)))
9999 ;; Read link, with completion for stored links.
10000 (org-link-fontify-links-to-this-file)
10001 (org-switch-to-buffer-other-window "*Org Links*")
10002 (with-current-buffer "*Org Links*"
10003 (erase-buffer)
10004 (insert "Insert a link.
10005 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10006 (when org-stored-links
10007 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10008 (insert (mapconcat 'org-link-prettify
10009 (reverse org-stored-links) "\n")))
10010 (goto-char (point-min)))
10011 (let ((cw (selected-window)))
10012 (select-window (get-buffer-window "*Org Links*" 'visible))
10013 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10014 (unless (pos-visible-in-window-p (point-max))
10015 (org-fit-window-to-buffer))
10016 (and (window-live-p cw) (select-window cw)))
10017 ;; Fake a link history, containing the stored links.
10018 (setq tmphist (append (mapcar 'car org-stored-links)
10019 org-insert-link-history))
10020 (setq all-prefixes (append (mapcar 'car abbrevs)
10021 (mapcar 'car org-link-abbrev-alist)
10022 org-link-types))
10023 (unwind-protect
10024 (progn
10025 (setq link
10026 (org-completing-read
10027 "Link: "
10028 (append
10029 (mapcar (lambda (x) (concat x ":"))
10030 all-prefixes)
10031 (mapcar 'car org-stored-links))
10032 nil nil nil
10033 'tmphist
10034 (caar org-stored-links)))
10035 (if (not (string-match "\\S-" link))
10036 (user-error "No link selected"))
10037 (mapc (lambda(l)
10038 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
10039 org-stored-links)
10040 (if (or (member link all-prefixes)
10041 (and (equal ":" (substring link -1))
10042 (member (substring link 0 -1) all-prefixes)
10043 (setq link (substring link 0 -1))))
10044 (setq link (with-current-buffer origbuf
10045 (org-link-try-special-completion link)))))
10046 (set-window-configuration wcf)
10047 (kill-buffer "*Org Links*"))
10048 (setq entry (assoc link org-stored-links))
10049 (or entry (push link org-insert-link-history))
10050 (setq desc (or desc (nth 1 entry)))))
10052 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10053 (not org-keep-stored-link-after-insertion))
10054 (setq org-stored-links (delq (assoc link org-stored-links)
10055 org-stored-links)))
10057 (if (and (string-match org-plain-link-re link)
10058 (not (string-match org-ts-regexp link)))
10059 ;; URL-like link, normalize the use of angular brackets.
10060 (setq link (org-remove-angle-brackets link)))
10062 ;; Check if we are linking to the current file with a search
10063 ;; option If yes, simplify the link by using only the search
10064 ;; option.
10065 (when (and buffer-file-name
10066 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10067 (let* ((path (match-string 1 link))
10068 (case-fold-search nil)
10069 (search (match-string 2 link)))
10070 (save-match-data
10071 (if (equal (file-truename buffer-file-name) (file-truename path))
10072 ;; We are linking to this same file, with a search option
10073 (setq link search)))))
10075 ;; Check if we can/should use a relative path. If yes, simplify the link
10076 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10077 (let* ((type (match-string 1 link))
10078 (path (match-string 2 link))
10079 (origpath path)
10080 (case-fold-search nil))
10081 (cond
10082 ((or (eq org-link-file-path-type 'absolute)
10083 (equal complete-file '(16)))
10084 (setq path (abbreviate-file-name (expand-file-name path))))
10085 ((eq org-link-file-path-type 'noabbrev)
10086 (setq path (expand-file-name path)))
10087 ((eq org-link-file-path-type 'relative)
10088 (setq path (file-relative-name path)))
10090 (save-match-data
10091 (if (string-match (concat "^" (regexp-quote
10092 (expand-file-name
10093 (file-name-as-directory
10094 default-directory))))
10095 (expand-file-name path))
10096 ;; We are linking a file with relative path name.
10097 (setq path (substring (expand-file-name path)
10098 (match-end 0)))
10099 (setq path (abbreviate-file-name (expand-file-name path)))))))
10100 (setq link (concat type path))
10101 (if (equal desc origpath)
10102 (setq desc path))))
10104 (if org-make-link-description-function
10105 (setq desc
10106 (or (condition-case nil
10107 (funcall org-make-link-description-function link desc)
10108 (error (progn (message "Can't get link description from `%s'"
10109 (symbol-name org-make-link-description-function))
10110 (sit-for 2) nil)))
10111 (read-string "Description: " default-description)))
10112 (if default-description (setq desc default-description)
10113 (setq desc (or (and auto-desc desc)
10114 (read-string "Description: " desc)))))
10116 (unless (string-match "\\S-" desc) (setq desc nil))
10117 (if remove (apply 'delete-region remove))
10118 (insert (org-make-link-string link desc))))
10120 (defun org-link-try-special-completion (type)
10121 "If there is completion support for link type TYPE, offer it."
10122 (let ((fun (intern (concat "org-" type "-complete-link"))))
10123 (if (functionp fun)
10124 (funcall fun)
10125 (read-string "Link (no completion support): " (concat type ":")))))
10127 (defun org-file-complete-link (&optional arg)
10128 "Create a file link using completion."
10129 (let (file link)
10130 (setq file (org-iread-file-name "File: "))
10131 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10132 (pwd1 (file-name-as-directory (abbreviate-file-name
10133 (expand-file-name ".")))))
10134 (cond
10135 ((equal arg '(16))
10136 (setq link (concat
10137 "file:"
10138 (abbreviate-file-name (expand-file-name file)))))
10139 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10140 (setq link (concat "file:" (match-string 1 file))))
10141 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10142 (expand-file-name file))
10143 (setq link (concat
10144 "file:" (match-string 1 (expand-file-name file)))))
10145 (t (setq link (concat "file:" file)))))
10146 link))
10148 (defun org-iread-file-name (&rest args)
10149 "Read-file-name using `ido-mode' speedup if available.
10150 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10151 See `read-file-name' for a description of parameters."
10152 (org-without-partial-completion
10153 (if (and org-completion-use-ido
10154 (fboundp 'ido-read-file-name)
10155 (boundp 'ido-mode) ido-mode
10156 (listp (second args)))
10157 (let ((ido-enter-matching-directory nil))
10158 (apply 'ido-read-file-name args))
10159 (apply 'read-file-name args))))
10161 (defun org-completing-read (&rest args)
10162 "Completing-read with SPACE being a normal character."
10163 (let ((enable-recursive-minibuffers t)
10164 (minibuffer-local-completion-map
10165 (copy-keymap minibuffer-local-completion-map)))
10166 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10167 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10168 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10169 (apply 'org-icompleting-read args)))
10171 (defun org-completing-read-no-i (&rest args)
10172 (let (org-completion-use-ido org-completion-use-iswitchb)
10173 (apply 'org-completing-read args)))
10175 (defun org-iswitchb-completing-read (prompt choices &rest args)
10176 "Use iswitch as a completing-read replacement to choose from choices.
10177 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10178 from."
10179 (let* ((iswitchb-use-virtual-buffers nil)
10180 (iswitchb-make-buflist-hook
10181 (lambda ()
10182 (setq iswitchb-temp-buflist choices))))
10183 (iswitchb-read-buffer prompt)))
10185 (defun org-icompleting-read (&rest args)
10186 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10187 (org-without-partial-completion
10188 (if (and org-completion-use-ido
10189 (fboundp 'ido-completing-read)
10190 (boundp 'ido-mode) ido-mode
10191 (listp (second args)))
10192 (let ((ido-enter-matching-directory nil))
10193 (apply 'ido-completing-read (concat (car args))
10194 (if (consp (car (nth 1 args)))
10195 (mapcar 'car (nth 1 args))
10196 (nth 1 args))
10197 (cddr args)))
10198 (if (and org-completion-use-iswitchb
10199 (boundp 'iswitchb-mode) iswitchb-mode
10200 (listp (second args)))
10201 (apply 'org-iswitchb-completing-read (concat (car args))
10202 (if (consp (car (nth 1 args)))
10203 (mapcar 'car (nth 1 args))
10204 (nth 1 args))
10205 (cddr args))
10206 (apply 'completing-read args)))))
10208 (defun org-extract-attributes (s)
10209 "Extract the attributes cookie from a string and set as text property."
10210 (let (a attr (start 0) key value)
10211 (save-match-data
10212 (when (string-match "{{\\([^}]+\\)}}$" s)
10213 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10214 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10215 (setq key (match-string 1 a) value (match-string 2 a)
10216 start (match-end 0)
10217 attr (plist-put attr (intern key) value))))
10218 (org-add-props s nil 'org-attr attr))
10221 ;;; Opening/following a link
10223 (defvar org-link-search-failed nil)
10225 (defvar org-open-link-functions nil
10226 "Hook for functions finding a plain text link.
10227 These functions must take a single argument, the link content.
10228 They will be called for links that look like [[link text][description]]
10229 when LINK TEXT does not have a protocol like \"http:\" and does not look
10230 like a filename (e.g. \"./blue.png\").
10232 These functions will be called *before* Org attempts to resolve the
10233 link by doing text searches in the current buffer - so if you want a
10234 link \"[[target]]\" to still find \"<<target>>\", your function should
10235 handle this as a special case.
10237 When the function does handle the link, it must return a non-nil value.
10238 If it decides that it is not responsible for this link, it must return
10239 nil to indicate that that Org-mode can continue with other options
10240 like exact and fuzzy text search.")
10242 (defun org-next-link (&optional search-backward)
10243 "Move forward to the next link.
10244 If the link is in hidden text, expose it."
10245 (interactive "P")
10246 (when (and org-link-search-failed (eq this-command last-command))
10247 (goto-char (point-min))
10248 (message "Link search wrapped back to beginning of buffer"))
10249 (setq org-link-search-failed nil)
10250 (let* ((pos (point))
10251 (ct (org-context))
10252 (a (assoc :link ct))
10253 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10254 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10255 ((looking-at org-any-link-re)
10256 ;; Don't stay stuck at link without an org-link face
10257 (forward-char (if search-backward -1 1))))
10258 (if (funcall srch-fun org-any-link-re nil t)
10259 (progn
10260 (goto-char (match-beginning 0))
10261 (if (outline-invisible-p) (org-show-context)))
10262 (goto-char pos)
10263 (setq org-link-search-failed t)
10264 (message "No further link found"))))
10266 (defun org-previous-link ()
10267 "Move backward to the previous link.
10268 If the link is in hidden text, expose it."
10269 (interactive)
10270 (funcall 'org-next-link t))
10272 (defun org-translate-link (s)
10273 "Translate a link string if a translation function has been defined."
10274 (if (and org-link-translation-function
10275 (fboundp org-link-translation-function)
10276 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10277 (progn
10278 (setq s (funcall org-link-translation-function
10279 (match-string 1 s) (match-string 2 s)))
10280 (concat (car s) ":" (cdr s)))
10283 (defun org-translate-link-from-planner (type path)
10284 "Translate a link from Emacs Planner syntax so that Org can follow it.
10285 This is still an experimental function, your mileage may vary."
10286 (cond
10287 ((member type '("http" "https" "news" "ftp"))
10288 ;; standard Internet links are the same.
10289 nil)
10290 ((and (equal type "irc") (string-match "^//" path))
10291 ;; Planner has two / at the beginning of an irc link, we have 1.
10292 ;; We should have zero, actually....
10293 (setq path (substring path 1)))
10294 ((and (equal type "lisp") (string-match "^/" path))
10295 ;; Planner has a slash, we do not.
10296 (setq type "elisp" path (substring path 1)))
10297 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10298 ;; A typical message link. Planner has the id after the final slash,
10299 ;; we separate it with a hash mark
10300 (setq path (concat (match-string 1 path) "#"
10301 (org-remove-angle-brackets (match-string 2 path))))))
10302 (cons type path))
10304 (defun org-find-file-at-mouse (ev)
10305 "Open file link or URL at mouse."
10306 (interactive "e")
10307 (mouse-set-point ev)
10308 (org-open-at-point 'in-emacs))
10310 (defun org-open-at-mouse (ev)
10311 "Open file link or URL at mouse.
10312 See the docstring of `org-open-file' for details."
10313 (interactive "e")
10314 (mouse-set-point ev)
10315 (if (eq major-mode 'org-agenda-mode)
10316 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10317 (org-open-at-point))
10319 (defvar org-window-config-before-follow-link nil
10320 "The window configuration before following a link.
10321 This is saved in case the need arises to restore it.")
10323 (defvar org-open-link-marker (make-marker)
10324 "Marker pointing to the location where `org-open-at-point' was called.")
10326 ;;;###autoload
10327 (defun org-open-at-point-global ()
10328 "Follow a link like Org-mode does.
10329 This command can be called in any mode to follow a link that has
10330 Org-mode syntax."
10331 (interactive)
10332 (org-run-like-in-org-mode 'org-open-at-point))
10334 ;;;###autoload
10335 (defun org-open-link-from-string (s &optional arg reference-buffer)
10336 "Open a link in the string S, as if it was in Org-mode."
10337 (interactive "sLink: \nP")
10338 (let ((reference-buffer (or reference-buffer (current-buffer))))
10339 (with-temp-buffer
10340 (let ((org-inhibit-startup (not reference-buffer)))
10341 (org-mode)
10342 (insert s)
10343 (goto-char (point-min))
10344 (when reference-buffer
10345 (setq org-link-abbrev-alist-local
10346 (with-current-buffer reference-buffer
10347 org-link-abbrev-alist-local)))
10348 (org-open-at-point arg reference-buffer)))))
10350 (defvar org-open-at-point-functions nil
10351 "Hook that is run when following a link at point.
10353 Functions in this hook must return t if they identify and follow
10354 a link at point. If they don't find anything interesting at point,
10355 they must return nil.")
10357 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10358 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10359 (defun org-open-at-point (&optional arg reference-buffer)
10360 "Open link at or after point.
10361 If there is no link at point, this function will search forward up to
10362 the end of the current line.
10363 Normally, files will be opened by an appropriate application. If the
10364 optional prefix argument ARG is non-nil, Emacs will visit the file.
10365 With a double prefix argument, try to open outside of Emacs, in the
10366 application the system uses for this file type."
10367 (interactive "P")
10368 ;; if in a code block, then open the block's results
10369 (unless (call-interactively #'org-babel-open-src-block-result)
10370 (org-load-modules-maybe)
10371 (move-marker org-open-link-marker (point))
10372 (setq org-window-config-before-follow-link (current-window-configuration))
10373 (org-remove-occur-highlights nil nil t)
10374 (cond
10375 ((and (org-at-heading-p)
10376 (not (org-at-timestamp-p t))
10377 (not (org-in-regexp
10378 (concat org-plain-link-re "\\|"
10379 org-bracket-link-regexp "\\|"
10380 org-angle-link-re "\\|"
10381 "[ \t]:[^ \t\n]+:[ \t]*$")))
10382 (not (get-text-property (point) 'org-linked-text)))
10383 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10384 (lk0 (car lkall))
10385 (lk (if (stringp lk0) (list lk0) lk0))
10386 (lkend (cdr lkall)))
10387 (mapcar (lambda(l)
10388 (search-forward l nil lkend)
10389 (goto-char (match-beginning 0))
10390 (org-open-at-point))
10391 lk))
10392 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10393 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10394 ((and (org-at-timestamp-p t)
10395 (not (org-in-regexp org-bracket-link-regexp)))
10396 (org-follow-timestamp-link))
10397 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10398 (not (org-in-regexp org-any-link-re)))
10399 (org-footnote-action))
10401 (let (type path link line search (pos (point)))
10402 (catch 'match
10403 (save-excursion
10404 (or (org-in-regexp org-plain-link-re)
10405 (skip-chars-forward "^]\n\r"))
10406 (when (org-in-regexp org-bracket-link-regexp 1)
10407 (setq link (org-extract-attributes
10408 (org-link-unescape (org-match-string-no-properties 1))))
10409 (while (string-match " *\n *" link)
10410 (setq link (replace-match " " t t link)))
10411 (setq link (org-link-expand-abbrev link))
10412 (cond
10413 ((or (file-name-absolute-p link)
10414 (string-match "^\\.\\.?/" link))
10415 (setq type "file" path link))
10416 ((string-match org-link-re-with-space3 link)
10417 (setq type (match-string 1 link) path (match-string 2 link)))
10418 ((string-match "^help:+\\(.+\\)" link)
10419 (setq type "help" path (match-string 1 link)))
10420 (t (setq type "thisfile" path link)))
10421 (throw 'match t)))
10423 (when (get-text-property (point) 'org-linked-text)
10424 (setq type "thisfile"
10425 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10426 (1+ (point)) (point))
10427 path (buffer-substring
10428 (or (previous-single-property-change pos 'org-linked-text)
10429 (point-min))
10430 (or (next-single-property-change pos 'org-linked-text)
10431 (point-max)))
10432 ;; Ensure we will search for a <<<radio>>> link, not
10433 ;; a simple reference like <<ref>>
10434 path (concat "<" path))
10435 (throw 'match t))
10437 (save-excursion
10438 (when (or (org-in-regexp org-angle-link-re)
10439 (let ((match (org-in-regexp org-plain-link-re)))
10440 ;; Check a plain link is not within a bracket link
10441 (and match
10442 (save-excursion
10443 (save-match-data
10444 (progn
10445 (goto-char (car match))
10446 (not (org-in-regexp org-bracket-link-regexp)))))))
10447 (let ((line_ending (save-excursion (end-of-line) (point))))
10448 ;; We are in a line before a plain or bracket link
10449 (or (re-search-forward org-plain-link-re line_ending t)
10450 (re-search-forward org-bracket-link-regexp line_ending t))))
10451 (setq type (match-string 1)
10452 path (org-link-unescape (match-string 2)))
10453 (throw 'match t)))
10454 (save-excursion
10455 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10456 (setq type "tags"
10457 path (match-string 1))
10458 (while (string-match ":" path)
10459 (setq path (replace-match "+" t t path)))
10460 (throw 'match t)))
10461 (when (org-in-regexp "<\\([^><\n]+\\)>")
10462 (setq type "tree-match"
10463 path (match-string 1))
10464 (throw 'match t)))
10465 (unless path
10466 (user-error "No link found"))
10468 ;; switch back to reference buffer
10469 ;; needed when if called in a temporary buffer through
10470 ;; org-open-link-from-string
10471 (with-current-buffer (or reference-buffer (current-buffer))
10473 ;; Remove any trailing spaces in path
10474 (if (string-match " +\\'" path)
10475 (setq path (replace-match "" t t path)))
10476 (if (and org-link-translation-function
10477 (fboundp org-link-translation-function))
10478 ;; Check if we need to translate the link
10479 (let ((tmp (funcall org-link-translation-function type path)))
10480 (setq type (car tmp) path (cdr tmp))))
10482 (cond
10484 ((assoc type org-link-protocols)
10485 (funcall (nth 1 (assoc type org-link-protocols)) path))
10487 ((equal type "help")
10488 (let ((f-or-v (intern path)))
10489 (cond ((fboundp f-or-v)
10490 (describe-function f-or-v))
10491 ((boundp f-or-v)
10492 (describe-variable f-or-v))
10493 (t (error "Not a known function or variable")))))
10495 ((equal type "mailto")
10496 (let ((cmd (car org-link-mailto-program))
10497 (args (cdr org-link-mailto-program)) args1
10498 (address path) (subject "") a)
10499 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10500 (setq address (match-string 1 path)
10501 subject (org-link-escape (match-string 2 path))))
10502 (while args
10503 (cond
10504 ((not (stringp (car args))) (push (pop args) args1))
10505 (t (setq a (pop args))
10506 (if (string-match "%a" a)
10507 (setq a (replace-match address t t a)))
10508 (if (string-match "%s" a)
10509 (setq a (replace-match subject t t a)))
10510 (push a args1))))
10511 (apply cmd (nreverse args1))))
10513 ((member type '("http" "https" "ftp" "news"))
10514 (browse-url
10515 (concat type ":"
10516 (if (org-string-match-p
10517 (concat "[[:nonascii:]"
10518 org-link-escape-chars-browser "]")
10519 path)
10520 (org-link-escape path org-link-escape-chars-browser)
10521 path))))
10523 ((string= type "doi")
10524 (browse-url
10525 (concat org-doi-server-url
10526 (if (org-string-match-p
10527 (concat "[[:nonascii:]"
10528 org-link-escape-chars-browser "]")
10529 path)
10530 (org-link-escape path org-link-escape-chars-browser)
10531 path))))
10533 ((member type '("message"))
10534 (browse-url (concat type ":" path)))
10536 ((string= type "tags")
10537 (org-tags-view arg path))
10539 ((string= type "tree-match")
10540 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10542 ((string= type "file")
10543 (if (string-match "::\\([0-9]+\\)\\'" path)
10544 (setq line (string-to-number (match-string 1 path))
10545 path (substring path 0 (match-beginning 0)))
10546 (if (string-match "::\\(.+\\)\\'" path)
10547 (setq search (match-string 1 path)
10548 path (substring path 0 (match-beginning 0)))))
10549 (if (string-match "[*?{]" (file-name-nondirectory path))
10550 (dired path)
10551 (org-open-file path arg line search)))
10553 ((string= type "shell")
10554 (let ((buf (generate-new-buffer "*Org Shell Output"))
10555 (cmd path))
10556 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10557 (string-match org-confirm-shell-link-not-regexp cmd))
10558 (not org-confirm-shell-link-function)
10559 (funcall org-confirm-shell-link-function
10560 (format "Execute \"%s\" in shell? "
10561 (org-add-props cmd nil
10562 'face 'org-warning))))
10563 (progn
10564 (message "Executing %s" cmd)
10565 (shell-command cmd buf)
10566 (if (featurep 'midnight)
10567 (setq clean-buffer-list-kill-buffer-names
10568 (cons buf clean-buffer-list-kill-buffer-names))))
10569 (error "Abort"))))
10571 ((string= type "elisp")
10572 (let ((cmd path))
10573 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10574 (string-match org-confirm-elisp-link-not-regexp cmd))
10575 (not org-confirm-elisp-link-function)
10576 (funcall org-confirm-elisp-link-function
10577 (format "Execute \"%s\" as elisp? "
10578 (org-add-props cmd nil
10579 'face 'org-warning))))
10580 (message "%s => %s" cmd
10581 (if (equal (string-to-char cmd) ?\()
10582 (eval (read cmd))
10583 (call-interactively (read cmd))))
10584 (error "Abort"))))
10586 ((and (string= type "thisfile")
10587 (or (run-hook-with-args-until-success
10588 'org-open-link-functions path)
10589 (and link
10590 (string-match "^id:" link)
10591 (or (featurep 'org-id) (require 'org-id))
10592 (progn
10593 (funcall (nth 1 (assoc "id" org-link-protocols))
10594 (substring path 3))
10595 t)))))
10597 ((string= type "thisfile")
10598 (if arg
10599 (switch-to-buffer-other-window
10600 (org-get-buffer-for-internal-link (current-buffer)))
10601 (org-mark-ring-push))
10602 (let ((cmd `(org-link-search
10603 ,path
10604 ,(cond ((equal arg '(4)) ''occur)
10605 ((equal arg '(16)) ''org-occur))
10606 ,pos)))
10607 (condition-case nil (let ((org-link-search-inhibit-query t))
10608 (eval cmd))
10609 (error (progn (widen) (eval cmd))))))
10611 (t (browse-url-at-point)))))))
10612 (move-marker org-open-link-marker nil)
10613 (run-hook-with-args 'org-follow-link-hook)))
10615 (defsubst org-uniquify (list)
10616 "Non-destructively remove duplicate elements from LIST."
10617 (let ((res (copy-sequence list))) (delete-dups res)))
10619 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10620 "Offer links in the current entry and return the selected link.
10621 If there is only one link, return it.
10622 If NTH is an integer, return the NTH link found.
10623 If ZERO is a string, check also this string for a link, and if
10624 there is one, return it."
10625 (with-current-buffer buffer
10626 (save-excursion
10627 (save-restriction
10628 (widen)
10629 (goto-char marker)
10630 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10631 "\\(" org-angle-link-re "\\)\\|"
10632 "\\(" org-plain-link-re "\\)"))
10633 (cnt ?0)
10634 (in-emacs (if (integerp nth) nil nth))
10635 have-zero end links link c)
10636 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10637 (push (match-string 0 zero) links)
10638 (setq cnt (1- cnt) have-zero t))
10639 (save-excursion
10640 (org-back-to-heading t)
10641 (setq end (save-excursion (outline-next-heading) (point)))
10642 (while (re-search-forward re end t)
10643 (push (match-string 0) links))
10644 (setq links (org-uniquify (reverse links))))
10645 (cond
10646 ((null links)
10647 (message "No links"))
10648 ((equal (length links) 1)
10649 (setq link (car links)))
10650 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10651 (setq link (nth (if have-zero nth (1- nth)) links)))
10652 (t ; we have to select a link
10653 (save-excursion
10654 (save-window-excursion
10655 (delete-other-windows)
10656 (with-output-to-temp-buffer "*Select Link*"
10657 (mapc (lambda (l)
10658 (if (not (string-match org-bracket-link-regexp l))
10659 (princ (format "[%c] %s\n" (incf cnt)
10660 (org-remove-angle-brackets l)))
10661 (if (match-end 3)
10662 (princ (format "[%c] %s (%s)\n" (incf cnt)
10663 (match-string 3 l) (match-string 1 l)))
10664 (princ (format "[%c] %s\n" (incf cnt)
10665 (match-string 1 l))))))
10666 links))
10667 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10668 (message "Select link to open, RET to open all:")
10669 (setq c (read-char-exclusive))
10670 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10671 (when (equal c ?q) (error "Abort"))
10672 (if (equal c ?\C-m)
10673 (setq link links)
10674 (setq nth (- c ?0))
10675 (if have-zero (setq nth (1+ nth)))
10676 (unless (and (integerp nth) (>= (length links) nth))
10677 (user-error "Invalid link selection"))
10678 (setq link (nth (1- nth) links)))))
10679 (cons link end))))))
10681 ;; Add special file links that specify the way of opening
10683 (org-add-link-type "file+sys" 'org-open-file-with-system)
10684 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10685 (defun org-open-file-with-system (path)
10686 "Open file at PATH using the system way of opening it."
10687 (org-open-file path 'system))
10688 (defun org-open-file-with-emacs (path)
10689 "Open file at PATH in Emacs."
10690 (org-open-file path 'emacs))
10693 ;;; File search
10695 (defvar org-create-file-search-functions nil
10696 "List of functions to construct the right search string for a file link.
10697 These functions are called in turn with point at the location to
10698 which the link should point.
10700 A function in the hook should first test if it would like to
10701 handle this file type, for example by checking the `major-mode'
10702 or the file extension. If it decides not to handle this file, it
10703 should just return nil to give other functions a chance. If it
10704 does handle the file, it must return the search string to be used
10705 when following the link. The search string will be part of the
10706 file link, given after a double colon, and `org-open-at-point'
10707 will automatically search for it. If special measures must be
10708 taken to make the search successful, another function should be
10709 added to the companion hook `org-execute-file-search-functions',
10710 which see.
10712 A function in this hook may also use `setq' to set the variable
10713 `description' to provide a suggestion for the descriptive text to
10714 be used for this link when it gets inserted into an Org-mode
10715 buffer with \\[org-insert-link].")
10717 (defvar org-execute-file-search-functions nil
10718 "List of functions to execute a file search triggered by a link.
10720 Functions added to this hook must accept a single argument, the
10721 search string that was part of the file link, the part after the
10722 double colon. The function must first check if it would like to
10723 handle this search, for example by checking the `major-mode' or
10724 the file extension. If it decides not to handle this search, it
10725 should just return nil to give other functions a chance. If it
10726 does handle the search, it must return a non-nil value to keep
10727 other functions from trying.
10729 Each function can access the current prefix argument through the
10730 variable `current-prefix-arg'. Note that a single prefix is used
10731 to force opening a link in Emacs, so it may be good to only use a
10732 numeric or double prefix to guide the search function.
10734 In case this is needed, a function in this hook can also restore
10735 the window configuration before `org-open-at-point' was called using:
10737 (set-window-configuration org-window-config-before-follow-link)")
10739 (defun org-link-search (s &optional type avoid-pos stealth)
10740 "Search for a link search option.
10741 If S is surrounded by forward slashes, it is interpreted as a
10742 regular expression. In org-mode files, this will create an `org-occur'
10743 sparse tree. In ordinary files, `occur' will be used to list matches.
10744 If the current buffer is in `dired-mode', grep will be used to search
10745 in all files. If AVOID-POS is given, ignore matches near that position.
10747 When optional argument STEALTH is non-nil, do not modify
10748 visibility around point, thus ignoring
10749 `org-show-hierarchy-above', `org-show-following-heading' and
10750 `org-show-siblings' variables."
10751 (let ((case-fold-search t)
10752 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10753 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10754 (append '(("") (" ") ("\t") ("\n"))
10755 org-emphasis-alist)
10756 "\\|") "\\)"))
10757 (pos (point))
10758 (pre nil) (post nil)
10759 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10760 (cond
10761 ;; First check if there are any special search functions
10762 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10763 ;; Now try the builtin stuff
10764 ((and (equal (string-to-char s0) ?#)
10765 (> (length s0) 1)
10766 (save-excursion
10767 (goto-char (point-min))
10768 (and
10769 (re-search-forward
10770 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10771 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10772 (setq type 'dedicated
10773 pos (match-beginning 0))))
10774 ;; There is an exact target for this
10775 (goto-char pos)
10776 (org-back-to-heading t)))
10777 ((save-excursion
10778 (goto-char (point-min))
10779 (and
10780 (re-search-forward
10781 (concat "<<" (regexp-quote s0) ">>") nil t)
10782 (setq type 'dedicated
10783 pos (match-beginning 0))))
10784 ;; There is an exact target for this
10785 (goto-char pos))
10786 ((save-excursion
10787 (goto-char (point-min))
10788 (and
10789 (re-search-forward
10790 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10791 (setq type 'dedicated pos (match-beginning 0))))
10792 ;; Found an element with a matching #+name affiliated keyword.
10793 (goto-char pos))
10794 ((and (string-match "^(\\(.*\\))$" s0)
10795 (save-excursion
10796 (goto-char (point-min))
10797 (and
10798 (re-search-forward
10799 (concat "[^[]" (regexp-quote
10800 (format org-coderef-label-format
10801 (match-string 1 s0))))
10802 nil t)
10803 (setq type 'dedicated
10804 pos (1+ (match-beginning 0))))))
10805 ;; There is a coderef target for this
10806 (goto-char pos))
10807 ((string-match "^/\\(.*\\)/$" s)
10808 ;; A regular expression
10809 (cond
10810 ((derived-mode-p 'org-mode)
10811 (org-occur (match-string 1 s)))
10812 (t (org-do-occur (match-string 1 s)))))
10813 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10814 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10815 (goto-char (point-min))
10816 (cond
10817 ((let (case-fold-search)
10818 (re-search-forward (format org-complex-heading-regexp-format
10819 (regexp-quote s))
10820 nil t))
10821 ;; OK, found a match
10822 (setq type 'dedicated)
10823 (goto-char (match-beginning 0)))
10824 ((and (not org-link-search-inhibit-query)
10825 (eq org-link-search-must-match-exact-headline 'query-to-create)
10826 (y-or-n-p "No match - create this as a new heading? "))
10827 (goto-char (point-max))
10828 (or (bolp) (newline))
10829 (insert "* " s "\n")
10830 (beginning-of-line 0))
10832 (goto-char pos)
10833 (error "No match"))))
10835 ;; A normal search string
10836 (when (equal (string-to-char s) ?*)
10837 ;; Anchor on headlines, post may include tags.
10838 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10839 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10840 s (substring s 1)))
10841 (remove-text-properties
10842 0 (length s)
10843 '(face nil mouse-face nil keymap nil fontified nil) s)
10844 ;; Make a series of regular expressions to find a match
10845 (setq words (org-split-string s "[ \n\r\t]+")
10847 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10848 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10849 "\\)" markers)
10850 re2a_ (concat "\\(" (mapconcat 'downcase words
10851 "[ \t\r\n]+") "\\)[ \t\r\n]")
10852 re2a (concat "[ \t\r\n]" re2a_)
10853 re4_ (concat "\\(" (mapconcat 'downcase words
10854 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10855 re4 (concat "[^a-zA-Z_]" re4_)
10857 re1 (concat pre re2 post)
10858 re3 (concat pre (if pre re4_ re4) post)
10859 re5 (concat pre ".*" re4)
10860 re2 (concat pre re2)
10861 re2a (concat pre (if pre re2a_ re2a))
10862 re4 (concat pre (if pre re4_ re4))
10863 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10864 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10865 re5 "\\)"))
10866 (cond
10867 ((eq type 'org-occur) (org-occur reall))
10868 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10869 (t (goto-char (point-min))
10870 (setq type 'fuzzy)
10871 (if (or (and (org-search-not-self 1 re0 nil t)
10872 (setq type 'dedicated))
10873 (org-search-not-self 1 re1 nil t)
10874 (org-search-not-self 1 re2 nil t)
10875 (org-search-not-self 1 re2a nil t)
10876 (org-search-not-self 1 re3 nil t)
10877 (org-search-not-self 1 re4 nil t)
10878 (org-search-not-self 1 re5 nil t))
10879 (goto-char (match-beginning 1))
10880 (goto-char pos)
10881 (error "No match"))))))
10882 (and (derived-mode-p 'org-mode)
10883 (not stealth)
10884 (org-show-context 'link-search))
10885 type))
10887 (defun org-search-not-self (group &rest args)
10888 "Execute `re-search-forward', but only accept matches that do not
10889 enclose the position of `org-open-link-marker'."
10890 (let ((m org-open-link-marker))
10891 (catch 'exit
10892 (while (apply 're-search-forward args)
10893 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10894 (goto-char (match-end group))
10895 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10896 (> (match-beginning 0) (marker-position m))
10897 (< (match-end 0) (marker-position m)))
10898 (save-match-data
10899 (or (not (org-in-regexp
10900 org-bracket-link-analytic-regexp 1))
10901 (not (match-end 4)) ; no description
10902 (and (<= (match-beginning 4) (point))
10903 (>= (match-end 4) (point))))))
10904 (throw 'exit (point))))))))
10906 (defun org-get-buffer-for-internal-link (buffer)
10907 "Return a buffer to be used for displaying the link target of internal links."
10908 (cond
10909 ((not org-display-internal-link-with-indirect-buffer)
10910 buffer)
10911 ((string-match "(Clone)$" (buffer-name buffer))
10912 (message "Buffer is already a clone, not making another one")
10913 ;; we also do not modify visibility in this case
10914 buffer)
10915 (t ; make a new indirect buffer for displaying the link
10916 (let* ((bn (buffer-name buffer))
10917 (ibn (concat bn "(Clone)"))
10918 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10919 (with-current-buffer ib (org-overview))
10920 ib))))
10922 (defun org-do-occur (regexp &optional cleanup)
10923 "Call the Emacs command `occur'.
10924 If CLEANUP is non-nil, remove the printout of the regular expression
10925 in the *Occur* buffer. This is useful if the regex is long and not useful
10926 to read."
10927 (occur regexp)
10928 (when cleanup
10929 (let ((cwin (selected-window)) win beg end)
10930 (when (setq win (get-buffer-window "*Occur*"))
10931 (select-window win))
10932 (goto-char (point-min))
10933 (when (re-search-forward "match[a-z]+" nil t)
10934 (setq beg (match-end 0))
10935 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10936 (setq end (1- (match-beginning 0)))))
10937 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10938 (goto-char (point-min))
10939 (select-window cwin))))
10941 ;;; The mark ring for links jumps
10943 (defvar org-mark-ring nil
10944 "Mark ring for positions before jumps in Org-mode.")
10945 (defvar org-mark-ring-last-goto nil
10946 "Last position in the mark ring used to go back.")
10947 ;; Fill and close the ring
10948 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10949 (loop for i from 1 to org-mark-ring-length do
10950 (push (make-marker) org-mark-ring))
10951 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10952 org-mark-ring)
10954 (defun org-mark-ring-push (&optional pos buffer)
10955 "Put the current position or POS into the mark ring and rotate it."
10956 (interactive)
10957 (setq pos (or pos (point)))
10958 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10959 (move-marker (car org-mark-ring)
10960 (or pos (point))
10961 (or buffer (current-buffer)))
10962 (message "%s"
10963 (substitute-command-keys
10964 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10966 (defun org-mark-ring-goto (&optional n)
10967 "Jump to the previous position in the mark ring.
10968 With prefix arg N, jump back that many stored positions. When
10969 called several times in succession, walk through the entire ring.
10970 Org-mode commands jumping to a different position in the current file,
10971 or to another Org-mode file, automatically push the old position
10972 onto the ring."
10973 (interactive "p")
10974 (let (p m)
10975 (if (eq last-command this-command)
10976 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10977 (setq p org-mark-ring))
10978 (setq org-mark-ring-last-goto p)
10979 (setq m (car p))
10980 (org-pop-to-buffer-same-window (marker-buffer m))
10981 (goto-char m)
10982 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10984 (defun org-remove-angle-brackets (s)
10985 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10986 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10988 (defun org-add-angle-brackets (s)
10989 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10990 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10992 (defun org-remove-double-quotes (s)
10993 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10994 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10997 ;;; Following specific links
10999 (defun org-follow-timestamp-link ()
11000 "Open an agenda view for the time-stamp date/range at point."
11001 (cond
11002 ((org-at-date-range-p t)
11003 (let ((org-agenda-start-on-weekday)
11004 (t1 (match-string 1))
11005 (t2 (match-string 2)) tt1 tt2)
11006 (setq tt1 (time-to-days (org-time-string-to-time t1))
11007 tt2 (time-to-days (org-time-string-to-time t2)))
11008 (let ((org-agenda-buffer-tmp-name
11009 (format "*Org Agenda(a:%s)"
11010 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11011 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11012 ((org-at-timestamp-p t)
11013 (let ((org-agenda-buffer-tmp-name
11014 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11015 (org-agenda-list nil (time-to-days (org-time-string-to-time
11016 (substring (match-string 1) 0 10)))
11017 1)))
11018 (t (error "This should not happen"))))
11021 ;;; Following file links
11022 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11023 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11024 (declare-function mailcap-mime-info
11025 "mailcap" (string &optional request no-decode))
11026 (defvar org-wait nil)
11027 (defun org-open-file (path &optional in-emacs line search)
11028 "Open the file at PATH.
11029 First, this expands any special file name abbreviations. Then the
11030 configuration variable `org-file-apps' is checked if it contains an
11031 entry for this file type, and if yes, the corresponding command is launched.
11033 If no application is found, Emacs simply visits the file.
11035 With optional prefix argument IN-EMACS, Emacs will visit the file.
11036 With a double \\[universal-argument] \\[universal-argument] \
11037 prefix arg, Org tries to avoid opening in Emacs
11038 and to use an external application to visit the file.
11040 Optional LINE specifies a line to go to, optional SEARCH a string
11041 to search for. If LINE or SEARCH is given, the file will be
11042 opened in Emacs, unless an entry from org-file-apps that makes
11043 use of groups in a regexp matches.
11045 If you want to change the way frames are used when following a
11046 link, please customize `org-link-frame-setup'.
11048 If the file does not exist, an error is thrown."
11049 (let* ((file (if (equal path "")
11050 buffer-file-name
11051 (substitute-in-file-name (expand-file-name path))))
11052 (file-apps (append org-file-apps (org-default-apps)))
11053 (apps (org-remove-if
11054 'org-file-apps-entry-match-against-dlink-p file-apps))
11055 (apps-dlink (org-remove-if-not
11056 'org-file-apps-entry-match-against-dlink-p file-apps))
11057 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11058 (dirp (if remp nil (file-directory-p file)))
11059 (file (if (and dirp org-open-directory-means-index-dot-org)
11060 (concat (file-name-as-directory file) "index.org")
11061 file))
11062 (a-m-a-p (assq 'auto-mode apps))
11063 (dfile (downcase file))
11064 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
11065 (link (cond ((and (eq line nil)
11066 (eq search nil))
11067 file)
11068 (line
11069 (concat file "::" (number-to-string line)))
11070 (search
11071 (concat file "::" search))))
11072 (dlink (downcase link))
11073 (old-buffer (current-buffer))
11074 (old-pos (point))
11075 (old-mode major-mode)
11076 ext cmd link-match-data)
11077 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11078 (setq ext (match-string 1 dfile))
11079 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11080 (setq ext (match-string 1 dfile))))
11081 (cond
11082 ((member in-emacs '((16) system))
11083 (setq cmd (cdr (assoc 'system apps))))
11084 (in-emacs (setq cmd 'emacs))
11086 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11087 (and dirp (cdr (assoc 'directory apps)))
11088 ; first, try matching against apps-dlink
11089 ; if we get a match here, store the match data for later
11090 (let ((match (assoc-default dlink apps-dlink
11091 'string-match)))
11092 (if match
11093 (progn (setq link-match-data (match-data))
11094 match)
11095 (progn (setq in-emacs (or in-emacs line search))
11096 nil))) ; if we have no match in apps-dlink,
11097 ; always open the file in emacs if line or search
11098 ; is given (for backwards compatibility)
11099 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11100 'string-match)
11101 (cdr (assoc ext apps))
11102 (cdr (assoc t apps))))))
11103 (when (eq cmd 'system)
11104 (setq cmd (cdr (assoc 'system apps))))
11105 (when (eq cmd 'default)
11106 (setq cmd (cdr (assoc t apps))))
11107 (when (eq cmd 'mailcap)
11108 (require 'mailcap)
11109 (mailcap-parse-mailcaps)
11110 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11111 (command (mailcap-mime-info mime-type)))
11112 (if (stringp command)
11113 (setq cmd command)
11114 (setq cmd 'emacs))))
11115 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11116 (not (file-exists-p file))
11117 (not org-open-non-existing-files))
11118 (user-error "No such file: %s" file))
11119 (cond
11120 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11121 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11122 (while (string-match "['\"]%s['\"]" cmd)
11123 (setq cmd (replace-match "%s" t t cmd)))
11124 (while (string-match "%s" cmd)
11125 (setq cmd (replace-match
11126 (save-match-data
11127 (shell-quote-argument
11128 (convert-standard-filename file)))
11129 t t cmd)))
11131 ;; Replace "%1", "%2" etc. in command with group matches from regex
11132 (save-match-data
11133 (let ((match-index 1)
11134 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11135 (set-match-data link-match-data)
11136 (while (<= match-index number-of-groups)
11137 (let ((regex (concat "%" (number-to-string match-index)))
11138 (replace-with (match-string match-index dlink)))
11139 (while (string-match regex cmd)
11140 (setq cmd (replace-match replace-with t t cmd))))
11141 (setq match-index (+ match-index 1)))))
11143 (save-window-excursion
11144 (message "Running %s...done" cmd)
11145 (start-process-shell-command cmd nil cmd)
11146 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11147 ((or (stringp cmd)
11148 (eq cmd 'emacs))
11149 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11150 (widen)
11151 (if line (org-goto-line line)
11152 (if search (org-link-search search))))
11153 ((consp cmd)
11154 (let ((file (convert-standard-filename file)))
11155 (save-match-data
11156 (set-match-data link-match-data)
11157 (eval cmd))))
11158 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11159 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11160 (or (not (equal old-buffer (current-buffer)))
11161 (not (equal old-pos (point))))
11162 (org-mark-ring-push old-pos old-buffer))))
11164 (defun org-file-apps-entry-match-against-dlink-p (entry)
11165 "This function returns non-nil if `entry' uses a regular
11166 expression which should be matched against the whole link by
11167 org-open-file.
11169 It assumes that is the case when the entry uses a regular
11170 expression which has at least one grouping construct and the
11171 action is either a lisp form or a command string containing
11172 '%1', i.e. using at least one subexpression match as a
11173 parameter."
11174 (let ((selector (car entry))
11175 (action (cdr entry)))
11176 (if (stringp selector)
11177 (and (> (regexp-opt-depth selector) 0)
11178 (or (and (stringp action)
11179 (string-match "%[0-9]" action))
11180 (consp action)))
11181 nil)))
11183 (defun org-default-apps ()
11184 "Return the default applications for this operating system."
11185 (cond
11186 ((eq system-type 'darwin)
11187 org-file-apps-defaults-macosx)
11188 ((eq system-type 'windows-nt)
11189 org-file-apps-defaults-windowsnt)
11190 (t org-file-apps-defaults-gnu)))
11192 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11193 "Convert extensions to regular expressions in the cars of LIST.
11194 Also, weed out any non-string entries, because the return value is used
11195 only for regexp matching.
11196 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11197 point to the symbol `emacs', indicating that the file should
11198 be opened in Emacs."
11199 (append
11200 (delq nil
11201 (mapcar (lambda (x)
11202 (if (not (stringp (car x)))
11204 (if (string-match "\\W" (car x))
11206 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11207 list))
11208 (if add-auto-mode
11209 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11211 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11212 (defun org-file-remote-p (file)
11213 "Test whether FILE specifies a location on a remote system.
11214 Return non-nil if the location is indeed remote.
11216 For example, the filename \"/user@host:/foo\" specifies a location
11217 on the system \"/user@host:\"."
11218 (cond ((fboundp 'file-remote-p)
11219 (file-remote-p file))
11220 ((fboundp 'tramp-handle-file-remote-p)
11221 (tramp-handle-file-remote-p file))
11222 ((and (boundp 'ange-ftp-name-format)
11223 (string-match (car ange-ftp-name-format) file))
11224 t)))
11227 ;;;; Refiling
11229 (defun org-get-org-file ()
11230 "Read a filename, with default directory `org-directory'."
11231 (let ((default (or org-default-notes-file remember-data-file)))
11232 (read-file-name (format "File name [%s]: " default)
11233 (file-name-as-directory org-directory)
11234 default)))
11236 (defun org-notes-order-reversed-p ()
11237 "Check if the current file should receive notes in reversed order."
11238 (cond
11239 ((not org-reverse-note-order) nil)
11240 ((eq t org-reverse-note-order) t)
11241 ((not (listp org-reverse-note-order)) nil)
11242 (t (catch 'exit
11243 (let ((all org-reverse-note-order)
11244 entry)
11245 (while (setq entry (pop all))
11246 (if (string-match (car entry) buffer-file-name)
11247 (throw 'exit (cdr entry))))
11248 nil)))))
11250 (defvar org-refile-target-table nil
11251 "The list of refile targets, created by `org-refile'.")
11253 (defvar org-agenda-new-buffers nil
11254 "Buffers created to visit agenda files.")
11256 (defvar org-refile-cache nil
11257 "Cache for refile targets.")
11259 (defvar org-refile-markers nil
11260 "All the markers used for caching refile locations.")
11262 (defun org-refile-marker (pos)
11263 "Get a new refile marker, but only if caching is in use."
11264 (if (not org-refile-use-cache)
11266 (let ((m (make-marker)))
11267 (move-marker m pos)
11268 (push m org-refile-markers)
11269 m)))
11271 (defun org-refile-cache-clear ()
11272 "Clear the refile cache and disable all the markers."
11273 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11274 (setq org-refile-markers nil)
11275 (setq org-refile-cache nil)
11276 (message "Refile cache has been cleared"))
11278 (defun org-refile-cache-check-set (set)
11279 "Check if all the markers in the cache still have live buffers."
11280 (let (marker)
11281 (catch 'exit
11282 (while (and set (setq marker (nth 3 (pop set))))
11283 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11284 (when (and marker (null (marker-buffer marker)))
11285 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11286 (sit-for 3)
11287 (throw 'exit nil)))
11288 t)))
11290 (defun org-refile-cache-put (set &rest identifiers)
11291 "Push the refile targets SET into the cache, under IDENTIFIERS."
11292 (let* ((key (sha1 (prin1-to-string identifiers)))
11293 (entry (assoc key org-refile-cache)))
11294 (if entry
11295 (setcdr entry set)
11296 (push (cons key set) org-refile-cache))))
11298 (defun org-refile-cache-get (&rest identifiers)
11299 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11300 (cond
11301 ((not org-refile-cache) nil)
11302 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11304 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11305 org-refile-cache))))
11306 (and set (org-refile-cache-check-set set) set)))))
11308 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11309 "Produce a table with refile targets."
11310 (let ((case-fold-search nil)
11311 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11312 (entries (or org-refile-targets '((nil . (:level . 1)))))
11313 targets tgs txt re files f desc descre fast-path-p level pos0)
11314 (message "Getting targets...")
11315 (with-current-buffer (or default-buffer (current-buffer))
11316 (while (setq entry (pop entries))
11317 (setq files (car entry) desc (cdr entry))
11318 (setq fast-path-p nil)
11319 (cond
11320 ((null files) (setq files (list (current-buffer))))
11321 ((eq files 'org-agenda-files)
11322 (setq files (org-agenda-files 'unrestricted)))
11323 ((and (symbolp files) (fboundp files))
11324 (setq files (funcall files)))
11325 ((and (symbolp files) (boundp files))
11326 (setq files (symbol-value files))))
11327 (if (stringp files) (setq files (list files)))
11328 (cond
11329 ((eq (car desc) :tag)
11330 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11331 ((eq (car desc) :todo)
11332 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11333 ((eq (car desc) :regexp)
11334 (setq descre (cdr desc)))
11335 ((eq (car desc) :level)
11336 (setq descre (concat "^\\*\\{" (number-to-string
11337 (if org-odd-levels-only
11338 (1- (* 2 (cdr desc)))
11339 (cdr desc)))
11340 "\\}[ \t]")))
11341 ((eq (car desc) :maxlevel)
11342 (setq fast-path-p t)
11343 (setq descre (concat "^\\*\\{1," (number-to-string
11344 (if org-odd-levels-only
11345 (1- (* 2 (cdr desc)))
11346 (cdr desc)))
11347 "\\}[ \t]")))
11348 (t (error "Bad refiling target description %s" desc)))
11349 (while (setq f (pop files))
11350 (with-current-buffer
11351 (if (bufferp f) f (org-get-agenda-file-buffer f))
11353 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11354 (progn
11355 (if (bufferp f) (setq f (buffer-file-name
11356 (buffer-base-buffer f))))
11357 (setq f (and f (expand-file-name f)))
11358 (if (eq org-refile-use-outline-path 'file)
11359 (push (list (file-name-nondirectory f) f nil nil) tgs))
11360 (save-excursion
11361 (save-restriction
11362 (widen)
11363 (goto-char (point-min))
11364 (while (re-search-forward descre nil t)
11365 (goto-char (setq pos0 (point-at-bol)))
11366 (catch 'next
11367 (when org-refile-target-verify-function
11368 (save-match-data
11369 (or (funcall org-refile-target-verify-function)
11370 (throw 'next t))))
11371 (when (and (looking-at org-complex-heading-regexp)
11372 (not (member (match-string 4) excluded-entries))
11373 (match-string 4))
11374 (setq level (org-reduced-level
11375 (- (match-end 1) (match-beginning 1)))
11376 txt (org-link-display-format (match-string 4))
11377 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11378 re (format org-complex-heading-regexp-format
11379 (regexp-quote (match-string 4))))
11380 (when org-refile-use-outline-path
11381 (setq txt (mapconcat
11382 'org-protect-slash
11383 (append
11384 (if (eq org-refile-use-outline-path
11385 'file)
11386 (list (file-name-nondirectory
11387 (buffer-file-name
11388 (buffer-base-buffer))))
11389 (if (eq org-refile-use-outline-path
11390 'full-file-path)
11391 (list (buffer-file-name
11392 (buffer-base-buffer)))))
11393 (org-get-outline-path fast-path-p
11394 level txt)
11395 (list txt))
11396 "/")))
11397 (push (list txt f re (org-refile-marker (point)))
11398 tgs)))
11399 (when (= (point) pos0)
11400 ;; verification function has not moved point
11401 (goto-char (point-at-eol))))))))
11402 (when org-refile-use-cache
11403 (org-refile-cache-put tgs (buffer-file-name) descre))
11404 (setq targets (append tgs targets))))))
11405 (message "Getting targets...done")
11406 (nreverse targets)))
11408 (defun org-protect-slash (s)
11409 (while (string-match "/" s)
11410 (setq s (replace-match "\\" t t s)))
11413 (defvar org-olpa (make-vector 20 nil))
11415 (defun org-get-outline-path (&optional fastp level heading)
11416 "Return the outline path to the current entry, as a list.
11418 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11419 routine which makes outline path derivations for an entire file,
11420 avoiding backtracing. Refile target collection makes use of that."
11421 (if fastp
11422 (progn
11423 (if (> level 19)
11424 (error "Outline path failure, more than 19 levels"))
11425 (loop for i from level upto 19 do
11426 (aset org-olpa i nil))
11427 (prog1
11428 (delq nil (append org-olpa nil))
11429 (aset org-olpa level heading)))
11430 (let (rtn case-fold-search)
11431 (save-excursion
11432 (save-restriction
11433 (widen)
11434 (while (org-up-heading-safe)
11435 (when (looking-at org-complex-heading-regexp)
11436 (push (org-trim
11437 (replace-regexp-in-string
11438 ;; Remove statistical/checkboxes cookies
11439 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11440 (org-match-string-no-properties 4)))
11441 rtn)))
11442 rtn)))))
11444 (defun org-format-outline-path (path &optional width prefix separator)
11445 "Format the outline path PATH for display.
11446 WIDTH is the maximum number of characters that is available.
11447 PREFIX is a prefix to be included in the returned string,
11448 such as the file name.
11449 SEPARATOR is inserted between the different parts of the path,
11450 the default is \"/\"."
11451 (setq width (or width 79))
11452 (if prefix (setq width (- width (length prefix))))
11453 (if (not path)
11454 (or prefix "")
11455 (let* ((nsteps (length path))
11456 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11457 (maxwidth (if (<= total-width width)
11458 10000 ;; everything fits
11459 ;; we need to shorten the level headings
11460 (/ (- width nsteps) nsteps)))
11461 (org-odd-levels-only nil)
11462 (n 0)
11463 (total (1+ (length prefix))))
11464 (setq maxwidth (max maxwidth 10))
11465 (concat prefix
11466 (if prefix (or separator "/"))
11467 (mapconcat
11468 (lambda (h)
11469 (setq n (1+ n))
11470 (if (and (= n nsteps) (< maxwidth 10000))
11471 (setq maxwidth (- total-width total)))
11472 (if (< (length h) maxwidth)
11473 (progn (setq total (+ total (length h) 1)) h)
11474 (setq h (substring h 0 (- maxwidth 2))
11475 total (+ total maxwidth 1))
11476 (if (string-match "[ \t]+\\'" h)
11477 (setq h (substring h 0 (match-beginning 0))))
11478 (setq h (concat h "..")))
11479 (org-add-props h nil 'face
11480 (nth (% (1- n) org-n-level-faces)
11481 org-level-faces))
11483 path (or separator "/"))))))
11485 (defun org-display-outline-path (&optional file current separator just-return-string)
11486 "Display the current outline path in the echo area.
11488 If FILE is non-nil, prepend the output with the file name.
11489 If CURRENT is non-nil, append the current heading to the output.
11490 SEPARATOR is passed through to `org-format-outline-path'. It separates
11491 the different parts of the path and defaults to \"/\".
11492 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11493 (interactive "P")
11494 (let* (case-fold-search
11495 (bfn (buffer-file-name (buffer-base-buffer)))
11496 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11497 res)
11498 (if current (setq path (append path
11499 (save-excursion
11500 (org-back-to-heading t)
11501 (if (looking-at org-complex-heading-regexp)
11502 (list (match-string 4)))))))
11503 (setq res
11504 (org-format-outline-path
11505 path
11506 (1- (frame-width))
11507 (and file bfn (concat (file-name-nondirectory bfn) separator))
11508 separator))
11509 (if just-return-string
11510 (org-no-properties res)
11511 (org-unlogged-message "%s" res))))
11513 (defvar org-refile-history nil
11514 "History for refiling operations.")
11516 (defvar org-after-refile-insert-hook nil
11517 "Hook run after `org-refile' has inserted its stuff at the new location.
11518 Note that this is still *before* the stuff will be removed from
11519 the *old* location.")
11521 (defvar org-capture-last-stored-marker)
11522 (defvar org-refile-keep nil
11523 "Non-nil means `org-refile' will copy instead of refile.")
11525 (defun org-copy ()
11526 "Like `org-refile', but copy."
11527 (interactive)
11528 (let ((org-refile-keep t))
11529 (funcall 'org-refile nil nil nil "Copy")))
11531 (defun org-refile (&optional goto default-buffer rfloc msg)
11532 "Move the entry or entries at point to another heading.
11533 The list of target headings is compiled using the information in
11534 `org-refile-targets', which see.
11536 At the target location, the entry is filed as a subitem of the target
11537 heading. Depending on `org-reverse-note-order', the new subitem will
11538 either be the first or the last subitem.
11540 If there is an active region, all entries in that region will be moved.
11541 However, the region must fulfill the requirement that the first heading
11542 is the first one sets the top-level of the moved text - at most siblings
11543 below it are allowed.
11545 With prefix arg GOTO, the command will only visit the target location
11546 and not actually move anything.
11548 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11549 go to the location where the last refiling operation has put the subtree.
11551 With a numeric prefix argument of `2', refile to the running clock.
11553 With a numeric prefix argument of `3', emulate `org-refile-keep'
11554 being set to `t' and copy to the target location, don't move it.
11555 Beware that keeping refiled entries may result in duplicated ID
11556 properties.
11558 RFLOC can be a refile location obtained in a different way.
11560 MSG is a string to replace \"Refile\" in the default prompt with
11561 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11563 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11565 If you are using target caching (see `org-refile-use-cache'),
11566 you have to clear the target cache in order to find new targets.
11567 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11568 prefix argument (`C-u C-u C-u C-c C-w')."
11570 (interactive "P")
11571 (if (member goto '(0 (64)))
11572 (org-refile-cache-clear)
11573 (let* ((actionmsg (cond (msg msg)
11574 ((equal goto 3) "Refile (and keep)")
11575 (t "Refile")))
11576 (cbuf (current-buffer))
11577 (regionp (org-region-active-p))
11578 (region-start (and regionp (region-beginning)))
11579 (region-end (and regionp (region-end)))
11580 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11581 (org-refile-keep (if (equal goto 3) t org-refile-keep))
11582 pos it nbuf file re level reversed)
11583 (setq last-command nil)
11584 (when regionp
11585 (goto-char region-start)
11586 (or (bolp) (goto-char (point-at-bol)))
11587 (setq region-start (point))
11588 (unless (or (org-kill-is-subtree-p
11589 (buffer-substring region-start region-end))
11590 (prog1 org-refile-active-region-within-subtree
11591 (let ((s (point-at-eol)))
11592 (org-toggle-heading)
11593 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11594 (user-error "The region is not a (sequence of) subtree(s)")))
11595 (if (equal goto '(16))
11596 (org-refile-goto-last-stored)
11597 (when (or
11598 (and (equal goto 2)
11599 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11600 (prog1
11601 (setq it (list (or org-clock-heading "running clock")
11602 (buffer-file-name
11603 (marker-buffer org-clock-hd-marker))
11605 (marker-position org-clock-hd-marker)))
11606 (setq goto nil)))
11607 (setq it (or rfloc
11608 (let (heading-text)
11609 (save-excursion
11610 (unless (and goto (listp goto))
11611 (org-back-to-heading t)
11612 (setq heading-text
11613 (nth 4 (org-heading-components))))
11615 (org-refile-get-location
11616 (cond ((and goto (listp goto)) "Goto")
11617 (regionp (concat actionmsg " region to"))
11618 (t (concat actionmsg " subtree \""
11619 heading-text "\" to")))
11620 default-buffer
11621 (and (not (equal '(4) goto))
11622 org-refile-allow-creating-parent-nodes)
11623 goto))))))
11624 (setq file (nth 1 it)
11625 re (nth 2 it)
11626 pos (nth 3 it))
11627 (if (and (not goto)
11629 (equal (buffer-file-name) file)
11630 (if regionp
11631 (and (>= pos region-start)
11632 (<= pos region-end))
11633 (and (>= pos (point))
11634 (< pos (save-excursion
11635 (org-end-of-subtree t t))))))
11636 (error "Cannot refile to position inside the tree or region"))
11638 (setq nbuf (or (find-buffer-visiting file)
11639 (find-file-noselect file)))
11640 (if (and goto (not (equal goto 3)))
11641 (progn
11642 (org-pop-to-buffer-same-window nbuf)
11643 (goto-char pos)
11644 (org-show-context 'org-goto))
11645 (if regionp
11646 (progn
11647 (org-kill-new (buffer-substring region-start region-end))
11648 (org-save-markers-in-region region-start region-end))
11649 (org-copy-subtree 1 nil t))
11650 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11651 (find-file-noselect file)))
11652 (setq reversed (org-notes-order-reversed-p))
11653 (save-excursion
11654 (save-restriction
11655 (widen)
11656 (if pos
11657 (progn
11658 (goto-char pos)
11659 (looking-at org-outline-regexp)
11660 (setq level (org-get-valid-level (funcall outline-level) 1))
11661 (goto-char
11662 (if reversed
11663 (or (outline-next-heading) (point-max))
11664 (or (save-excursion (org-get-next-sibling))
11665 (org-end-of-subtree t t)
11666 (point-max)))))
11667 (setq level 1)
11668 (if (not reversed)
11669 (goto-char (point-max))
11670 (goto-char (point-min))
11671 (or (outline-next-heading) (goto-char (point-max)))))
11672 (if (not (bolp)) (newline))
11673 (org-paste-subtree level)
11674 (when org-log-refile
11675 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11676 (unless (eq org-log-refile 'note)
11677 (save-excursion (org-add-log-note))))
11678 (and org-auto-align-tags
11679 (let ((org-loop-over-headlines-in-active-region nil))
11680 (org-set-tags nil t)))
11681 (let ((bookmark-name (plist-get org-bookmark-names-plist
11682 :last-refile)))
11683 (when bookmark-name
11684 (with-demoted-errors
11685 (bookmark-set bookmark-name))))
11686 ;; If we are refiling for capture, make sure that the
11687 ;; last-capture pointers point here
11688 (when (org-bound-and-true-p org-refile-for-capture)
11689 (let ((bookmark-name (plist-get org-bookmark-names-plist
11690 :last-capture-marker)))
11691 (when bookmark-name
11692 (with-demoted-errors
11693 (bookmark-set bookmark-name))))
11694 (move-marker org-capture-last-stored-marker (point)))
11695 (if (fboundp 'deactivate-mark) (deactivate-mark))
11696 (run-hooks 'org-after-refile-insert-hook))))
11697 (unless org-refile-keep
11698 (if regionp
11699 (delete-region (point) (+ (point) (- region-end region-start)))
11700 (delete-region
11701 (and (org-back-to-heading t) (point))
11702 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11703 (when (featurep 'org-inlinetask)
11704 (org-inlinetask-remove-END-maybe))
11705 (setq org-markers-to-move nil)
11706 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11708 (defun org-refile-goto-last-stored ()
11709 "Go to the location where the last refile was stored."
11710 (interactive)
11711 (bookmark-jump "org-refile-last-stored")
11712 (message "This is the location of the last refile"))
11714 (defun org-refile--get-location (refloc tbl)
11715 "When user refile to REFLOC, find the associated target in TBL.
11716 Also check `org-refile-target-table'."
11717 (car (delq
11719 (mapcar
11720 (lambda (r) (or (assoc r tbl)
11721 (assoc r org-refile-target-table)))
11722 (list (replace-regexp-in-string "/$" "" refloc)
11723 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11725 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11726 no-exclude)
11727 "Prompt the user for a refile location, using PROMPT.
11728 PROMPT should not be suffixed with a colon and a space, because
11729 this function appends the default value from
11730 `org-refile-history' automatically, if that is not empty.
11731 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11732 this is used for the GOTO interface."
11733 (let ((org-refile-targets org-refile-targets)
11734 (org-refile-use-outline-path org-refile-use-outline-path)
11735 excluded-entries)
11736 (when (and (derived-mode-p 'org-mode)
11737 (not org-refile-use-cache)
11738 (not no-exclude))
11739 (org-map-tree
11740 (lambda()
11741 (setq excluded-entries
11742 (append excluded-entries (list (org-get-heading t t)))))))
11743 (setq org-refile-target-table
11744 (org-refile-get-targets default-buffer excluded-entries)))
11745 (unless org-refile-target-table
11746 (user-error "No refile targets"))
11747 (let* ((cbuf (current-buffer))
11748 (partial-completion-mode nil)
11749 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11750 (cfunc (if (and org-refile-use-outline-path
11751 org-outline-path-complete-in-steps)
11752 'org-olpath-completing-read
11753 'org-icompleting-read))
11754 (extra (if org-refile-use-outline-path "/" ""))
11755 (cbnex (concat (buffer-name) extra))
11756 (filename (and cfn (expand-file-name cfn)))
11757 (tbl (mapcar
11758 (lambda (x)
11759 (if (and (not (member org-refile-use-outline-path
11760 '(file full-file-path)))
11761 (not (equal filename (nth 1 x))))
11762 (cons (concat (car x) extra " ("
11763 (file-name-nondirectory (nth 1 x)) ")")
11764 (cdr x))
11765 (cons (concat (car x) extra) (cdr x))))
11766 org-refile-target-table))
11767 (completion-ignore-case t)
11768 cdef
11769 (prompt (concat prompt
11770 (or (and (car org-refile-history)
11771 (concat " (default " (car org-refile-history) ")"))
11772 (and (assoc cbnex tbl) (setq cdef cbnex)
11773 (concat " (default " cbnex ")"))) ": "))
11774 pa answ parent-target child parent old-hist)
11775 (setq old-hist org-refile-history)
11776 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11777 nil 'org-refile-history (or cdef (car org-refile-history))))
11778 (if (setq pa (org-refile--get-location answ tbl))
11779 (progn
11780 (org-refile-check-position pa)
11781 (when (or (not org-refile-history)
11782 (not (eq old-hist org-refile-history))
11783 (not (equal (car pa) (car org-refile-history))))
11784 (setq org-refile-history
11785 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11786 org-refile-history
11787 (cdr org-refile-history))))
11788 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11789 (pop org-refile-history)))
11791 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11792 (progn
11793 (setq parent (match-string 1 answ)
11794 child (match-string 2 answ))
11795 (setq parent-target (org-refile--get-location parent tbl))
11796 (when (and parent-target
11797 (or (eq new-nodes t)
11798 (and (eq new-nodes 'confirm)
11799 (y-or-n-p (format "Create new node \"%s\"? "
11800 child)))))
11801 (org-refile-new-child parent-target child)))
11802 (user-error "Invalid target location")))))
11804 (declare-function org-string-nw-p "org-macs" (s))
11805 (defun org-refile-check-position (refile-pointer)
11806 "Check if the refile pointer matches the headline to which it points."
11807 (let* ((file (nth 1 refile-pointer))
11808 (re (nth 2 refile-pointer))
11809 (pos (nth 3 refile-pointer))
11810 buffer)
11811 (if (and (not (markerp pos)) (not file))
11812 (user-error "Please save the buffer to a file before refiling")
11813 (when (org-string-nw-p re)
11814 (setq buffer (if (markerp pos)
11815 (marker-buffer pos)
11816 (or (find-buffer-visiting file)
11817 (find-file-noselect file))))
11818 (with-current-buffer buffer
11819 (save-excursion
11820 (save-restriction
11821 (widen)
11822 (goto-char pos)
11823 (beginning-of-line 1)
11824 (unless (org-looking-at-p re)
11825 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11827 (defun org-refile-new-child (parent-target child)
11828 "Use refile target PARENT-TARGET to add new CHILD below it."
11829 (unless parent-target
11830 (error "Cannot find parent for new node"))
11831 (let ((file (nth 1 parent-target))
11832 (pos (nth 3 parent-target))
11833 level)
11834 (with-current-buffer (or (find-buffer-visiting file)
11835 (find-file-noselect file))
11836 (save-excursion
11837 (save-restriction
11838 (widen)
11839 (if pos
11840 (goto-char pos)
11841 (goto-char (point-max))
11842 (if (not (bolp)) (newline)))
11843 (when (looking-at org-outline-regexp)
11844 (setq level (funcall outline-level))
11845 (org-end-of-subtree t t))
11846 (org-back-over-empty-lines)
11847 (insert "\n" (make-string
11848 (if pos (org-get-valid-level level 1) 1) ?*)
11849 " " child "\n")
11850 (beginning-of-line 0)
11851 (list (concat (car parent-target) "/" child) file "" (point)))))))
11853 (defun org-olpath-completing-read (prompt collection &rest args)
11854 "Read an outline path like a file name."
11855 (let ((thetable collection)
11856 (org-completion-use-ido nil) ; does not work with ido.
11857 (org-completion-use-iswitchb nil)) ; or iswitchb
11858 (apply
11859 'org-icompleting-read prompt
11860 (lambda (string predicate &optional flag)
11861 (let (rtn r f (l (length string)))
11862 (cond
11863 ((eq flag nil)
11864 ;; try completion
11865 (try-completion string thetable))
11866 ((eq flag t)
11867 ;; all-completions
11868 (setq rtn (all-completions string thetable predicate))
11869 (mapcar
11870 (lambda (x)
11871 (setq r (substring x l))
11872 (if (string-match " ([^)]*)$" x)
11873 (setq f (match-string 0 x))
11874 (setq f ""))
11875 (if (string-match "/" r)
11876 (concat string (substring r 0 (match-end 0)) f)
11878 rtn))
11879 ((eq flag 'lambda)
11880 ;; exact match?
11881 (assoc string thetable)))))
11882 args)))
11884 ;;;; Dynamic blocks
11886 (defun org-find-dblock (name)
11887 "Find the first dynamic block with name NAME in the buffer.
11888 If not found, stay at current position and return nil."
11889 (let ((case-fold-search t) pos)
11890 (save-excursion
11891 (goto-char (point-min))
11892 (setq pos (and (re-search-forward
11893 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11894 (match-beginning 0))))
11895 (if pos (goto-char pos))
11896 pos))
11898 (defconst org-dblock-start-re
11899 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11900 "Matches the start line of a dynamic block, with parameters.")
11902 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11903 "Matches the end of a dynamic block.")
11905 (defun org-create-dblock (plist)
11906 "Create a dynamic block section, with parameters taken from PLIST.
11907 PLIST must contain a :name entry which is used as name of the block."
11908 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11909 (end-of-line 1)
11910 (newline))
11911 (let ((col (current-column))
11912 (name (plist-get plist :name)))
11913 (insert "#+BEGIN: " name)
11914 (while plist
11915 (if (eq (car plist) :name)
11916 (setq plist (cddr plist))
11917 (insert " " (prin1-to-string (pop plist)))))
11918 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11919 (beginning-of-line -2)))
11921 (defun org-prepare-dblock ()
11922 "Prepare dynamic block for refresh.
11923 This empties the block, puts the cursor at the insert position and returns
11924 the property list including an extra property :name with the block name."
11925 (unless (looking-at org-dblock-start-re)
11926 (user-error "Not at a dynamic block"))
11927 (let* ((begdel (1+ (match-end 0)))
11928 (name (org-no-properties (match-string 1)))
11929 (params (append (list :name name)
11930 (read (concat "(" (match-string 3) ")")))))
11931 (save-excursion
11932 (beginning-of-line 1)
11933 (skip-chars-forward " \t")
11934 (setq params (plist-put params :indentation-column (current-column))))
11935 (unless (re-search-forward org-dblock-end-re nil t)
11936 (error "Dynamic block not terminated"))
11937 (setq params
11938 (append params
11939 (list :content (buffer-substring
11940 begdel (match-beginning 0)))))
11941 (delete-region begdel (match-beginning 0))
11942 (goto-char begdel)
11943 (open-line 1)
11944 params))
11946 (defun org-map-dblocks (&optional command)
11947 "Apply COMMAND to all dynamic blocks in the current buffer.
11948 If COMMAND is not given, use `org-update-dblock'."
11949 (let ((cmd (or command 'org-update-dblock)))
11950 (save-excursion
11951 (goto-char (point-min))
11952 (while (re-search-forward org-dblock-start-re nil t)
11953 (goto-char (match-beginning 0))
11954 (save-excursion
11955 (condition-case nil
11956 (funcall cmd)
11957 (error (message "Error during update of dynamic block"))))
11958 (unless (re-search-forward org-dblock-end-re nil t)
11959 (error "Dynamic block not terminated"))))))
11961 (defun org-dblock-update (&optional arg)
11962 "User command for updating dynamic blocks.
11963 Update the dynamic block at point. With prefix ARG, update all dynamic
11964 blocks in the buffer."
11965 (interactive "P")
11966 (if arg
11967 (org-update-all-dblocks)
11968 (or (looking-at org-dblock-start-re)
11969 (org-beginning-of-dblock))
11970 (org-update-dblock)))
11972 (defun org-update-dblock ()
11973 "Update the dynamic block at point.
11974 This means to empty the block, parse for parameters and then call
11975 the correct writing function."
11976 (interactive)
11977 (save-excursion
11978 (let* ((win (selected-window))
11979 (pos (point))
11980 (line (org-current-line))
11981 (params (org-prepare-dblock))
11982 (name (plist-get params :name))
11983 (indent (plist-get params :indentation-column))
11984 (cmd (intern (concat "org-dblock-write:" name))))
11985 (message "Updating dynamic block `%s' at line %d..." name line)
11986 (funcall cmd params)
11987 (message "Updating dynamic block `%s' at line %d...done" name line)
11988 (goto-char pos)
11989 (when (and indent (> indent 0))
11990 (setq indent (make-string indent ?\ ))
11991 (save-excursion
11992 (select-window win)
11993 (org-beginning-of-dblock)
11994 (forward-line 1)
11995 (while (not (looking-at org-dblock-end-re))
11996 (insert indent)
11997 (beginning-of-line 2))
11998 (when (looking-at org-dblock-end-re)
11999 (and (looking-at "[ \t]+")
12000 (replace-match ""))
12001 (insert indent)))))))
12003 (defun org-beginning-of-dblock ()
12004 "Find the beginning of the dynamic block at point.
12005 Error if there is no such block at point."
12006 (let ((pos (point))
12007 beg)
12008 (end-of-line 1)
12009 (if (and (re-search-backward org-dblock-start-re nil t)
12010 (setq beg (match-beginning 0))
12011 (re-search-forward org-dblock-end-re nil t)
12012 (> (match-end 0) pos))
12013 (goto-char beg)
12014 (goto-char pos)
12015 (error "Not in a dynamic block"))))
12017 (defun org-update-all-dblocks ()
12018 "Update all dynamic blocks in the buffer.
12019 This function can be used in a hook."
12020 (interactive)
12021 (when (derived-mode-p 'org-mode)
12022 (org-map-dblocks 'org-update-dblock)))
12025 ;;;; Completion
12027 (declare-function org-export-backend-name "org-export" (cl-x))
12028 (declare-function org-export-backend-options "org-export" (cl-x))
12029 (defun org-get-export-keywords ()
12030 "Return a list of all currently understood export keywords.
12031 Export keywords include options, block names, attributes and
12032 keywords relative to each registered export back-end."
12033 (let (keywords)
12034 (dolist (backend
12035 (org-bound-and-true-p org-export--registered-backends)
12036 (delq nil keywords))
12037 ;; Back-end name (for keywords, like #+LATEX:)
12038 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12039 (dolist (option-entry (org-export-backend-options backend))
12040 ;; Back-end options.
12041 (push (nth 1 option-entry) keywords)))))
12043 (defconst org-options-keywords
12044 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12045 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12046 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12047 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12048 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12050 (defcustom org-structure-template-alist
12051 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC" "<src lang=\"?\">\n\n</src>")
12052 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE" "<example>\n?\n</example>")
12053 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE" "<quote>\n?\n</quote>")
12054 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE" "<verse>\n?\n</verse>")
12055 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM" "<verbatim>\n?\n</verbatim>")
12056 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER" "<center>\n?\n</center>")
12057 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
12058 "<literal style=\"latex\">\n?\n</literal>")
12059 ("L" "#+LaTeX: " "<literal style=\"latex\">?</literal>")
12060 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
12061 "<literal style=\"html\">\n?\n</literal>")
12062 ("H" "#+HTML: " "<literal style=\"html\">?</literal>")
12063 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII" "")
12064 ("A" "#+ASCII: " "")
12065 ("i" "#+INDEX: ?" "#+INDEX: ?")
12066 ("I" "#+INCLUDE: %file ?"
12067 "<include file=%file markup=\"?\">"))
12068 "Structure completion elements.
12069 This is a list of abbreviation keys and values. The value gets inserted
12070 if you type `<' followed by the key and then press the completion key,
12071 usually `M-TAB'. %file will be replaced by a file name after prompting
12072 for the file using completion. The cursor will be placed at the position
12073 of the `?` in the template.
12074 There are two templates for each key, the first uses the original Org syntax,
12075 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12076 the default when the /org-mtags.el/ module has been loaded. See also the
12077 variable `org-mtags-prefer-muse-templates'."
12078 :group 'org-completion
12079 :type '(repeat
12080 (list
12081 (string :tag "Key")
12082 (string :tag "Template")
12083 (string :tag "Muse Template"))))
12085 (defun org-try-structure-completion ()
12086 "Try to complete a structure template before point.
12087 This looks for strings like \"<e\" on an otherwise empty line and
12088 expands them."
12089 (let ((l (buffer-substring (point-at-bol) (point)))
12091 (when (and (looking-at "[ \t]*$")
12092 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12093 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12094 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12095 (match-beginning 1)) a)
12096 t)))
12098 (defun org-complete-expand-structure-template (start cell)
12099 "Expand a structure template."
12100 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
12101 (rpl (nth (if musep 2 1) cell))
12102 (ind ""))
12103 (delete-region start (point))
12104 (when (string-match "\\`#\\+" rpl)
12105 (cond
12106 ((bolp))
12107 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12108 (setq ind (buffer-substring (point-at-bol) (point))))
12109 (t (newline))))
12110 (setq start (point))
12111 (if (string-match "%file" rpl)
12112 (setq rpl (replace-match
12113 (concat
12114 "\""
12115 (save-match-data
12116 (abbreviate-file-name (read-file-name "Include file: ")))
12117 "\"")
12118 t t rpl)))
12119 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12120 (concat "\n" ind)))
12121 (insert rpl)
12122 (if (re-search-backward "\\?" start t) (delete-char 1))))
12124 ;;;; TODO, DEADLINE, Comments
12126 (defun org-toggle-comment ()
12127 "Change the COMMENT state of an entry."
12128 (interactive)
12129 (save-excursion
12130 (org-back-to-heading)
12131 (let (case-fold-search)
12132 (cond
12133 ((looking-at (format org-heading-keyword-regexp-format
12134 org-comment-string))
12135 (goto-char (match-end 1))
12136 (looking-at (concat " +" org-comment-string))
12137 (replace-match "" t t)
12138 (when (eolp) (insert " ")))
12139 ((looking-at org-outline-regexp)
12140 (goto-char (match-end 0))
12141 (insert org-comment-string " "))))))
12143 (defvar org-last-todo-state-is-todo nil
12144 "This is non-nil when the last TODO state change led to a TODO state.
12145 If the last change removed the TODO tag or switched to DONE, then
12146 this is nil.")
12148 (defvar org-setting-tags nil) ; dynamically skipped
12150 (defvar org-todo-setup-filter-hook nil
12151 "Hook for functions that pre-filter todo specs.
12152 Each function takes a todo spec and returns either nil or the spec
12153 transformed into canonical form." )
12155 (defvar org-todo-get-default-hook nil
12156 "Hook for functions that get a default item for todo.
12157 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12158 nil or a string to be used for the todo mark." )
12160 (defvar org-agenda-headline-snapshot-before-repeat)
12162 (defun org-current-effective-time ()
12163 "Return current time adjusted for `org-extend-today-until' variable."
12164 (let* ((ct (org-current-time))
12165 (dct (decode-time ct))
12166 (ct1
12167 (cond
12168 (org-use-last-clock-out-time-as-effective-time
12169 (or (org-clock-get-last-clock-out-time) ct))
12170 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12171 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12172 (t ct))))
12173 ct1))
12175 (defun org-todo-yesterday (&optional arg)
12176 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12177 (interactive "P")
12178 (if (eq major-mode 'org-agenda-mode)
12179 (apply 'org-agenda-todo-yesterday arg)
12180 (let* ((hour (third (decode-time
12181 (org-current-time))))
12182 (org-extend-today-until (1+ hour)))
12183 (org-todo arg))))
12185 (defvar org-block-entry-blocking ""
12186 "First entry preventing the TODO state change.")
12188 (defun org-todo (&optional arg)
12189 "Change the TODO state of an item.
12190 The state of an item is given by a keyword at the start of the heading,
12191 like
12192 *** TODO Write paper
12193 *** DONE Call mom
12195 The different keywords are specified in the variable `org-todo-keywords'.
12196 By default the available states are \"TODO\" and \"DONE\".
12197 So for this example: when the item starts with TODO, it is changed to DONE.
12198 When it starts with DONE, the DONE is removed. And when neither TODO nor
12199 DONE are present, add TODO at the beginning of the heading.
12201 With \\[universal-argument] prefix arg, use completion to determine the new \
12202 state.
12203 With numeric prefix arg, switch to that state.
12204 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12205 keywords (nextset).
12206 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12207 With a numeric prefix arg of 0, inhibit note taking for the change.
12209 For calling through lisp, arg is also interpreted in the following way:
12210 'none -> empty state
12211 \"\"(empty string) -> switch to empty state
12212 'done -> switch to DONE
12213 'nextset -> switch to the next set of keywords
12214 'previousset -> switch to the previous set of keywords
12215 \"WAITING\" -> switch to the specified keyword, but only if it
12216 really is a member of `org-todo-keywords'."
12217 (interactive "P")
12218 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12219 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12220 'region-start-level 'region))
12221 org-loop-over-headlines-in-active-region)
12222 (org-map-entries
12223 `(org-todo ,arg)
12224 org-loop-over-headlines-in-active-region
12225 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12226 (if (equal arg '(16)) (setq arg 'nextset))
12227 (let ((org-blocker-hook org-blocker-hook)
12228 commentp
12229 case-fold-search)
12230 (when (equal arg '(64))
12231 (setq arg nil org-blocker-hook nil))
12232 (when (and org-blocker-hook
12233 (or org-inhibit-blocking
12234 (org-entry-get nil "NOBLOCKING")))
12235 (setq org-blocker-hook nil))
12236 (save-excursion
12237 (catch 'exit
12238 (org-back-to-heading t)
12239 (when (looking-at (concat "^\\*+ " org-comment-string))
12240 (org-toggle-comment)
12241 (setq commentp t))
12242 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12243 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12244 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12245 (let* ((match-data (match-data))
12246 (startpos (point-at-bol))
12247 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12248 (org-log-done org-log-done)
12249 (org-log-repeat org-log-repeat)
12250 (org-todo-log-states org-todo-log-states)
12251 (org-inhibit-logging
12252 (if (equal arg 0)
12253 (progn (setq arg nil) 'note) org-inhibit-logging))
12254 (this (match-string 1))
12255 (hl-pos (match-beginning 0))
12256 (head (org-get-todo-sequence-head this))
12257 (ass (assoc head org-todo-kwd-alist))
12258 (interpret (nth 1 ass))
12259 (done-word (nth 3 ass))
12260 (final-done-word (nth 4 ass))
12261 (org-last-state (or this ""))
12262 (completion-ignore-case t)
12263 (member (member this org-todo-keywords-1))
12264 (tail (cdr member))
12265 (org-state (cond
12266 ((and org-todo-key-trigger
12267 (or (and (equal arg '(4))
12268 (eq org-use-fast-todo-selection 'prefix))
12269 (and (not arg) org-use-fast-todo-selection
12270 (not (eq org-use-fast-todo-selection
12271 'prefix)))))
12272 ;; Use fast selection
12273 (org-fast-todo-selection))
12274 ((and (equal arg '(4))
12275 (or (not org-use-fast-todo-selection)
12276 (not org-todo-key-trigger)))
12277 ;; Read a state with completion
12278 (org-icompleting-read
12279 "State: " (mapcar 'list org-todo-keywords-1)
12280 nil t))
12281 ((eq arg 'right)
12282 (if this
12283 (if tail (car tail) nil)
12284 (car org-todo-keywords-1)))
12285 ((eq arg 'left)
12286 (if (equal member org-todo-keywords-1)
12288 (if this
12289 (nth (- (length org-todo-keywords-1)
12290 (length tail) 2)
12291 org-todo-keywords-1)
12292 (org-last org-todo-keywords-1))))
12293 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12294 (setq arg nil))) ; hack to fall back to cycling
12295 (arg
12296 ;; user or caller requests a specific state
12297 (cond
12298 ((equal arg "") nil)
12299 ((eq arg 'none) nil)
12300 ((eq arg 'done) (or done-word (car org-done-keywords)))
12301 ((eq arg 'nextset)
12302 (or (car (cdr (member head org-todo-heads)))
12303 (car org-todo-heads)))
12304 ((eq arg 'previousset)
12305 (let ((org-todo-heads (reverse org-todo-heads)))
12306 (or (car (cdr (member head org-todo-heads)))
12307 (car org-todo-heads))))
12308 ((car (member arg org-todo-keywords-1)))
12309 ((stringp arg)
12310 (user-error "State `%s' not valid in this file" arg))
12311 ((nth (1- (prefix-numeric-value arg))
12312 org-todo-keywords-1))))
12313 ((null member) (or head (car org-todo-keywords-1)))
12314 ((equal this final-done-word) nil) ;; -> make empty
12315 ((null tail) nil) ;; -> first entry
12316 ((memq interpret '(type priority))
12317 (if (eq this-command last-command)
12318 (car tail)
12319 (if (> (length tail) 0)
12320 (or done-word (car org-done-keywords))
12321 nil)))
12323 (car tail))))
12324 (org-state (or
12325 (run-hook-with-args-until-success
12326 'org-todo-get-default-hook org-state org-last-state)
12327 org-state))
12328 (next (if org-state (concat " " org-state " ") " "))
12329 (change-plist (list :type 'todo-state-change :from this :to org-state
12330 :position startpos))
12331 dolog now-done-p)
12332 (when org-blocker-hook
12333 (setq org-last-todo-state-is-todo
12334 (not (member this org-done-keywords)))
12335 (unless (save-excursion
12336 (save-match-data
12337 (org-with-wide-buffer
12338 (run-hook-with-args-until-failure
12339 'org-blocker-hook change-plist))))
12340 (if (org-called-interactively-p 'interactive)
12341 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12342 this org-state org-block-entry-blocking)
12343 ;; fail silently
12344 (message "TODO state change from %s to %s blocked (by \"%s\")"
12345 this org-state org-block-entry-blocking)
12346 (throw 'exit nil))))
12347 (store-match-data match-data)
12348 (replace-match next t t)
12349 (unless (pos-visible-in-window-p hl-pos)
12350 (message "TODO state changed to %s" (org-trim next)))
12351 (unless head
12352 (setq head (org-get-todo-sequence-head org-state)
12353 ass (assoc head org-todo-kwd-alist)
12354 interpret (nth 1 ass)
12355 done-word (nth 3 ass)
12356 final-done-word (nth 4 ass)))
12357 (when (memq arg '(nextset previousset))
12358 (message "Keyword-Set %d/%d: %s"
12359 (- (length org-todo-sets) -1
12360 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12361 (length org-todo-sets)
12362 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12363 (setq org-last-todo-state-is-todo
12364 (not (member org-state org-done-keywords)))
12365 (setq now-done-p (and (member org-state org-done-keywords)
12366 (not (member this org-done-keywords))))
12367 (and logging (org-local-logging logging))
12368 (when (and (or org-todo-log-states org-log-done)
12369 (not (eq org-inhibit-logging t))
12370 (not (memq arg '(nextset previousset))))
12371 ;; we need to look at recording a time and note
12372 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12373 (nth 2 (assoc this org-todo-log-states))))
12374 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12375 (setq dolog 'time))
12376 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12377 (and org-state
12378 (member org-state org-not-done-keywords)
12379 (not (member this org-not-done-keywords))))
12380 ;; This is now a todo state and was not one before
12381 ;; If there was a CLOSED time stamp, get rid of it.
12382 (org-add-planning-info nil nil 'closed))
12383 (when (and now-done-p org-log-done)
12384 ;; It is now done, and it was not done before
12385 (org-add-planning-info 'closed (org-current-effective-time))
12386 (if (and (not dolog) (eq 'note org-log-done))
12387 (org-add-log-setup 'done org-state this 'findpos 'note)))
12388 (when (and org-state dolog)
12389 ;; This is a non-nil state, and we need to log it
12390 (org-add-log-setup 'state org-state this 'findpos dolog)))
12391 ;; Fixup tag positioning
12392 (org-todo-trigger-tag-changes org-state)
12393 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12394 (when org-provide-todo-statistics
12395 (org-update-parent-todo-statistics))
12396 (run-hooks 'org-after-todo-state-change-hook)
12397 (if (and arg (not (member org-state org-done-keywords)))
12398 (setq head (org-get-todo-sequence-head org-state)))
12399 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12400 ;; Do we need to trigger a repeat?
12401 (when now-done-p
12402 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12403 ;; This is for the agenda, take a snapshot of the headline.
12404 (save-match-data
12405 (setq org-agenda-headline-snapshot-before-repeat
12406 (org-get-heading))))
12407 (org-auto-repeat-maybe org-state))
12408 ;; Fixup cursor location if close to the keyword
12409 (if (and (outline-on-heading-p)
12410 (not (bolp))
12411 (save-excursion (beginning-of-line 1)
12412 (looking-at org-todo-line-regexp))
12413 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12414 (progn
12415 (goto-char (or (match-end 2) (match-end 1)))
12416 (and (looking-at " ") (just-one-space))))
12417 (when org-trigger-hook
12418 (save-excursion
12419 (run-hook-with-args 'org-trigger-hook change-plist)))
12420 (when commentp (org-toggle-comment))))))))
12422 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12423 "Block turning an entry into a TODO, using the hierarchy.
12424 This checks whether the current task should be blocked from state
12425 changes. Such blocking occurs when:
12427 1. The task has children which are not all in a completed state.
12429 2. A task has a parent with the property :ORDERED:, and there
12430 are siblings prior to the current task with incomplete
12431 status.
12433 3. The parent of the task is blocked because it has siblings that should
12434 be done first, or is child of a block grandparent TODO entry."
12436 (if (not org-enforce-todo-dependencies)
12437 t ; if locally turned off don't block
12438 (catch 'dont-block
12439 ;; If this is not a todo state change, or if this entry is already DONE,
12440 ;; do not block
12441 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12442 (member (plist-get change-plist :from)
12443 (cons 'done org-done-keywords))
12444 (member (plist-get change-plist :to)
12445 (cons 'todo org-not-done-keywords))
12446 (not (plist-get change-plist :to)))
12447 (throw 'dont-block t))
12448 ;; If this task has children, and any are undone, it's blocked
12449 (save-excursion
12450 (org-back-to-heading t)
12451 (let ((this-level (funcall outline-level)))
12452 (outline-next-heading)
12453 (let ((child-level (funcall outline-level)))
12454 (while (and (not (eobp))
12455 (> child-level this-level))
12456 ;; this todo has children, check whether they are all
12457 ;; completed
12458 (if (and (not (org-entry-is-done-p))
12459 (org-entry-is-todo-p))
12460 (progn (setq org-block-entry-blocking (org-get-heading))
12461 (throw 'dont-block nil)))
12462 (outline-next-heading)
12463 (setq child-level (funcall outline-level))))))
12464 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12465 ;; any previous siblings are undone, it's blocked
12466 (save-excursion
12467 (org-back-to-heading t)
12468 (let* ((pos (point))
12469 (parent-pos (and (org-up-heading-safe) (point))))
12470 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12471 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12472 (forward-line 1)
12473 (re-search-forward org-not-done-heading-regexp pos t))
12474 (setq org-block-entry-blocking (match-string 0))
12475 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12476 ;; Search further up the hierarchy, to see if an ancestor is blocked
12477 (while t
12478 (goto-char parent-pos)
12479 (if (not (looking-at org-not-done-heading-regexp))
12480 (throw 'dont-block t)) ; do not block, parent is not a TODO
12481 (setq pos (point))
12482 (setq parent-pos (and (org-up-heading-safe) (point)))
12483 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12484 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12485 (forward-line 1)
12486 (re-search-forward org-not-done-heading-regexp pos t)
12487 (setq org-block-entry-blocking (org-get-heading)))
12488 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12490 (defcustom org-track-ordered-property-with-tag nil
12491 "Should the ORDERED property also be shown as a tag?
12492 The ORDERED property decides if an entry should require subtasks to be
12493 completed in sequence. Since a property is not very visible, setting
12494 this option means that toggling the ORDERED property with the command
12495 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12496 not relevant for the behavior, but it makes things more visible.
12498 Note that toggling the tag with tags commands will not change the property
12499 and therefore not influence behavior!
12501 This can be t, meaning the tag ORDERED should be used, It can also be a
12502 string to select a different tag for this task."
12503 :group 'org-todo
12504 :type '(choice
12505 (const :tag "No tracking" nil)
12506 (const :tag "Track with ORDERED tag" t)
12507 (string :tag "Use other tag")))
12509 (defun org-toggle-ordered-property ()
12510 "Toggle the ORDERED property of the current entry.
12511 For better visibility, you can track the value of this property with a tag.
12512 See variable `org-track-ordered-property-with-tag'."
12513 (interactive)
12514 (let* ((t1 org-track-ordered-property-with-tag)
12515 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12516 (save-excursion
12517 (org-back-to-heading)
12518 (if (org-entry-get nil "ORDERED")
12519 (progn
12520 (org-delete-property "ORDERED" "PROPERTIES")
12521 (and tag (org-toggle-tag tag 'off))
12522 (message "Subtasks can be completed in arbitrary order"))
12523 (org-entry-put nil "ORDERED" "t")
12524 (and tag (org-toggle-tag tag 'on))
12525 (message "Subtasks must be completed in sequence")))))
12527 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12528 (defun org-block-todo-from-checkboxes (change-plist)
12529 "Block turning an entry into a TODO, using checkboxes.
12530 This checks whether the current task should be blocked from state
12531 changes because there are unchecked boxes in this entry."
12532 (if (not org-enforce-todo-checkbox-dependencies)
12533 t ; if locally turned off don't block
12534 (catch 'dont-block
12535 ;; If this is not a todo state change, or if this entry is already DONE,
12536 ;; do not block
12537 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12538 (member (plist-get change-plist :from)
12539 (cons 'done org-done-keywords))
12540 (member (plist-get change-plist :to)
12541 (cons 'todo org-not-done-keywords))
12542 (not (plist-get change-plist :to)))
12543 (throw 'dont-block t))
12544 ;; If this task has checkboxes that are not checked, it's blocked
12545 (save-excursion
12546 (org-back-to-heading t)
12547 (let ((beg (point)) end)
12548 (outline-next-heading)
12549 (setq end (point))
12550 (goto-char beg)
12551 (if (org-list-search-forward
12552 (concat (org-item-beginning-re)
12553 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12554 "\\[[- ]\\]")
12555 end t)
12556 (progn
12557 (if (boundp 'org-blocked-by-checkboxes)
12558 (setq org-blocked-by-checkboxes t))
12559 (throw 'dont-block nil)))))
12560 t))) ; do not block
12562 (defun org-entry-blocked-p ()
12563 "Is the current entry blocked?"
12564 (org-with-silent-modifications
12565 (if (org-entry-get nil "NOBLOCKING")
12566 nil ;; Never block this entry
12567 (not (run-hook-with-args-until-failure
12568 'org-blocker-hook
12569 (list :type 'todo-state-change
12570 :position (point)
12571 :from 'todo
12572 :to 'done))))))
12574 (defun org-update-statistics-cookies (all)
12575 "Update the statistics cookie, either from TODO or from checkboxes.
12576 This should be called with the cursor in a line with a statistics cookie."
12577 (interactive "P")
12578 (if all
12579 (progn
12580 (org-update-checkbox-count 'all)
12581 (org-map-entries 'org-update-parent-todo-statistics))
12582 (if (not (org-at-heading-p))
12583 (org-update-checkbox-count)
12584 (let ((pos (point-marker))
12585 end l1 l2)
12586 (ignore-errors (org-back-to-heading t))
12587 (if (not (org-at-heading-p))
12588 (org-update-checkbox-count)
12589 (setq l1 (org-outline-level))
12590 (setq end (save-excursion
12591 (outline-next-heading)
12592 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12593 (point)))
12594 (if (and (save-excursion
12595 (re-search-forward
12596 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12597 (not (save-excursion (re-search-forward
12598 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12599 (org-update-checkbox-count)
12600 (if (and l2 (> l2 l1))
12601 (progn
12602 (goto-char end)
12603 (org-update-parent-todo-statistics))
12604 (goto-char pos)
12605 (beginning-of-line 1)
12606 (while (re-search-forward
12607 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12608 (point-at-eol) t)
12609 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12610 (goto-char pos)
12611 (move-marker pos nil)))))
12613 (defvar org-entry-property-inherited-from) ;; defined below
12614 (defun org-update-parent-todo-statistics ()
12615 "Update any statistics cookie in the parent of the current headline.
12616 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12617 the entire subtree and this will travel up the hierarchy and update
12618 statistics everywhere."
12619 (let* ((prop (save-excursion (org-up-heading-safe)
12620 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12621 (recursive (or (not org-hierarchical-todo-statistics)
12622 (and prop (string-match "\\<recursive\\>" prop))))
12623 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12625 (first t)
12626 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12627 level ltoggle l1 new ndel
12628 (cnt-all 0) (cnt-done 0) is-percent kwd
12629 checkbox-beg ov ovs ove cookie-present)
12630 (catch 'exit
12631 (save-excursion
12632 (beginning-of-line 1)
12633 (setq ltoggle (funcall outline-level))
12634 ;; Three situations are to consider:
12636 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12637 ;; to the top-level ancestor on the headline;
12639 ;; 2. If parent has "recursive" property, repeat up to the
12640 ;; headline setting that property, taking inheritance into
12641 ;; account;
12643 ;; 3. Else, move up to direct parent and proceed only once.
12644 (while (and (setq level (org-up-heading-safe))
12645 (or recursive first)
12646 (>= (point) lim))
12647 (setq first nil cookie-present nil)
12648 (unless (and level
12649 (not (string-match
12650 "\\<checkbox\\>"
12651 (downcase (or (org-entry-get nil "COOKIE_DATA")
12652 "")))))
12653 (throw 'exit nil))
12654 (while (re-search-forward box-re (point-at-eol) t)
12655 (setq cnt-all 0 cnt-done 0 cookie-present t)
12656 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12657 (save-match-data
12658 (unless (outline-next-heading) (throw 'exit nil))
12659 (while (and (looking-at org-complex-heading-regexp)
12660 (> (setq l1 (length (match-string 1))) level))
12661 (setq kwd (and (or recursive (= l1 ltoggle))
12662 (match-string 2)))
12663 (if (or (eq org-provide-todo-statistics 'all-headlines)
12664 (and (listp org-provide-todo-statistics)
12665 (or (member kwd org-provide-todo-statistics)
12666 (member kwd org-done-keywords))))
12667 (setq cnt-all (1+ cnt-all))
12668 (if (eq org-provide-todo-statistics t)
12669 (and kwd (setq cnt-all (1+ cnt-all)))))
12670 (and (member kwd org-done-keywords)
12671 (setq cnt-done (1+ cnt-done)))
12672 (outline-next-heading)))
12673 (setq new
12674 (if is-percent
12675 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12676 (format "[%d/%d]" cnt-done cnt-all))
12677 ndel (- (match-end 0) checkbox-beg))
12678 ;; handle overlays when updating cookie from column view
12679 (when (setq ov (car (overlays-at checkbox-beg)))
12680 (setq ovs (overlay-start ov) ove (overlay-end ov))
12681 (delete-overlay ov))
12682 (goto-char checkbox-beg)
12683 (insert new)
12684 (delete-region (point) (+ (point) ndel))
12685 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12686 (when ov (move-overlay ov ovs ove)))
12687 (when cookie-present
12688 (run-hook-with-args 'org-after-todo-statistics-hook
12689 cnt-done (- cnt-all cnt-done))))))
12690 (run-hooks 'org-todo-statistics-hook)))
12692 (defvar org-after-todo-statistics-hook nil
12693 "Hook that is called after a TODO statistics cookie has been updated.
12694 Each function is called with two arguments: the number of not-done entries
12695 and the number of done entries.
12697 For example, the following function, when added to this hook, will switch
12698 an entry to DONE when all children are done, and back to TODO when new
12699 entries are set to a TODO status. Note that this hook is only called
12700 when there is a statistics cookie in the headline!
12702 (defun org-summary-todo (n-done n-not-done)
12703 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12704 (let (org-log-done org-log-states) ; turn off logging
12705 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12708 (defvar org-todo-statistics-hook nil
12709 "Hook that is run whenever Org thinks TODO statistics should be updated.
12710 This hook runs even if there is no statistics cookie present, in which case
12711 `org-after-todo-statistics-hook' would not run.")
12713 (defun org-todo-trigger-tag-changes (state)
12714 "Apply the changes defined in `org-todo-state-tags-triggers'."
12715 (let ((l org-todo-state-tags-triggers)
12716 changes)
12717 (when (or (not state) (equal state ""))
12718 (setq changes (append changes (cdr (assoc "" l)))))
12719 (when (and (stringp state) (> (length state) 0))
12720 (setq changes (append changes (cdr (assoc state l)))))
12721 (when (member state org-not-done-keywords)
12722 (setq changes (append changes (cdr (assoc 'todo l)))))
12723 (when (member state org-done-keywords)
12724 (setq changes (append changes (cdr (assoc 'done l)))))
12725 (dolist (c changes)
12726 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12728 (defun org-local-logging (value)
12729 "Get logging settings from a property VALUE."
12730 (let* (words w a)
12731 ;; directly set the variables, they are already local.
12732 (setq org-log-done nil
12733 org-log-repeat nil
12734 org-todo-log-states nil)
12735 (setq words (org-split-string value))
12736 (while (setq w (pop words))
12737 (cond
12738 ((setq a (assoc w org-startup-options))
12739 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12740 (set (nth 1 a) (nth 2 a))))
12741 ((setq a (org-extract-log-state-settings w))
12742 (and (member (car a) org-todo-keywords-1)
12743 (push a org-todo-log-states)))))))
12745 (defun org-get-todo-sequence-head (kwd)
12746 "Return the head of the TODO sequence to which KWD belongs.
12747 If KWD is not set, check if there is a text property remembering the
12748 right sequence."
12749 (let (p)
12750 (cond
12751 ((not kwd)
12752 (or (get-text-property (point-at-bol) 'org-todo-head)
12753 (progn
12754 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12755 nil (point-at-eol)))
12756 (get-text-property p 'org-todo-head))))
12757 ((not (member kwd org-todo-keywords-1))
12758 (car org-todo-keywords-1))
12759 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12761 (defun org-fast-todo-selection ()
12762 "Fast TODO keyword selection with single keys.
12763 Returns the new TODO keyword, or nil if no state change should occur."
12764 (let* ((fulltable org-todo-key-alist)
12765 (done-keywords org-done-keywords) ;; needed for the faces.
12766 (maxlen (apply 'max (mapcar
12767 (lambda (x)
12768 (if (stringp (car x)) (string-width (car x)) 0))
12769 fulltable)))
12770 (expert nil)
12771 (fwidth (+ maxlen 3 1 3))
12772 (ncol (/ (- (window-width) 4) fwidth))
12773 tg cnt e c tbl
12774 groups ingroup)
12775 (save-excursion
12776 (save-window-excursion
12777 (if expert
12778 (set-buffer (get-buffer-create " *Org todo*"))
12779 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12780 (erase-buffer)
12781 (org-set-local 'org-done-keywords done-keywords)
12782 (setq tbl fulltable cnt 0)
12783 (while (setq e (pop tbl))
12784 (cond
12785 ((equal e '(:startgroup))
12786 (push '() groups) (setq ingroup t)
12787 (when (not (= cnt 0))
12788 (setq cnt 0)
12789 (insert "\n"))
12790 (insert "{ "))
12791 ((equal e '(:endgroup))
12792 (setq ingroup nil cnt 0)
12793 (insert "}\n"))
12794 ((equal e '(:newline))
12795 (when (not (= cnt 0))
12796 (setq cnt 0)
12797 (insert "\n")
12798 (setq e (car tbl))
12799 (while (equal (car tbl) '(:newline))
12800 (insert "\n")
12801 (setq tbl (cdr tbl)))))
12803 (setq tg (car e) c (cdr e))
12804 (if ingroup (push tg (car groups)))
12805 (setq tg (org-add-props tg nil 'face
12806 (org-get-todo-face tg)))
12807 (if (and (= cnt 0) (not ingroup)) (insert " "))
12808 (insert "[" c "] " tg (make-string
12809 (- fwidth 4 (length tg)) ?\ ))
12810 (when (= (setq cnt (1+ cnt)) ncol)
12811 (insert "\n")
12812 (if ingroup (insert " "))
12813 (setq cnt 0)))))
12814 (insert "\n")
12815 (goto-char (point-min))
12816 (if (not expert) (org-fit-window-to-buffer))
12817 (message "[a-z..]:Set [SPC]:clear")
12818 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12819 (cond
12820 ((or (= c ?\C-g)
12821 (and (= c ?q) (not (rassoc c fulltable))))
12822 (setq quit-flag t))
12823 ((= c ?\ ) nil)
12824 ((setq e (rassoc c fulltable) tg (car e))
12826 (t (setq quit-flag t)))))))
12828 (defun org-entry-is-todo-p ()
12829 (member (org-get-todo-state) org-not-done-keywords))
12831 (defun org-entry-is-done-p ()
12832 (member (org-get-todo-state) org-done-keywords))
12834 (defun org-get-todo-state ()
12835 "Return the TODO keyword of the current subtree."
12836 (save-excursion
12837 (org-back-to-heading t)
12838 (and (looking-at org-todo-line-regexp)
12839 (match-end 2)
12840 (match-string 2))))
12842 (defun org-at-date-range-p (&optional inactive-ok)
12843 "Is the cursor inside a date range?"
12844 (interactive)
12845 (save-excursion
12846 (catch 'exit
12847 (let ((pos (point)))
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 (skip-chars-backward "^<[\r\n")
12854 (skip-chars-backward "<[")
12855 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12856 (>= (match-end 0) pos)
12857 (throw 'exit t)))
12858 nil)))
12860 (defun org-get-repeat (&optional tagline)
12861 "Check if there is a deadline/schedule with repeater in this entry."
12862 (save-match-data
12863 (save-excursion
12864 (org-back-to-heading t)
12865 (and (re-search-forward (if tagline
12866 (concat tagline "\\s-*" org-repeat-re)
12867 org-repeat-re)
12868 (org-entry-end-position) t)
12869 (match-string-no-properties 1)))))
12871 (defvar org-last-changed-timestamp)
12872 (defvar org-last-inserted-timestamp)
12873 (defvar org-log-post-message)
12874 (defvar org-log-note-purpose)
12875 (defvar org-log-note-how)
12876 (defvar org-log-note-extra)
12877 (defun org-auto-repeat-maybe (done-word)
12878 "Check if the current headline contains a repeated deadline/schedule.
12879 If yes, set TODO state back to what it was and change the base date
12880 of repeating deadline/scheduled time stamps to new date.
12881 This function is run automatically after each state change to a DONE state."
12882 ;; last-state is dynamically scoped into this function
12883 (let* ((repeat (org-get-repeat))
12884 (aa (assoc org-last-state org-todo-kwd-alist))
12885 (interpret (nth 1 aa))
12886 (head (nth 2 aa))
12887 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12888 (msg "Entry repeats: ")
12889 (org-log-done nil)
12890 (org-todo-log-states nil)
12891 re type n what ts time to-state)
12892 (when repeat
12893 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12894 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12895 org-todo-repeat-to-state))
12896 (unless (and to-state (member to-state org-todo-keywords-1))
12897 (setq to-state (if (eq interpret 'type) org-last-state head)))
12898 (org-todo to-state)
12899 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12900 (org-entry-put nil "LAST_REPEAT" (format-time-string
12901 (org-time-stamp-format t t))))
12902 (when org-log-repeat
12903 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12904 (memq 'org-add-log-note post-command-hook))
12905 ;; OK, we are already setup for some record
12906 (if (eq org-log-repeat 'note)
12907 ;; make sure we take a note, not only a time stamp
12908 (setq org-log-note-how 'note))
12909 ;; Set up for taking a record
12910 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12911 org-last-state
12912 'findpos org-log-repeat)))
12913 (org-back-to-heading t)
12914 (org-add-planning-info nil nil 'closed)
12915 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12916 org-deadline-time-regexp "\\)\\|\\("
12917 org-ts-regexp "\\)"))
12918 (while (re-search-forward
12919 re (save-excursion (outline-next-heading) (point)) t)
12920 (setq type (if (match-end 1) org-scheduled-string
12921 (if (match-end 3) org-deadline-string "Plain:"))
12922 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12923 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12924 (setq n (string-to-number (match-string 2 ts))
12925 what (match-string 3 ts))
12926 (if (equal what "w") (setq n (* n 7) what "d"))
12927 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12928 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12929 ;; Preparation, see if we need to modify the start date for the change
12930 (when (match-end 1)
12931 (setq time (save-match-data (org-time-string-to-time ts)))
12932 (cond
12933 ((equal (match-string 1 ts) ".")
12934 ;; Shift starting date to today
12935 (org-timestamp-change
12936 (- (org-today) (time-to-days time))
12937 'day))
12938 ((equal (match-string 1 ts) "+")
12939 (let ((nshiftmax 10) (nshift 0))
12940 (while (or (= nshift 0)
12941 (<= (time-to-days time)
12942 (time-to-days (current-time))))
12943 (when (= (incf nshift) nshiftmax)
12944 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12945 (error "Abort")))
12946 (org-timestamp-change n (cdr (assoc what whata)))
12947 (org-at-timestamp-p t)
12948 (setq ts (match-string 1))
12949 (setq time (save-match-data (org-time-string-to-time ts)))))
12950 (org-timestamp-change (- n) (cdr (assoc what whata)))
12951 ;; rematch, so that we have everything in place for the real shift
12952 (org-at-timestamp-p t)
12953 (setq ts (match-string 1))
12954 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12955 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12956 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12957 (setq org-log-post-message msg)
12958 (message "%s" msg))))
12960 (defun org-show-todo-tree (arg)
12961 "Make a compact tree which shows all headlines marked with TODO.
12962 The tree will show the lines where the regexp matches, and all higher
12963 headlines above the match.
12964 With a \\[universal-argument] prefix, prompt for a regexp to match.
12965 With a numeric prefix N, construct a sparse tree for the Nth element
12966 of `org-todo-keywords-1'."
12967 (interactive "P")
12968 (let ((case-fold-search nil)
12969 (kwd-re
12970 (cond ((null arg) org-not-done-regexp)
12971 ((equal arg '(4))
12972 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12973 (mapcar 'list org-todo-keywords-1))))
12974 (concat "\\("
12975 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12976 "\\)\\>")))
12977 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12978 (regexp-quote (nth (1- (prefix-numeric-value arg))
12979 org-todo-keywords-1)))
12980 (t (user-error "Invalid prefix argument: %s" arg)))))
12981 (message "%d TODO entries found"
12982 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12984 (defun org-deadline (arg &optional time)
12985 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12986 With one universal prefix argument, remove any deadline from the item.
12987 With two universal prefix arguments, prompt for a warning delay.
12988 With argument TIME, set the deadline at the corresponding date. TIME
12989 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12990 (interactive "P")
12991 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12992 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12993 'region-start-level 'region))
12994 org-loop-over-headlines-in-active-region)
12995 (org-map-entries
12996 `(org-deadline ',arg ,time)
12997 org-loop-over-headlines-in-active-region
12998 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12999 (let* ((old-date (org-entry-get nil "DEADLINE"))
13000 (old-date-time (if old-date (org-time-string-to-time old-date)))
13001 (repeater (and old-date
13002 (string-match
13003 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13004 old-date)
13005 (match-string 1 old-date))))
13006 (cond
13007 ((equal arg '(4))
13008 (when (and old-date org-log-redeadline)
13009 (org-add-log-setup 'deldeadline nil old-date 'findpos
13010 org-log-redeadline))
13011 (org-remove-timestamp-with-keyword org-deadline-string)
13012 (message "Item no longer has a deadline."))
13013 ((equal arg '(16))
13014 (save-excursion
13015 (org-back-to-heading t)
13016 (if (re-search-forward
13017 org-deadline-time-regexp
13018 (save-excursion (outline-next-heading) (point)) t)
13019 (let* ((rpl0 (match-string 1))
13020 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13021 (replace-match
13022 (concat org-deadline-string
13023 " <" rpl
13024 (format " -%dd"
13025 (abs
13026 (- (time-to-days
13027 (save-match-data
13028 (org-read-date nil t nil "Warn starting from" old-date-time)))
13029 (time-to-days old-date-time))))
13030 ">") t t))
13031 (user-error "No deadline information to update"))))
13033 (org-add-planning-info 'deadline time 'closed)
13034 (when (and old-date org-log-redeadline
13035 (not (equal old-date
13036 (substring org-last-inserted-timestamp 1 -1))))
13037 (org-add-log-setup 'redeadline nil old-date 'findpos
13038 org-log-redeadline))
13039 (when repeater
13040 (save-excursion
13041 (org-back-to-heading t)
13042 (when (re-search-forward (concat org-deadline-string " "
13043 org-last-inserted-timestamp)
13044 (save-excursion
13045 (outline-next-heading) (point)) t)
13046 (goto-char (1- (match-end 0)))
13047 (insert " " repeater)
13048 (setq org-last-inserted-timestamp
13049 (concat (substring org-last-inserted-timestamp 0 -1)
13050 " " repeater
13051 (substring org-last-inserted-timestamp -1))))))
13052 (message "Deadline on %s" org-last-inserted-timestamp))))))
13054 (defun org-schedule (arg &optional time)
13055 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13056 With one universal prefix argument, remove any scheduling date from the item.
13057 With two universal prefix arguments, prompt for a delay cookie.
13058 With argument TIME, scheduled at the corresponding date. TIME can
13059 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13060 (interactive "P")
13061 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13062 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13063 'region-start-level 'region))
13064 org-loop-over-headlines-in-active-region)
13065 (org-map-entries
13066 `(org-schedule ',arg ,time)
13067 org-loop-over-headlines-in-active-region
13068 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13069 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13070 (old-date-time (if old-date (org-time-string-to-time old-date)))
13071 (repeater (and old-date
13072 (string-match
13073 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13074 old-date)
13075 (match-string 1 old-date))))
13076 (cond
13077 ((equal arg '(4))
13078 (progn
13079 (when (and old-date org-log-reschedule)
13080 (org-add-log-setup 'delschedule nil old-date 'findpos
13081 org-log-reschedule))
13082 (org-remove-timestamp-with-keyword org-scheduled-string)
13083 (message "Item is no longer scheduled.")))
13084 ((equal arg '(16))
13085 (save-excursion
13086 (org-back-to-heading t)
13087 (if (re-search-forward
13088 org-scheduled-time-regexp
13089 (save-excursion (outline-next-heading) (point)) t)
13090 (let* ((rpl0 (match-string 1))
13091 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13092 (replace-match
13093 (concat org-scheduled-string
13094 " <" rpl
13095 (format " -%dd"
13096 (abs
13097 (- (time-to-days
13098 (save-match-data
13099 (org-read-date nil t nil "Delay until" old-date-time)))
13100 (time-to-days old-date-time))))
13101 ">") t t))
13102 (user-error "No scheduled information to update"))))
13104 (org-add-planning-info 'scheduled time 'closed)
13105 (when (and old-date org-log-reschedule
13106 (not (equal old-date
13107 (substring org-last-inserted-timestamp 1 -1))))
13108 (org-add-log-setup 'reschedule nil old-date 'findpos
13109 org-log-reschedule))
13110 (when repeater
13111 (save-excursion
13112 (org-back-to-heading t)
13113 (when (re-search-forward (concat org-scheduled-string " "
13114 org-last-inserted-timestamp)
13115 (save-excursion
13116 (outline-next-heading) (point)) t)
13117 (goto-char (1- (match-end 0)))
13118 (insert " " repeater)
13119 (setq org-last-inserted-timestamp
13120 (concat (substring org-last-inserted-timestamp 0 -1)
13121 " " repeater
13122 (substring org-last-inserted-timestamp -1))))))
13123 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13125 (defun org-get-scheduled-time (pom &optional inherit)
13126 "Get the scheduled time as a time tuple, of a format suitable
13127 for calling org-schedule with, or if there is no scheduling,
13128 returns nil."
13129 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13130 (when time
13131 (apply 'encode-time (org-parse-time-string time)))))
13133 (defun org-get-deadline-time (pom &optional inherit)
13134 "Get the deadline as a time tuple, of a format suitable for
13135 calling org-deadline with, or if there is no scheduling, returns
13136 nil."
13137 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13138 (when time
13139 (apply 'encode-time (org-parse-time-string time)))))
13141 (defun org-remove-timestamp-with-keyword (keyword)
13142 "Remove all time stamps with KEYWORD in the current entry."
13143 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13144 beg)
13145 (save-excursion
13146 (org-back-to-heading t)
13147 (setq beg (point))
13148 (outline-next-heading)
13149 (while (re-search-backward re beg t)
13150 (replace-match "")
13151 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13152 (equal (char-before) ?\ ))
13153 (backward-delete-char 1)
13154 (if (string-match "^[ \t]*$" (buffer-substring
13155 (point-at-bol) (point-at-eol)))
13156 (delete-region (point-at-bol)
13157 (min (point-max) (1+ (point-at-eol))))))))))
13159 (defvar org-time-was-given) ; dynamically scoped parameter
13160 (defvar org-end-time-was-given) ; dynamically scoped parameter
13162 (defun org-add-planning-info (what &optional time &rest remove)
13163 "Insert new timestamp with keyword in the line directly after the headline.
13164 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13165 If non is given, the user is prompted for a date.
13166 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13167 be removed."
13168 (interactive)
13169 (let (org-time-was-given org-end-time-was-given ts
13170 end default-time default-input)
13172 (catch 'exit
13173 (when (and (memq what '(scheduled deadline))
13174 (or (not time)
13175 (and (stringp time)
13176 (string-match "^[-+]+[0-9]" time))))
13177 ;; Try to get a default date/time from existing timestamp
13178 (save-excursion
13179 (org-back-to-heading t)
13180 (setq end (save-excursion (outline-next-heading) (point)))
13181 (when (re-search-forward (if (eq what 'scheduled)
13182 org-scheduled-time-regexp
13183 org-deadline-time-regexp)
13184 end t)
13185 (setq ts (match-string 1)
13186 default-time
13187 (apply 'encode-time (org-parse-time-string ts))
13188 default-input (and ts (org-get-compact-tod ts))))))
13189 (when what
13190 (setq time
13191 (if (stringp time)
13192 ;; This is a string (relative or absolute), set proper date
13193 (apply 'encode-time
13194 (org-read-date-analyze
13195 time default-time (decode-time default-time)))
13196 ;; If necessary, get the time from the user
13197 (or time (org-read-date nil 'to-time nil nil
13198 default-time default-input)))))
13200 (when (and org-insert-labeled-timestamps-at-point
13201 (member what '(scheduled deadline)))
13202 (insert
13203 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13204 (org-insert-time-stamp time org-time-was-given
13205 nil nil nil (list org-end-time-was-given))
13206 (setq what nil))
13207 (save-excursion
13208 (save-restriction
13209 (let (col list elt ts buffer-invisibility-spec)
13210 (org-back-to-heading t)
13211 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13212 (goto-char (match-end 1))
13213 (setq col (current-column))
13214 (goto-char (match-end 0))
13215 (if (eobp) (insert "\n") (forward-char 1))
13216 (when (and (not what)
13217 (not (looking-at
13218 (concat "[ \t]*"
13219 org-keyword-time-not-clock-regexp))))
13220 ;; Nothing to add, nothing to remove...... :-)
13221 (throw 'exit nil))
13222 (if (and (not (looking-at org-outline-regexp))
13223 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13224 "[^\r\n]*"))
13225 (not (equal (match-string 1) org-clock-string)))
13226 (narrow-to-region (match-beginning 0) (match-end 0))
13227 (insert-before-markers "\n")
13228 (backward-char 1)
13229 (narrow-to-region (point) (point))
13230 (and org-adapt-indentation (org-indent-to-column col)))
13231 ;; Check if we have to remove something.
13232 (setq list (cons what remove))
13233 (while list
13234 (setq elt (pop list))
13235 (when (or (and (eq elt 'scheduled)
13236 (re-search-forward org-scheduled-time-regexp nil t))
13237 (and (eq elt 'deadline)
13238 (re-search-forward org-deadline-time-regexp nil t))
13239 (and (eq elt 'closed)
13240 (re-search-forward org-closed-time-regexp nil t)))
13241 (replace-match "")
13242 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13243 (and (looking-at "[ \t]+") (replace-match ""))
13244 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13245 (when what
13246 (insert
13247 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13248 (cond ((eq what 'scheduled) org-scheduled-string)
13249 ((eq what 'deadline) org-deadline-string)
13250 ((eq what 'closed) org-closed-string))
13251 " ")
13252 (setq ts (org-insert-time-stamp
13253 time
13254 (or org-time-was-given
13255 (and (eq what 'closed) org-log-done-with-time))
13256 (eq what 'closed)
13257 nil nil (list org-end-time-was-given)))
13258 (insert
13259 (if (not (or (bolp) (eq (char-before) ?\ )
13260 (memq (char-after) '(32 10))
13261 (eobp))) " " ""))
13262 (end-of-line 1))
13263 (goto-char (point-min))
13264 (widen)
13265 (if (and (looking-at "[ \t]*\n")
13266 (equal (char-before) ?\n))
13267 (delete-region (1- (point)) (point-at-eol)))
13268 ts))))))
13270 (defvar org-log-note-marker (make-marker))
13271 (defvar org-log-note-purpose nil)
13272 (defvar org-log-note-state nil)
13273 (defvar org-log-note-previous-state nil)
13274 (defvar org-log-note-how nil)
13275 (defvar org-log-note-extra nil)
13276 (defvar org-log-note-window-configuration nil)
13277 (defvar org-log-note-return-to (make-marker))
13278 (defvar org-log-note-effective-time nil
13279 "Remembered current time so that dynamically scoped
13280 `org-extend-today-until' affects tha timestamps in state change
13281 log")
13283 (defvar org-log-post-message nil
13284 "Message to be displayed after a log note has been stored.
13285 The auto-repeater uses this.")
13287 (defun org-add-note ()
13288 "Add a note to the current entry.
13289 This is done in the same way as adding a state change note."
13290 (interactive)
13291 (org-add-log-setup 'note nil nil 'findpos nil))
13293 (defvar org-property-end-re)
13294 (defun org-add-log-setup (&optional purpose state prev-state
13295 findpos how extra)
13296 "Set up the post command hook to take a note.
13297 If this is about to TODO state change, the new state is expected in STATE.
13298 When FINDPOS is non-nil, find the correct position for the note in
13299 the current entry. If not, assume that it can be inserted at point.
13300 HOW is an indicator what kind of note should be created.
13301 EXTRA is additional text that will be inserted into the notes buffer."
13302 (let* ((org-log-into-drawer (org-log-into-drawer))
13303 (drawer (cond ((stringp org-log-into-drawer)
13304 org-log-into-drawer)
13305 (org-log-into-drawer "LOGBOOK"))))
13306 (save-restriction
13307 (save-excursion
13308 (when findpos
13309 (org-back-to-heading t)
13310 (narrow-to-region (point) (save-excursion
13311 (outline-next-heading) (point)))
13312 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13313 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13314 "[^\r\n]*\\)?"))
13315 (goto-char (match-end 0))
13316 (cond
13317 (drawer
13318 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13319 nil t)
13320 (progn
13321 (goto-char (match-end 0))
13322 (or org-log-states-order-reversed
13323 (and (re-search-forward org-property-end-re nil t)
13324 (goto-char (1- (match-beginning 0))))))
13325 (insert "\n:" drawer ":\n:END:")
13326 (beginning-of-line 0)
13327 (org-indent-line)
13328 (beginning-of-line 2)
13329 (org-indent-line)
13330 (end-of-line 0)))
13331 ((and org-log-state-notes-insert-after-drawers
13332 (save-excursion
13333 (forward-line) (looking-at org-drawer-regexp)))
13334 (forward-line)
13335 (while (looking-at org-drawer-regexp)
13336 (goto-char (match-end 0))
13337 (re-search-forward org-property-end-re (point-max) t)
13338 (forward-line))
13339 (forward-line -1)))
13340 (unless org-log-states-order-reversed
13341 (and (= (char-after) ?\n) (forward-char 1))
13342 (org-skip-over-state-notes)
13343 (skip-chars-backward " \t\n\r")))
13344 (move-marker org-log-note-marker (point))
13345 (setq org-log-note-purpose purpose
13346 org-log-note-state state
13347 org-log-note-previous-state prev-state
13348 org-log-note-how how
13349 org-log-note-extra extra
13350 org-log-note-effective-time (org-current-effective-time))
13351 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13353 (defun org-skip-over-state-notes ()
13354 "Skip past the list of State notes in an entry."
13355 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13356 (when (ignore-errors (goto-char (org-in-item-p)))
13357 (let* ((struct (org-list-struct))
13358 (prevs (org-list-prevs-alist struct)))
13359 (while (looking-at "[ \t]*- State")
13360 (goto-char (or (org-list-get-next-item (point) struct prevs)
13361 (org-list-get-item-end (point) struct)))))))
13363 (defun org-add-log-note (&optional purpose)
13364 "Pop up a window for taking a note, and add this note later at point."
13365 (remove-hook 'post-command-hook 'org-add-log-note)
13366 (setq org-log-note-window-configuration (current-window-configuration))
13367 (delete-other-windows)
13368 (move-marker org-log-note-return-to (point))
13369 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13370 (goto-char org-log-note-marker)
13371 (org-switch-to-buffer-other-window "*Org Note*")
13372 (erase-buffer)
13373 (if (memq org-log-note-how '(time state))
13374 (let (current-prefix-arg) (org-store-log-note))
13375 (let ((org-inhibit-startup t)) (org-mode))
13376 (insert (format "# Insert note for %s.
13377 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13378 (cond
13379 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13380 ((eq org-log-note-purpose 'done) "closed todo item")
13381 ((eq org-log-note-purpose 'state)
13382 (format "state change from \"%s\" to \"%s\""
13383 (or org-log-note-previous-state "")
13384 (or org-log-note-state "")))
13385 ((eq org-log-note-purpose 'reschedule)
13386 "rescheduling")
13387 ((eq org-log-note-purpose 'delschedule)
13388 "no longer scheduled")
13389 ((eq org-log-note-purpose 'redeadline)
13390 "changing deadline")
13391 ((eq org-log-note-purpose 'deldeadline)
13392 "removing deadline")
13393 ((eq org-log-note-purpose 'refile)
13394 "refiling")
13395 ((eq org-log-note-purpose 'note)
13396 "this entry")
13397 (t (error "This should not happen")))))
13398 (if org-log-note-extra (insert org-log-note-extra))
13399 (org-set-local 'org-finish-function 'org-store-log-note)
13400 (run-hooks 'org-log-buffer-setup-hook)))
13402 (defvar org-note-abort nil) ; dynamically scoped
13403 (defun org-store-log-note ()
13404 "Finish taking a log note, and insert it to where it belongs."
13405 (let ((txt (buffer-string)))
13406 (kill-buffer (current-buffer))
13407 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13408 lines ind bul)
13409 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13410 (setq txt (replace-match "" t t txt)))
13411 (if (string-match "\\s-+\\'" txt)
13412 (setq txt (replace-match "" t t txt)))
13413 (setq lines (org-split-string txt "\n"))
13414 (when (and note (string-match "\\S-" note))
13415 (setq note
13416 (org-replace-escapes
13417 note
13418 (list (cons "%u" (user-login-name))
13419 (cons "%U" user-full-name)
13420 (cons "%t" (format-time-string
13421 (org-time-stamp-format 'long 'inactive)
13422 org-log-note-effective-time))
13423 (cons "%T" (format-time-string
13424 (org-time-stamp-format 'long nil)
13425 org-log-note-effective-time))
13426 (cons "%d" (format-time-string
13427 (org-time-stamp-format nil 'inactive)
13428 org-log-note-effective-time))
13429 (cons "%D" (format-time-string
13430 (org-time-stamp-format nil nil)
13431 org-log-note-effective-time))
13432 (cons "%s" (if org-log-note-state
13433 (concat "\"" org-log-note-state "\"")
13434 ""))
13435 (cons "%S" (if org-log-note-previous-state
13436 (concat "\"" org-log-note-previous-state "\"")
13437 "\"\"")))))
13438 (if lines (setq note (concat note " \\\\")))
13439 (push note lines))
13440 (when (or current-prefix-arg org-note-abort)
13441 (when org-log-into-drawer
13442 (org-remove-empty-drawer-at
13443 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
13444 org-log-note-marker))
13445 (setq lines nil))
13446 (when lines
13447 (with-current-buffer (marker-buffer org-log-note-marker)
13448 (save-excursion
13449 (goto-char org-log-note-marker)
13450 (move-marker org-log-note-marker nil)
13451 (end-of-line 1)
13452 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13453 (setq ind (save-excursion
13454 (if (ignore-errors (goto-char (org-in-item-p)))
13455 (let ((struct (org-list-struct)))
13456 (org-list-get-ind
13457 (org-list-get-top-point struct) struct))
13458 (skip-chars-backward " \r\t\n")
13459 (cond
13460 ((and (org-at-heading-p)
13461 org-adapt-indentation)
13462 (1+ (org-current-level)))
13463 ((org-at-heading-p) 0)
13464 (t (org-get-indentation))))))
13465 (setq bul (org-list-bullet-string "-"))
13466 (org-indent-line-to ind)
13467 (insert bul (pop lines))
13468 (let ((ind-body (+ (length bul) ind)))
13469 (while lines
13470 (insert "\n")
13471 (org-indent-line-to ind-body)
13472 (insert (pop lines))))
13473 (message "Note stored")
13474 (org-back-to-heading t)
13475 (org-cycle-hide-drawers 'children))
13476 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13477 ;; from within `org-add-log-note' because `buffer-undo-list'
13478 ;; is then modified outside of `org-with-remote-undo'.
13479 (when (eq this-command 'org-agenda-todo)
13480 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13481 ;; Don't add undo information when called from `org-agenda-todo'
13482 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13483 (set-window-configuration org-log-note-window-configuration)
13484 (with-current-buffer (marker-buffer org-log-note-return-to)
13485 (goto-char org-log-note-return-to))
13486 (move-marker org-log-note-return-to nil)
13487 (and org-log-post-message (message "%s" org-log-post-message))))
13489 (defun org-remove-empty-drawer-at (drawer pos)
13490 "Remove an empty drawer DRAWER at position POS.
13491 POS may also be a marker."
13492 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13493 (save-excursion
13494 (save-restriction
13495 (widen)
13496 (goto-char pos)
13497 (if (org-in-regexp
13498 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13499 (replace-match ""))))))
13501 (defvar org-ts-type nil)
13502 (defun org-sparse-tree (&optional arg type)
13503 "Create a sparse tree, prompt for the details.
13504 This command can create sparse trees. You first need to select the type
13505 of match used to create the tree:
13507 t Show all TODO entries.
13508 T Show entries with a specific TODO keyword.
13509 m Show entries selected by a tags/property match.
13510 p Enter a property name and its value (both with completion on existing
13511 names/values) and show entries with that property.
13512 r Show entries matching a regular expression (`/' can be used as well).
13513 b Show deadlines and scheduled items before a date.
13514 a Show deadlines and scheduled items after a date.
13515 d Show deadlines due within `org-deadline-warning-days'.
13516 D Show deadlines and scheduled items between a date range."
13517 (interactive "P")
13518 (setq type (or type org-sparse-tree-default-date-type))
13519 (setq org-ts-type type)
13520 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty
13521 [d]eadlines [b]efore-date [a]fter-date [D]ates range
13522 [c]ycle through date types: %s"
13523 (case type
13524 (all "all timestamps")
13525 (scheduled "only scheduled")
13526 (deadline "only deadline")
13527 (active "only active timestamps")
13528 (inactive "only inactive timestamps")
13529 (scheduled-or-deadline "scheduled/deadline")
13530 (closed "with a closed time-stamp")
13531 (otherwise "scheduled/deadline")))
13532 (let ((answer (read-char-exclusive)))
13533 (case answer
13535 (org-sparse-tree
13537 (cadr (memq type '(scheduled-or-deadline all scheduled deadline active
13538 inactive closed)))))
13539 (?d (call-interactively #'org-check-deadlines))
13540 (?b (call-interactively #'org-check-before-date))
13541 (?a (call-interactively #'org-check-after-date))
13542 (?D (call-interactively #'org-check-dates-range))
13543 (?t (call-interactively #'org-show-todo-tree))
13544 (?T (org-show-todo-tree '(4)))
13545 (?m (call-interactively #'org-match-sparse-tree))
13546 ((?p ?P)
13547 (let* ((kwd (org-icompleting-read
13548 "Property: " (mapcar #'list (org-buffer-property-keys))))
13549 (value (org-icompleting-read
13550 "Value: " (mapcar #'list (org-property-values kwd)))))
13551 (unless (string-match "\\`{.*}\\'" value)
13552 (setq value (concat "\"" value "\"")))
13553 (org-match-sparse-tree arg (concat kwd "=" value))))
13554 ((?r ?R ?/) (call-interactively #'org-occur))
13555 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13557 (defvar org-occur-highlights nil
13558 "List of overlays used for occur matches.")
13559 (make-variable-buffer-local 'org-occur-highlights)
13560 (defvar org-occur-parameters nil
13561 "Parameters of the active org-occur calls.
13562 This is a list, each call to org-occur pushes as cons cell,
13563 containing the regular expression and the callback, onto the list.
13564 The list can contain several entries if `org-occur' has been called
13565 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13566 will only contain one set of parameters. When the highlights are
13567 removed (for example with `C-c C-c', or with the next edit (depending
13568 on `org-remove-highlights-with-change'), this variable is emptied
13569 as well.")
13570 (make-variable-buffer-local 'org-occur-parameters)
13572 (defun org-occur (regexp &optional keep-previous callback)
13573 "Make a compact tree which shows all matches of REGEXP.
13574 The tree will show the lines where the regexp matches, and all higher
13575 headlines above the match. It will also show the heading after the match,
13576 to make sure editing the matching entry is easy.
13577 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13578 call to `org-occur' will be kept, to allow stacking of calls to this
13579 command.
13580 If CALLBACK is non-nil, it is a function which is called to confirm
13581 that the match should indeed be shown."
13582 (interactive "sRegexp: \nP")
13583 (when (equal regexp "")
13584 (user-error "Regexp cannot be empty"))
13585 (unless keep-previous
13586 (org-remove-occur-highlights nil nil t))
13587 (push (cons regexp callback) org-occur-parameters)
13588 (let ((cnt 0))
13589 (save-excursion
13590 (goto-char (point-min))
13591 (if (or (not keep-previous) ; do not want to keep
13592 (not org-occur-highlights)) ; no previous matches
13593 ;; hide everything
13594 (org-overview))
13595 (while (re-search-forward regexp nil t)
13596 (when (or (not callback)
13597 (save-match-data (funcall callback)))
13598 (setq cnt (1+ cnt))
13599 (when org-highlight-sparse-tree-matches
13600 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13601 (org-show-context 'occur-tree))))
13602 (when org-remove-highlights-with-change
13603 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13604 nil 'local))
13605 (unless org-sparse-tree-open-archived-trees
13606 (org-hide-archived-subtrees (point-min) (point-max)))
13607 (run-hooks 'org-occur-hook)
13608 (if (org-called-interactively-p 'interactive)
13609 (message "%d match(es) for regexp %s" cnt regexp))
13610 cnt))
13612 (defun org-occur-next-match (&optional n reset)
13613 "Function for `next-error-function' to find sparse tree matches.
13614 N is the number of matches to move, when negative move backwards.
13615 RESET is entirely ignored - this function always goes back to the
13616 starting point when no match is found."
13617 (let* ((limit (if (< n 0) (point-min) (point-max)))
13618 (search-func (if (< n 0)
13619 'previous-single-char-property-change
13620 'next-single-char-property-change))
13621 (n (abs n))
13622 (pos (point))
13624 (catch 'exit
13625 (while (setq p1 (funcall search-func (point) 'org-type))
13626 (when (equal p1 limit)
13627 (goto-char pos)
13628 (error "No more matches"))
13629 (when (equal (get-char-property p1 'org-type) 'org-occur)
13630 (setq n (1- n))
13631 (when (= n 0)
13632 (goto-char p1)
13633 (throw 'exit (point))))
13634 (goto-char p1))
13635 (goto-char p1)
13636 (error "No more matches"))))
13638 (defun org-show-context (&optional key)
13639 "Make sure point and context are visible.
13640 How much context is shown depends upon the variables
13641 `org-show-hierarchy-above', `org-show-following-heading',
13642 `org-show-entry-below' and `org-show-siblings'."
13643 (let ((heading-p (org-at-heading-p t))
13644 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13645 (following-p (org-get-alist-option org-show-following-heading key))
13646 (entry-p (org-get-alist-option org-show-entry-below key))
13647 (siblings-p (org-get-alist-option org-show-siblings key)))
13648 ;; Show heading or entry text
13649 (if (and heading-p (not entry-p))
13650 (org-flag-heading nil) ; only show the heading
13651 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13652 (org-show-hidden-entry))) ; show entire entry
13653 (when following-p
13654 ;; Show next sibling, or heading below text
13655 (save-excursion
13656 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13657 (org-flag-heading nil))))
13658 (when siblings-p (org-show-siblings))
13659 (when hierarchy-p
13660 ;; show all higher headings, possibly with siblings
13661 (save-excursion
13662 (while (and (condition-case nil
13663 (progn (org-up-heading-all 1) t)
13664 (error nil))
13665 (not (bobp)))
13666 (org-flag-heading nil)
13667 (when siblings-p (org-show-siblings)))))
13668 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13670 (defvar org-reveal-start-hook nil
13671 "Hook run before revealing a location.")
13673 (defun org-reveal (&optional siblings)
13674 "Show current entry, hierarchy above it, and the following headline.
13675 This can be used to show a consistent set of context around locations
13676 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13677 not t for the search context.
13679 With optional argument SIBLINGS, on each level of the hierarchy all
13680 siblings are shown. This repairs the tree structure to what it would
13681 look like when opened with hierarchical calls to `org-cycle'.
13682 With double optional argument \\[universal-argument] \\[universal-argument], \
13683 go to the parent and show the
13684 entire tree."
13685 (interactive "P")
13686 (run-hooks 'org-reveal-start-hook)
13687 (let ((org-show-hierarchy-above t)
13688 (org-show-following-heading t)
13689 (org-show-siblings (if siblings t org-show-siblings)))
13690 (org-show-context nil))
13691 (when (equal siblings '(16))
13692 (save-excursion
13693 (when (org-up-heading-safe)
13694 (org-show-subtree)
13695 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13697 (defun org-highlight-new-match (beg end)
13698 "Highlight from BEG to END and mark the highlight is an occur headline."
13699 (let ((ov (make-overlay beg end)))
13700 (overlay-put ov 'face 'secondary-selection)
13701 (overlay-put ov 'org-type 'org-occur)
13702 (push ov org-occur-highlights)))
13704 (defun org-remove-occur-highlights (&optional beg end noremove)
13705 "Remove the occur highlights from the buffer.
13706 BEG and END are ignored. If NOREMOVE is nil, remove this function
13707 from the `before-change-functions' in the current buffer."
13708 (interactive)
13709 (unless org-inhibit-highlight-removal
13710 (mapc 'delete-overlay org-occur-highlights)
13711 (setq org-occur-highlights nil)
13712 (setq org-occur-parameters nil)
13713 (unless noremove
13714 (remove-hook 'before-change-functions
13715 'org-remove-occur-highlights 'local))))
13717 ;;;; Priorities
13719 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13720 "Regular expression matching the priority indicator.")
13722 (defvar org-remove-priority-next-time nil)
13724 (defun org-priority-up ()
13725 "Increase the priority of the current item."
13726 (interactive)
13727 (org-priority 'up))
13729 (defun org-priority-down ()
13730 "Decrease the priority of the current item."
13731 (interactive)
13732 (org-priority 'down))
13734 (defun org-priority (&optional action show)
13735 "Change the priority of an item.
13736 ACTION can be `set', `up', `down', or a character."
13737 (interactive "P")
13738 (if (equal action '(4))
13739 (org-show-priority)
13740 (unless org-enable-priority-commands
13741 (user-error "Priority commands are disabled"))
13742 (setq action (or action 'set))
13743 (let (current new news have remove)
13744 (save-excursion
13745 (org-back-to-heading t)
13746 (if (looking-at org-priority-regexp)
13747 (setq current (string-to-char (match-string 2))
13748 have t))
13749 (cond
13750 ((eq action 'remove)
13751 (setq remove t new ?\ ))
13752 ((or (eq action 'set)
13753 (if (featurep 'xemacs) (characterp action) (integerp action)))
13754 (if (not (eq action 'set))
13755 (setq new action)
13756 (message "Priority %c-%c, SPC to remove: "
13757 org-highest-priority org-lowest-priority)
13758 (save-match-data
13759 (setq new (read-char-exclusive))))
13760 (if (and (= (upcase org-highest-priority) org-highest-priority)
13761 (= (upcase org-lowest-priority) org-lowest-priority))
13762 (setq new (upcase new)))
13763 (cond ((equal new ?\ ) (setq remove t))
13764 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13765 (user-error "Priority must be between `%c' and `%c'"
13766 org-highest-priority org-lowest-priority))))
13767 ((eq action 'up)
13768 (setq new (if have
13769 (1- current) ; normal cycling
13770 ;; last priority was empty
13771 (if (eq last-command this-command)
13772 org-lowest-priority ; wrap around empty to lowest
13773 ;; default
13774 (if org-priority-start-cycle-with-default
13775 org-default-priority
13776 (1- org-default-priority))))))
13777 ((eq action 'down)
13778 (setq new (if have
13779 (1+ current) ; normal cycling
13780 ;; last priority was empty
13781 (if (eq last-command this-command)
13782 org-highest-priority ; wrap around empty to highest
13783 ;; default
13784 (if org-priority-start-cycle-with-default
13785 org-default-priority
13786 (1+ org-default-priority))))))
13787 (t (user-error "Invalid action")))
13788 (if (or (< (upcase new) org-highest-priority)
13789 (> (upcase new) org-lowest-priority))
13790 (if (and (memq action '(up down))
13791 (not have) (not (eq last-command this-command)))
13792 ;; `new' is from default priority
13793 (error
13794 "The default can not be set, see `org-default-priority' why")
13795 ;; normal cycling: `new' is beyond highest/lowest priority
13796 ;; and is wrapped around to the empty priority
13797 (setq remove t)))
13798 (setq news (format "%c" new))
13799 (if have
13800 (if remove
13801 (replace-match "" t t nil 1)
13802 (replace-match news t t nil 2))
13803 (if remove
13804 (user-error "No priority cookie found in line")
13805 (let ((case-fold-search nil))
13806 (looking-at org-todo-line-regexp))
13807 (if (match-end 2)
13808 (progn
13809 (goto-char (match-end 2))
13810 (insert " [#" news "]"))
13811 (goto-char (match-beginning 3))
13812 (insert "[#" news "] "))))
13813 (org-preserve-lc (org-set-tags nil 'align)))
13814 (if remove
13815 (message "Priority removed")
13816 (message "Priority of current item set to %s" news)))))
13818 (defun org-show-priority ()
13819 "Show the priority of the current item.
13820 This priority is composed of the main priority given with the [#A] cookies,
13821 and by additional input from the age of a schedules or deadline entry."
13822 (interactive)
13823 (let ((pri (if (eq major-mode 'org-agenda-mode)
13824 (org-get-at-bol 'priority)
13825 (save-excursion
13826 (save-match-data
13827 (beginning-of-line)
13828 (and (looking-at org-heading-regexp)
13829 (org-get-priority (match-string 0))))))))
13830 (message "Priority is %d" (if pri pri -1000))))
13832 (defun org-get-priority (s)
13833 "Find priority cookie and return priority."
13834 (save-match-data
13835 (if (functionp org-get-priority-function)
13836 (funcall org-get-priority-function)
13837 (if (not (string-match org-priority-regexp s))
13838 (* 1000 (- org-lowest-priority org-default-priority))
13839 (* 1000 (- org-lowest-priority
13840 (string-to-char (match-string 2 s))))))))
13842 ;;;; Tags
13844 (defvar org-agenda-archives-mode)
13845 (defvar org-map-continue-from nil
13846 "Position from where mapping should continue.
13847 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13849 (defvar org-scanner-tags nil
13850 "The current tag list while the tags scanner is running.")
13851 (defvar org-trust-scanner-tags nil
13852 "Should `org-get-tags-at' use the tags for the scanner.
13853 This is for internal dynamical scoping only.
13854 When this is non-nil, the function `org-get-tags-at' will return the value
13855 of `org-scanner-tags' instead of building the list by itself. This
13856 can lead to large speed-ups when the tags scanner is used in a file with
13857 many entries, and when the list of tags is retrieved, for example to
13858 obtain a list of properties. Building the tags list for each entry in such
13859 a file becomes an N^2 operation - but with this variable set, it scales
13860 as N.")
13862 (defun org-scan-tags (action matcher todo-only &optional start-level)
13863 "Sca headline tags with inheritance and produce output ACTION.
13865 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13866 or `agenda' to produce an entry list for an agenda view. It can also be
13867 a Lisp form or a function that should be called at each matched headline, in
13868 this case the return value is a list of all return values from these calls.
13870 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13871 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13872 only lines with a not-done TODO keyword are included in the output.
13873 This should be the same variable that was scoped into
13874 and set by `org-make-tags-matcher' when it constructed MATCHER.
13876 START-LEVEL can be a string with asterisks, reducing the scope to
13877 headlines matching this string."
13878 (require 'org-agenda)
13879 (let* ((re (concat "^"
13880 (if start-level
13881 ;; Get the correct level to match
13882 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13883 org-outline-regexp)
13884 " *\\(\\<\\("
13885 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13886 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13887 (props (list 'face 'default
13888 'done-face 'org-agenda-done
13889 'undone-face 'default
13890 'mouse-face 'highlight
13891 'org-not-done-regexp org-not-done-regexp
13892 'org-todo-regexp org-todo-regexp
13893 'org-complex-heading-regexp org-complex-heading-regexp
13894 'help-echo
13895 (format "mouse-2 or RET jump to org file %s"
13896 (abbreviate-file-name
13897 (or (buffer-file-name (buffer-base-buffer))
13898 (buffer-name (buffer-base-buffer)))))))
13899 (org-map-continue-from nil)
13900 lspos tags tags-list
13901 (tags-alist (list (cons 0 org-file-tags)))
13902 (llast 0) rtn rtn1 level category i txt
13903 todo marker entry priority)
13904 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13905 (setq action (list 'lambda nil action)))
13906 (save-excursion
13907 (goto-char (point-min))
13908 (when (eq action 'sparse-tree)
13909 (org-overview)
13910 (org-remove-occur-highlights))
13911 (while (let (case-fold-search)
13912 (re-search-forward re nil t))
13913 (setq org-map-continue-from nil)
13914 (catch :skip
13915 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13916 tags (if (match-end 4) (org-match-string-no-properties 4)))
13917 (goto-char (setq lspos (match-beginning 0)))
13918 (setq level (org-reduced-level (org-outline-level))
13919 category (org-get-category))
13920 (setq i llast llast level)
13921 ;; remove tag lists from same and sublevels
13922 (while (>= i level)
13923 (when (setq entry (assoc i tags-alist))
13924 (setq tags-alist (delete entry tags-alist)))
13925 (setq i (1- i)))
13926 ;; add the next tags
13927 (when tags
13928 (setq tags (org-split-string tags ":")
13929 tags-alist
13930 (cons (cons level tags) tags-alist)))
13931 ;; compile tags for current headline
13932 (setq tags-list
13933 (if org-use-tag-inheritance
13934 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13935 tags)
13936 org-scanner-tags tags-list)
13937 (when org-use-tag-inheritance
13938 (setcdr (car tags-alist)
13939 (mapcar (lambda (x)
13940 (setq x (copy-sequence x))
13941 (org-add-prop-inherited x))
13942 (cdar tags-alist))))
13943 (when (and tags org-use-tag-inheritance
13944 (or (not (eq t org-use-tag-inheritance))
13945 org-tags-exclude-from-inheritance))
13946 ;; selective inheritance, remove uninherited ones
13947 (setcdr (car tags-alist)
13948 (org-remove-uninherited-tags (cdar tags-alist))))
13949 (when (and
13951 ;; eval matcher only when the todo condition is OK
13952 (and (or (not todo-only) (member todo org-not-done-keywords))
13953 (let ((case-fold-search t) (org-trust-scanner-tags t))
13954 (eval matcher)))
13956 ;; Call the skipper, but return t if it does not skip,
13957 ;; so that the `and' form continues evaluating
13958 (progn
13959 (unless (eq action 'sparse-tree) (org-agenda-skip))
13962 ;; Check if timestamps are deselecting this entry
13963 (or (not todo-only)
13964 (and (member todo org-not-done-keywords)
13965 (or (not org-agenda-tags-todo-honor-ignore-options)
13966 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13968 ;; select this headline
13969 (cond
13970 ((eq action 'sparse-tree)
13971 (and org-highlight-sparse-tree-matches
13972 (org-get-heading) (match-end 0)
13973 (org-highlight-new-match
13974 (match-beginning 1) (match-end 1)))
13975 (org-show-context 'tags-tree))
13976 ((eq action 'agenda)
13977 (setq txt (org-agenda-format-item
13979 (concat
13980 (if (eq org-tags-match-list-sublevels 'indented)
13981 (make-string (1- level) ?.) "")
13982 (org-get-heading))
13983 level category
13984 tags-list)
13985 priority (org-get-priority txt))
13986 (goto-char lspos)
13987 (setq marker (org-agenda-new-marker))
13988 (org-add-props txt props
13989 'org-marker marker 'org-hd-marker marker 'org-category category
13990 'todo-state todo
13991 'priority priority 'type "tagsmatch")
13992 (push txt rtn))
13993 ((functionp action)
13994 (setq org-map-continue-from nil)
13995 (save-excursion
13996 (setq rtn1 (funcall action))
13997 (push rtn1 rtn)))
13998 (t (user-error "Invalid action")))
14000 ;; if we are to skip sublevels, jump to end of subtree
14001 (unless org-tags-match-list-sublevels
14002 (org-end-of-subtree t)
14003 (backward-char 1))))
14004 ;; Get the correct position from where to continue
14005 (if org-map-continue-from
14006 (goto-char org-map-continue-from)
14007 (and (= (point) lspos) (end-of-line 1)))))
14008 (when (and (eq action 'sparse-tree)
14009 (not org-sparse-tree-open-archived-trees))
14010 (org-hide-archived-subtrees (point-min) (point-max)))
14011 (nreverse rtn)))
14013 (defun org-remove-uninherited-tags (tags)
14014 "Remove all tags that are not inherited from the list TAGS."
14015 (cond
14016 ((eq org-use-tag-inheritance t)
14017 (if org-tags-exclude-from-inheritance
14018 (org-delete-all org-tags-exclude-from-inheritance tags)
14019 tags))
14020 ((not org-use-tag-inheritance) nil)
14021 ((stringp org-use-tag-inheritance)
14022 (delq nil (mapcar
14023 (lambda (x)
14024 (if (and (string-match org-use-tag-inheritance x)
14025 (not (member x org-tags-exclude-from-inheritance)))
14026 x nil))
14027 tags)))
14028 ((listp org-use-tag-inheritance)
14029 (delq nil (mapcar
14030 (lambda (x)
14031 (if (member x org-use-tag-inheritance) x nil))
14032 tags)))))
14034 (defun org-match-sparse-tree (&optional todo-only match)
14035 "Create a sparse tree according to tags string MATCH.
14036 MATCH can contain positive and negative selection of tags, like
14037 \"+WORK+URGENT-WITHBOSS\".
14038 If optional argument TODO-ONLY is non-nil, only select lines that are
14039 also TODO lines."
14040 (interactive "P")
14041 (org-agenda-prepare-buffers (list (current-buffer)))
14042 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
14044 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14046 (defvar org-cached-props nil)
14047 (defun org-cached-entry-get (pom property)
14048 (if (or (eq t org-use-property-inheritance)
14049 (and (stringp org-use-property-inheritance)
14050 (string-match org-use-property-inheritance property))
14051 (and (listp org-use-property-inheritance)
14052 (member property org-use-property-inheritance)))
14053 ;; Caching is not possible, check it directly
14054 (org-entry-get pom property 'inherit)
14055 ;; Get all properties, so that we can do complicated checks easily
14056 (cdr (assoc property (or org-cached-props
14057 (setq org-cached-props
14058 (org-entry-properties pom)))))))
14060 (defun org-global-tags-completion-table (&optional files)
14061 "Return the list of all tags in all agenda buffer/files.
14062 Optional FILES argument is a list of files which can be used
14063 instead of the agenda files."
14064 (save-excursion
14065 (org-uniquify
14066 (delq nil
14067 (apply 'append
14068 (mapcar
14069 (lambda (file)
14070 (set-buffer (find-file-noselect file))
14071 (append (org-get-buffer-tags)
14072 (mapcar (lambda (x) (if (stringp (car-safe x))
14073 (list (car-safe x)) nil))
14074 org-tag-alist)))
14075 (if (and files (car files))
14076 files
14077 (org-agenda-files))))))))
14079 (defun org-make-tags-matcher (match)
14080 "Create the TAGS/TODO matcher form for the selection string MATCH.
14082 The variable `todo-only' is scoped dynamically into this function.
14083 It will be set to t if the matcher restricts matching to TODO entries,
14084 otherwise will not be touched.
14086 Returns a cons of the selection string MATCH and the constructed
14087 lisp form implementing the matcher. The matcher is to be evaluated
14088 at an Org entry, with point on the headline, and returns t if the
14089 entry matches the selection string MATCH. The returned lisp form
14090 references two variables with information about the entry, which
14091 must be bound around the form's evaluation: todo, the TODO keyword
14092 at the entry (or nil of none); and tags-list, the list of all tags
14093 at the entry including inherited ones. Additionally, the category
14094 of the entry (if any) must be specified as the text property
14095 'org-category on the headline.
14097 See also `org-scan-tags'.
14099 (declare (special todo-only))
14100 (unless (boundp 'todo-only)
14101 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14102 (unless match
14103 ;; Get a new match request, with completion against the global
14104 ;; tags table and the local tags in current buffer
14105 (let ((org-last-tags-completion-table
14106 (org-uniquify
14107 (delq nil (append (org-get-buffer-tags)
14108 (org-global-tags-completion-table))))))
14109 (setq match (org-completing-read-no-i
14110 "Match: " 'org-tags-completion-function nil nil nil
14111 'org-tags-history))))
14113 ;; Parse the string and create a lisp form
14114 (let ((match0 match)
14115 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14116 minus tag mm
14117 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14118 orterms term orlist re-p str-p level-p level-op time-p
14119 prop-p pn pv po gv rest (start 0) (ss 0))
14120 ;; Expand group tags
14121 (setq match (org-tags-expand match))
14123 ;; Check if there is a TODO part of this match, which would be the
14124 ;; part after a "/". TO make sure that this slash is not part of
14125 ;; a property value to be matched against, we also check that there
14126 ;; is no " after that slash.
14127 ;; First, find the last slash
14128 (while (string-match "/+" match ss)
14129 (setq start (match-beginning 0) ss (match-end 0)))
14130 (if (and (string-match "/+" match start)
14131 (not (save-match-data (string-match "\"" match start))))
14132 ;; match contains also a todo-matching request
14133 (progn
14134 (setq tagsmatch (substring match 0 (match-beginning 0))
14135 todomatch (substring match (match-end 0)))
14136 (if (string-match "^!" todomatch)
14137 (setq todo-only t todomatch (substring todomatch 1)))
14138 (if (string-match "^\\s-*$" todomatch)
14139 (setq todomatch nil)))
14140 ;; only matching tags
14141 (setq tagsmatch match todomatch nil))
14143 ;; Make the tags matcher
14144 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14145 (setq tagsmatcher t)
14146 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14147 (while (setq term (pop orterms))
14148 (while (and (equal (substring term -1) "\\") orterms)
14149 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14150 (while (string-match re term)
14151 (setq rest (substring term (match-end 0))
14152 minus (and (match-end 1)
14153 (equal (match-string 1 term) "-"))
14154 tag (save-match-data (replace-regexp-in-string
14155 "\\\\-" "-"
14156 (match-string 2 term)))
14157 re-p (equal (string-to-char tag) ?{)
14158 level-p (match-end 4)
14159 prop-p (match-end 5)
14160 mm (cond
14161 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14162 (level-p
14163 (setq level-op (org-op-to-function (match-string 3 term)))
14164 `(,level-op level ,(string-to-number
14165 (match-string 4 term))))
14166 (prop-p
14167 (setq pn (match-string 5 term)
14168 po (match-string 6 term)
14169 pv (match-string 7 term)
14170 re-p (equal (string-to-char pv) ?{)
14171 str-p (equal (string-to-char pv) ?\")
14172 time-p (save-match-data
14173 (string-match "^\"[[<].*[]>]\"$" pv))
14174 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14175 (if time-p (setq pv (org-matcher-time pv)))
14176 (setq po (org-op-to-function po (if time-p 'time str-p)))
14177 (cond
14178 ((equal pn "CATEGORY")
14179 (setq gv '(get-text-property (point) 'org-category)))
14180 ((equal pn "TODO")
14181 (setq gv 'todo))
14183 (setq gv `(org-cached-entry-get nil ,pn))))
14184 (if re-p
14185 (if (eq po 'org<>)
14186 `(not (string-match ,pv (or ,gv "")))
14187 `(string-match ,pv (or ,gv "")))
14188 (if str-p
14189 `(,po (or ,gv "") ,pv)
14190 `(,po (string-to-number (or ,gv ""))
14191 ,(string-to-number pv) ))))
14192 (t `(member ,tag tags-list)))
14193 mm (if minus (list 'not mm) mm)
14194 term rest)
14195 (push mm tagsmatcher))
14196 (push (if (> (length tagsmatcher) 1)
14197 (cons 'and tagsmatcher)
14198 (car tagsmatcher))
14199 orlist)
14200 (setq tagsmatcher nil))
14201 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14202 (setq tagsmatcher
14203 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14204 ;; Make the todo matcher
14205 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14206 (setq todomatcher t)
14207 (setq orterms (org-split-string todomatch "|") orlist nil)
14208 (while (setq term (pop orterms))
14209 (while (string-match re term)
14210 (setq minus (and (match-end 1)
14211 (equal (match-string 1 term) "-"))
14212 kwd (match-string 2 term)
14213 re-p (equal (string-to-char kwd) ?{)
14214 term (substring term (match-end 0))
14215 mm (if re-p
14216 `(string-match ,(substring kwd 1 -1) todo)
14217 (list 'equal 'todo kwd))
14218 mm (if minus (list 'not mm) mm))
14219 (push mm todomatcher))
14220 (push (if (> (length todomatcher) 1)
14221 (cons 'and todomatcher)
14222 (car todomatcher))
14223 orlist)
14224 (setq todomatcher nil))
14225 (setq todomatcher (if (> (length orlist) 1)
14226 (cons 'or orlist) (car orlist))))
14228 ;; Return the string and lisp forms of the matcher
14229 (setq matcher (if todomatcher
14230 (list 'and tagsmatcher todomatcher)
14231 tagsmatcher))
14232 (when todo-only
14233 (setq matcher (list 'and '(member todo org-not-done-keywords)
14234 matcher)))
14235 (cons match0 matcher)))
14237 (defun org-tags-expand (match &optional single-as-list downcased)
14238 "Expand group tags in MATCH.
14240 This replaces every group tag in MATCH with a regexp tag search.
14241 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14242 will be replaced like this:
14244 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14245 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14246 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14248 Replacing by a regexp preserves the structure of the match.
14249 E.g., this expansion
14251 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14253 will match anything tagged with \"Lab\" and \"Home\", or tagged
14254 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14256 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14257 assumed to be a single group tag, and the function will return
14258 the list of tags in this group.
14260 When DOWNCASE is non-nil, expand downcased TAGS."
14261 (if org-group-tags
14262 (let* ((case-fold-search t)
14263 (stable org-mode-syntax-table)
14264 (tal (or org-tag-groups-alist-for-agenda
14265 org-tag-groups-alist))
14266 (tal (if downcased
14267 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14268 (tml (mapcar 'car tal))
14269 (rtnmatch match) rpl)
14270 ;; @ and _ are allowed as word-components in tags
14271 (modify-syntax-entry ?@ "w" stable)
14272 (modify-syntax-entry ?_ "w" stable)
14273 (while (and tml
14274 (with-syntax-table stable
14275 (string-match
14276 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14277 (regexp-opt tml) "\\>\\)") rtnmatch)))
14278 (let* ((dir (match-string 1 rtnmatch))
14279 (tag (match-string 2 rtnmatch))
14280 (tag (if downcased (downcase tag) tag)))
14281 (setq tml (delete tag tml))
14282 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14283 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14284 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14285 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14286 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14287 (if single-as-list
14288 (or (reverse rpl) (list rtnmatch))
14289 rtnmatch))
14290 (if single-as-list (list (if downcased (downcase match) match))
14291 match)))
14293 (defun org-op-to-function (op &optional stringp)
14294 "Turn an operator into the appropriate function."
14295 (setq op
14296 (cond
14297 ((equal op "<" ) '(< string< org-time<))
14298 ((equal op ">" ) '(> org-string> org-time>))
14299 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14300 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14301 ((member op '("=" "==")) '(= string= org-time=))
14302 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14303 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14305 (defun org<> (a b) (not (= a b)))
14306 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14307 (defun org-string>= (a b) (not (string< a b)))
14308 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14309 (defun org-string<> (a b) (not (string= a b)))
14310 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14311 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14312 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14313 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14314 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14315 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14316 (defun org-2ft (s)
14317 "Convert S to a floating point time.
14318 If S is already a number, just return it. If it is a string, parse
14319 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14320 (cond
14321 ((numberp s) s)
14322 ((stringp s)
14323 (condition-case nil
14324 (float-time (apply 'encode-time (org-parse-time-string s)))
14325 (error 0.)))
14326 (t 0.)))
14328 (defun org-time-today ()
14329 "Time in seconds today at 0:00.
14330 Returns the float number of seconds since the beginning of the
14331 epoch to the beginning of today (00:00)."
14332 (float-time (apply 'encode-time
14333 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14335 (defun org-matcher-time (s)
14336 "Interpret a time comparison value."
14337 (save-match-data
14338 (cond
14339 ((string= s "<now>") (float-time))
14340 ((string= s "<today>") (org-time-today))
14341 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14342 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14343 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14344 (+ (org-time-today)
14345 (* (string-to-number (match-string 1 s))
14346 (cdr (assoc (match-string 2 s)
14347 '(("d" . 86400.0) ("w" . 604800.0)
14348 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14349 (t (org-2ft s)))))
14351 (defun org-match-any-p (re list)
14352 "Does re match any element of list?"
14353 (setq list (mapcar (lambda (x) (string-match re x)) list))
14354 (delq nil list))
14356 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14357 (defvar org-tags-overlay (make-overlay 1 1))
14358 (org-detach-overlay org-tags-overlay)
14360 (defun org-get-local-tags-at (&optional pos)
14361 "Get a list of tags defined in the current headline."
14362 (org-get-tags-at pos 'local))
14364 (defun org-get-local-tags ()
14365 "Get a list of tags defined in the current headline."
14366 (org-get-tags-at nil 'local))
14368 (defun org-get-tags-at (&optional pos local)
14369 "Get a list of all headline tags applicable at POS.
14370 POS defaults to point. If tags are inherited, the list contains
14371 the targets in the same sequence as the headlines appear, i.e.
14372 the tags of the current headline come last.
14373 When LOCAL is non-nil, only return tags from the current headline,
14374 ignore inherited ones."
14375 (interactive)
14376 (if (and org-trust-scanner-tags
14377 (or (not pos) (equal pos (point)))
14378 (not local))
14379 org-scanner-tags
14380 (let (tags ltags lastpos parent)
14381 (save-excursion
14382 (save-restriction
14383 (widen)
14384 (goto-char (or pos (point)))
14385 (save-match-data
14386 (catch 'done
14387 (condition-case nil
14388 (progn
14389 (org-back-to-heading t)
14390 (while (not (equal lastpos (point)))
14391 (setq lastpos (point))
14392 (when (looking-at
14393 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14394 (setq ltags (org-split-string
14395 (org-match-string-no-properties 1) ":"))
14396 (when parent
14397 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14398 (setq tags (append
14399 (if parent
14400 (org-remove-uninherited-tags ltags)
14401 ltags)
14402 tags)))
14403 (or org-use-tag-inheritance (throw 'done t))
14404 (if local (throw 'done t))
14405 (or (org-up-heading-safe) (error nil))
14406 (setq parent t)))
14407 (error nil)))))
14408 (if local
14409 tags
14410 (reverse (delete-dups
14411 (reverse (append
14412 (org-remove-uninherited-tags
14413 org-file-tags) tags)))))))))
14415 (defun org-add-prop-inherited (s)
14416 (add-text-properties 0 (length s) '(inherited t) s)
14419 (defun org-toggle-tag (tag &optional onoff)
14420 "Toggle the tag TAG for the current line.
14421 If ONOFF is `on' or `off', don't toggle but set to this state."
14422 (let (res current)
14423 (save-excursion
14424 (org-back-to-heading t)
14425 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14426 (point-at-eol) t)
14427 (progn
14428 (setq current (match-string 1))
14429 (replace-match ""))
14430 (setq current ""))
14431 (setq current (nreverse (org-split-string current ":")))
14432 (cond
14433 ((eq onoff 'on)
14434 (setq res t)
14435 (or (member tag current) (push tag current)))
14436 ((eq onoff 'off)
14437 (or (not (member tag current)) (setq current (delete tag current))))
14438 (t (if (member tag current)
14439 (setq current (delete tag current))
14440 (setq res t)
14441 (push tag current))))
14442 (end-of-line 1)
14443 (if current
14444 (progn
14445 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14446 (org-set-tags nil t))
14447 (delete-horizontal-space))
14448 (run-hooks 'org-after-tags-change-hook))
14449 res))
14451 (defun org-align-tags-here (to-col)
14452 ;; Assumes that this is a headline
14453 "Align tags on the current headline to TO-COL."
14454 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14455 (beginning-of-line 1)
14456 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14457 (< pos (match-beginning 2)))
14458 (progn
14459 (setq tags-l (- (match-end 2) (match-beginning 2)))
14460 (goto-char (match-beginning 1))
14461 (insert " ")
14462 (delete-region (point) (1+ (match-beginning 2)))
14463 (setq ncol (max (current-column)
14464 (1+ col)
14465 (if (> to-col 0)
14466 to-col
14467 (- (abs to-col) tags-l))))
14468 (setq p (point))
14469 (insert (make-string (- ncol (current-column)) ?\ ))
14470 (setq ncol (current-column))
14471 (when indent-tabs-mode (tabify p (point-at-eol)))
14472 (org-move-to-column (min ncol col)))
14473 (goto-char pos))))
14475 (defun org-set-tags-command (&optional arg just-align)
14476 "Call the set-tags command for the current entry."
14477 (interactive "P")
14478 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14479 (org-set-tags arg just-align)
14480 (save-excursion
14481 (unless (and (org-region-active-p)
14482 org-loop-over-headlines-in-active-region)
14483 (org-back-to-heading t))
14484 (org-set-tags arg just-align))))
14486 (defun org-set-tags-to (data)
14487 "Set the tags of the current entry to DATA, replacing the current tags.
14488 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14489 If DATA is nil or the empty string, any tags will be removed."
14490 (interactive "sTags: ")
14491 (setq data
14492 (cond
14493 ((eq data nil) "")
14494 ((equal data "") "")
14495 ((stringp data)
14496 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14497 ":"))
14498 ((listp data)
14499 (concat ":" (mapconcat 'identity data ":") ":"))))
14500 (when data
14501 (save-excursion
14502 (org-back-to-heading t)
14503 (when (looking-at org-complex-heading-regexp)
14504 (if (match-end 5)
14505 (progn
14506 (goto-char (match-beginning 5))
14507 (insert data)
14508 (delete-region (point) (point-at-eol))
14509 (org-set-tags nil 'align))
14510 (goto-char (point-at-eol))
14511 (insert " " data)
14512 (org-set-tags nil 'align)))
14513 (beginning-of-line 1)
14514 (if (looking-at ".*?\\([ \t]+\\)$")
14515 (delete-region (match-beginning 1) (match-end 1))))))
14517 (defun org-align-all-tags ()
14518 "Align the tags i all headings."
14519 (interactive)
14520 (save-excursion
14521 (or (ignore-errors (org-back-to-heading t))
14522 (outline-next-heading))
14523 (if (org-at-heading-p)
14524 (org-set-tags t)
14525 (message "No headings"))))
14527 (defvar org-indent-indentation-per-level)
14528 (defun org-set-tags (&optional arg just-align)
14529 "Set the tags for the current headline.
14530 With prefix ARG, realign all tags in headings in the current buffer.
14531 When JUST-ALIGN is non-nil, only align tags."
14532 (interactive "P")
14533 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14534 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14535 'region-start-level 'region))
14536 org-loop-over-headlines-in-active-region)
14537 (org-map-entries
14538 ;; We don't use ARG and JUST-ALIGN here because these args
14539 ;; are not useful when looping over headlines.
14540 `(org-set-tags)
14541 org-loop-over-headlines-in-active-region
14542 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14543 (let* ((re org-outline-regexp-bol)
14544 (current (unless arg (org-get-tags-string)))
14545 (col (current-column))
14546 (org-setting-tags t)
14547 table current-tags inherited-tags ; computed below when needed
14548 tags p0 c0 c1 rpl di tc level)
14549 (if arg
14550 (save-excursion
14551 (goto-char (point-min))
14552 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14553 (while (re-search-forward re nil t)
14554 (org-set-tags nil t)
14555 (end-of-line 1)))
14556 (message "All tags realigned to column %d" org-tags-column))
14557 (if just-align
14558 (setq tags current)
14559 ;; Get a new set of tags from the user
14560 (save-excursion
14561 (setq table (append org-tag-persistent-alist
14562 (or org-tag-alist (org-get-buffer-tags))
14563 (and
14564 org-complete-tags-always-offer-all-agenda-tags
14565 (org-global-tags-completion-table
14566 (org-agenda-files))))
14567 org-last-tags-completion-table table
14568 current-tags (org-split-string current ":")
14569 inherited-tags (nreverse
14570 (nthcdr (length current-tags)
14571 (nreverse (org-get-tags-at))))
14572 tags
14573 (if (or (eq t org-use-fast-tag-selection)
14574 (and org-use-fast-tag-selection
14575 (delq nil (mapcar 'cdr table))))
14576 (org-fast-tag-selection
14577 current-tags inherited-tags table
14578 (if org-fast-tag-selection-include-todo
14579 org-todo-key-alist))
14580 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14581 (org-trim
14582 (org-icompleting-read "Tags: "
14583 'org-tags-completion-function
14584 nil nil current 'org-tags-history))))))
14585 (while (string-match "[-+&]+" tags)
14586 ;; No boolean logic, just a list
14587 (setq tags (replace-match ":" t t tags))))
14589 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14591 (if org-tags-sort-function
14592 (setq tags (mapconcat 'identity
14593 (sort (org-split-string
14594 tags (org-re "[^[:alnum:]_@#%]+"))
14595 org-tags-sort-function) ":")))
14597 (if (string-match "\\`[\t ]*\\'" tags)
14598 (setq tags "")
14599 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14600 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14602 ;; Insert new tags at the correct column
14603 (beginning-of-line 1)
14604 (setq level (or (and (looking-at org-outline-regexp)
14605 (- (match-end 0) (point) 1))
14607 (cond
14608 ((and (equal current "") (equal tags "")))
14609 ((re-search-forward
14610 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14611 (point-at-eol) t)
14612 (if (equal tags "")
14613 (setq rpl "")
14614 (goto-char (match-beginning 0))
14615 (setq c0 (current-column)
14616 ;; compute offset for the case of org-indent-mode active
14617 di (if (org-bound-and-true-p org-indent-mode)
14618 (* (1- org-indent-indentation-per-level) (1- level))
14620 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14621 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14622 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14623 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14624 (replace-match rpl t t)
14625 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14626 tags)
14627 (t (error "Tags alignment failed")))
14628 (org-move-to-column col)
14629 (unless just-align
14630 (run-hooks 'org-after-tags-change-hook))))))
14632 (defun org-change-tag-in-region (beg end tag off)
14633 "Add or remove TAG for each entry in the region.
14634 This works in the agenda, and also in an org-mode buffer."
14635 (interactive
14636 (list (region-beginning) (region-end)
14637 (let ((org-last-tags-completion-table
14638 (if (derived-mode-p 'org-mode)
14639 (org-uniquify
14640 (delq nil (append (org-get-buffer-tags)
14641 (org-global-tags-completion-table))))
14642 (org-global-tags-completion-table))))
14643 (org-icompleting-read
14644 "Tag: " 'org-tags-completion-function nil nil nil
14645 'org-tags-history))
14646 (progn
14647 (message "[s]et or [r]emove? ")
14648 (equal (read-char-exclusive) ?r))))
14649 (if (fboundp 'deactivate-mark) (deactivate-mark))
14650 (let ((agendap (equal major-mode 'org-agenda-mode))
14651 l1 l2 m buf pos newhead (cnt 0))
14652 (goto-char end)
14653 (setq l2 (1- (org-current-line)))
14654 (goto-char beg)
14655 (setq l1 (org-current-line))
14656 (loop for l from l1 to l2 do
14657 (org-goto-line l)
14658 (setq m (get-text-property (point) 'org-hd-marker))
14659 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14660 (and agendap m))
14661 (setq buf (if agendap (marker-buffer m) (current-buffer))
14662 pos (if agendap m (point)))
14663 (with-current-buffer buf
14664 (save-excursion
14665 (save-restriction
14666 (goto-char pos)
14667 (setq cnt (1+ cnt))
14668 (org-toggle-tag tag (if off 'off 'on))
14669 (setq newhead (org-get-heading)))))
14670 (and agendap (org-agenda-change-all-lines newhead m))))
14671 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14673 (defun org-tags-completion-function (string predicate &optional flag)
14674 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14675 (confirm (lambda (x) (stringp (car x)))))
14676 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14677 (setq s1 (match-string 1 string)
14678 s2 (match-string 2 string))
14679 (setq s1 "" s2 string))
14680 (cond
14681 ((eq flag nil)
14682 ;; try completion
14683 (setq rtn (try-completion s2 ctable confirm))
14684 (if (stringp rtn)
14685 (setq rtn
14686 (concat s1 s2 (substring rtn (length s2))
14687 (if (and org-add-colon-after-tag-completion
14688 (assoc rtn ctable))
14689 ":" ""))))
14690 rtn)
14691 ((eq flag t)
14692 ;; all-completions
14693 (all-completions s2 ctable confirm))
14694 ((eq flag 'lambda)
14695 ;; exact match?
14696 (assoc s2 ctable)))))
14698 (defun org-fast-tag-insert (kwd tags face &optional end)
14699 "Insert KDW, and the TAGS, the latter with face FACE.
14700 Also insert END."
14701 (insert (format "%-12s" (concat kwd ":"))
14702 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14703 (or end "")))
14705 (defun org-fast-tag-show-exit (flag)
14706 (save-excursion
14707 (org-goto-line 3)
14708 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14709 (replace-match ""))
14710 (when flag
14711 (end-of-line 1)
14712 (org-move-to-column (- (window-width) 19) t)
14713 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14715 (defun org-set-current-tags-overlay (current prefix)
14716 "Add an overlay to CURRENT tag with PREFIX."
14717 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14718 (if (featurep 'xemacs)
14719 (org-overlay-display org-tags-overlay (concat prefix s)
14720 'secondary-selection)
14721 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14722 (org-overlay-display org-tags-overlay (concat prefix s)))))
14724 (defvar org-last-tag-selection-key nil)
14725 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14726 "Fast tag selection with single keys.
14727 CURRENT is the current list of tags in the headline, INHERITED is the
14728 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14729 possibly with grouping information. TODO-TABLE is a similar table with
14730 TODO keywords, should these have keys assigned to them.
14731 If the keys are nil, a-z are automatically assigned.
14732 Returns the new tags string, or nil to not change the current settings."
14733 (let* ((fulltable (append table todo-table))
14734 (maxlen (apply 'max (mapcar
14735 (lambda (x)
14736 (if (stringp (car x)) (string-width (car x)) 0))
14737 fulltable)))
14738 (buf (current-buffer))
14739 (expert (eq org-fast-tag-selection-single-key 'expert))
14740 (buffer-tags nil)
14741 (fwidth (+ maxlen 3 1 3))
14742 (ncol (/ (- (window-width) 4) fwidth))
14743 (i-face 'org-done)
14744 (c-face 'org-todo)
14745 tg cnt e c char c1 c2 ntable tbl rtn
14746 ov-start ov-end ov-prefix
14747 (exit-after-next org-fast-tag-selection-single-key)
14748 (done-keywords org-done-keywords)
14749 groups ingroup)
14750 (save-excursion
14751 (beginning-of-line 1)
14752 (if (looking-at
14753 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14754 (setq ov-start (match-beginning 1)
14755 ov-end (match-end 1)
14756 ov-prefix "")
14757 (setq ov-start (1- (point-at-eol))
14758 ov-end (1+ ov-start))
14759 (skip-chars-forward "^\n\r")
14760 (setq ov-prefix
14761 (concat
14762 (buffer-substring (1- (point)) (point))
14763 (if (> (current-column) org-tags-column)
14765 (make-string (- org-tags-column (current-column)) ?\ ))))))
14766 (move-overlay org-tags-overlay ov-start ov-end)
14767 (save-window-excursion
14768 (if expert
14769 (set-buffer (get-buffer-create " *Org tags*"))
14770 (delete-other-windows)
14771 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
14772 (org-switch-to-buffer-other-window " *Org tags*"))
14773 (erase-buffer)
14774 (org-set-local 'org-done-keywords done-keywords)
14775 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14776 (org-fast-tag-insert "Current" current c-face "\n\n")
14777 (org-fast-tag-show-exit exit-after-next)
14778 (org-set-current-tags-overlay current ov-prefix)
14779 (setq tbl fulltable char ?a cnt 0)
14780 (while (setq e (pop tbl))
14781 (cond
14782 ((equal (car e) :startgroup)
14783 (push '() groups) (setq ingroup t)
14784 (when (not (= cnt 0))
14785 (setq cnt 0)
14786 (insert "\n"))
14787 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14788 ((equal (car e) :endgroup)
14789 (setq ingroup nil cnt 0)
14790 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14791 ((equal e '(:newline))
14792 (when (not (= cnt 0))
14793 (setq cnt 0)
14794 (insert "\n")
14795 (setq e (car tbl))
14796 (while (equal (car tbl) '(:newline))
14797 (insert "\n")
14798 (setq tbl (cdr tbl)))))
14799 ((equal e '(:grouptags)) nil)
14801 (setq tg (copy-sequence (car e)) c2 nil)
14802 (if (cdr e)
14803 (setq c (cdr e))
14804 ;; automatically assign a character.
14805 (setq c1 (string-to-char
14806 (downcase (substring
14807 tg (if (= (string-to-char tg) ?@) 1 0)))))
14808 (if (or (rassoc c1 ntable) (rassoc c1 table))
14809 (while (or (rassoc char ntable) (rassoc char table))
14810 (setq char (1+ char)))
14811 (setq c2 c1))
14812 (setq c (or c2 char)))
14813 (if ingroup (push tg (car groups)))
14814 (setq tg (org-add-props tg nil 'face
14815 (cond
14816 ((not (assoc tg table))
14817 (org-get-todo-face tg))
14818 ((member tg current) c-face)
14819 ((member tg inherited) i-face))))
14820 (if (equal (caar tbl) :grouptags)
14821 (org-add-props tg nil 'face 'org-tag-group))
14822 (if (and (= cnt 0) (not ingroup)) (insert " "))
14823 (insert "[" c "] " tg (make-string
14824 (- fwidth 4 (length tg)) ?\ ))
14825 (push (cons tg c) ntable)
14826 (when (= (setq cnt (1+ cnt)) ncol)
14827 (insert "\n")
14828 (if ingroup (insert " "))
14829 (setq cnt 0)))))
14830 (setq ntable (nreverse ntable))
14831 (insert "\n")
14832 (goto-char (point-min))
14833 (if (not expert) (org-fit-window-to-buffer))
14834 (setq rtn
14835 (catch 'exit
14836 (while t
14837 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14838 (if (not groups) "no " "")
14839 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14840 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14841 (setq org-last-tag-selection-key c)
14842 (cond
14843 ((= c ?\r) (throw 'exit t))
14844 ((= c ?!)
14845 (setq groups (not groups))
14846 (goto-char (point-min))
14847 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14848 ((= c ?\C-c)
14849 (if (not expert)
14850 (org-fast-tag-show-exit
14851 (setq exit-after-next (not exit-after-next)))
14852 (setq expert nil)
14853 (delete-other-windows)
14854 (set-window-buffer (split-window-vertically) " *Org tags*")
14855 (org-switch-to-buffer-other-window " *Org tags*")
14856 (org-fit-window-to-buffer)))
14857 ((or (= c ?\C-g)
14858 (and (= c ?q) (not (rassoc c ntable))))
14859 (org-detach-overlay org-tags-overlay)
14860 (setq quit-flag t))
14861 ((= c ?\ )
14862 (setq current nil)
14863 (if exit-after-next (setq exit-after-next 'now)))
14864 ((= c ?\t)
14865 (condition-case nil
14866 (setq tg (org-icompleting-read
14867 "Tag: "
14868 (or buffer-tags
14869 (with-current-buffer buf
14870 (org-get-buffer-tags)))))
14871 (quit (setq tg "")))
14872 (when (string-match "\\S-" tg)
14873 (add-to-list 'buffer-tags (list tg))
14874 (if (member tg current)
14875 (setq current (delete tg current))
14876 (push tg current)))
14877 (if exit-after-next (setq exit-after-next 'now)))
14878 ((setq e (rassoc c todo-table) tg (car e))
14879 (with-current-buffer buf
14880 (save-excursion (org-todo tg)))
14881 (if exit-after-next (setq exit-after-next 'now)))
14882 ((setq e (rassoc c ntable) tg (car e))
14883 (if (member tg current)
14884 (setq current (delete tg current))
14885 (loop for g in groups do
14886 (if (member tg g)
14887 (mapc (lambda (x)
14888 (setq current (delete x current)))
14889 g)))
14890 (push tg current))
14891 (if exit-after-next (setq exit-after-next 'now))))
14893 ;; Create a sorted list
14894 (setq current
14895 (sort current
14896 (lambda (a b)
14897 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14898 (if (eq exit-after-next 'now) (throw 'exit t))
14899 (goto-char (point-min))
14900 (beginning-of-line 2)
14901 (delete-region (point) (point-at-eol))
14902 (org-fast-tag-insert "Current" current c-face)
14903 (org-set-current-tags-overlay current ov-prefix)
14904 (while (re-search-forward
14905 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14906 (setq tg (match-string 1))
14907 (add-text-properties
14908 (match-beginning 1) (match-end 1)
14909 (list 'face
14910 (cond
14911 ((member tg current) c-face)
14912 ((member tg inherited) i-face)
14913 (t (get-text-property (match-beginning 1) 'face))))))
14914 (goto-char (point-min)))))
14915 (org-detach-overlay org-tags-overlay)
14916 (if rtn
14917 (mapconcat 'identity current ":")
14918 nil))))
14920 (defun org-get-tags-string ()
14921 "Get the TAGS string in the current headline."
14922 (unless (org-at-heading-p t)
14923 (user-error "Not on a heading"))
14924 (save-excursion
14925 (beginning-of-line 1)
14926 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14927 (org-match-string-no-properties 1)
14928 "")))
14930 (defun org-get-tags ()
14931 "Get the list of tags specified in the current headline."
14932 (org-split-string (org-get-tags-string) ":"))
14934 (defun org-get-buffer-tags ()
14935 "Get a table of all tags used in the buffer, for completion."
14936 (let (tags)
14937 (save-excursion
14938 (goto-char (point-min))
14939 (while (re-search-forward
14940 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14941 (when (equal (char-after (point-at-bol 0)) ?*)
14942 (mapc (lambda (x) (add-to-list 'tags x))
14943 (org-split-string (org-match-string-no-properties 1) ":")))))
14944 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14945 (mapcar 'list tags)))
14947 ;;;; The mapping API
14949 (defun org-map-entries (func &optional match scope &rest skip)
14950 "Call FUNC at each headline selected by MATCH in SCOPE.
14952 FUNC is a function or a lisp form. The function will be called without
14953 arguments, with the cursor positioned at the beginning of the headline.
14954 The return values of all calls to the function will be collected and
14955 returned as a list.
14957 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14958 does not need to preserve point. After evaluation, the cursor will be
14959 moved to the end of the line (presumably of the headline of the
14960 processed entry) and search continues from there. Under some
14961 circumstances, this may not produce the wanted results. For example,
14962 if you have removed (e.g. archived) the current (sub)tree it could
14963 mean that the next entry will be skipped entirely. In such cases, you
14964 can specify the position from where search should continue by making
14965 FUNC set the variable `org-map-continue-from' to the desired buffer
14966 position.
14968 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14969 Only headlines that are matched by this query will be considered during
14970 the iteration. When MATCH is nil or t, all headlines will be
14971 visited by the iteration.
14973 SCOPE determines the scope of this command. It can be any of:
14975 nil The current buffer, respecting the restriction if any
14976 tree The subtree started with the entry at point
14977 region The entries within the active region, if any
14978 region-start-level
14979 The entries within the active region, but only those at
14980 the same level than the first one.
14981 file The current buffer, without restriction
14982 file-with-archives
14983 The current buffer, and any archives associated with it
14984 agenda All agenda files
14985 agenda-with-archives
14986 All agenda files with any archive files associated with them
14987 \(file1 file2 ...)
14988 If this is a list, all files in the list will be scanned
14990 The remaining args are treated as settings for the skipping facilities of
14991 the scanner. The following items can be given here:
14993 archive skip trees with the archive tag
14994 comment skip trees with the COMMENT keyword
14995 function or Emacs Lisp form:
14996 will be used as value for `org-agenda-skip-function', so
14997 whenever the function returns a position, FUNC will not be
14998 called for that entry and search will continue from the
14999 position returned
15001 If your function needs to retrieve the tags including inherited tags
15002 at the *current* entry, you can use the value of the variable
15003 `org-scanner-tags' which will be much faster than getting the value
15004 with `org-get-tags-at'. If your function gets properties with
15005 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15006 to t around the call to `org-entry-properties' to get the same speedup.
15007 Note that if your function moves around to retrieve tags and properties at
15008 a *different* entry, you cannot use these techniques."
15009 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15010 (not (org-region-active-p)))
15011 (let* ((org-agenda-archives-mode nil) ; just to make sure
15012 (org-agenda-skip-archived-trees (memq 'archive skip))
15013 (org-agenda-skip-comment-trees (memq 'comment skip))
15014 (org-agenda-skip-function
15015 (car (org-delete-all '(comment archive) skip)))
15016 (org-tags-match-list-sublevels t)
15017 (start-level (eq scope 'region-start-level))
15018 matcher file res
15019 org-todo-keywords-for-agenda
15020 org-done-keywords-for-agenda
15021 org-todo-keyword-alist-for-agenda
15022 org-drawers-for-agenda
15023 org-tag-alist-for-agenda
15024 todo-only)
15026 (cond
15027 ((eq match t) (setq matcher t))
15028 ((eq match nil) (setq matcher t))
15029 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15031 (save-excursion
15032 (save-restriction
15033 (cond ((eq scope 'tree)
15034 (org-back-to-heading t)
15035 (org-narrow-to-subtree)
15036 (setq scope nil))
15037 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15038 (org-region-active-p))
15039 ;; If needed, set start-level to a string like "2"
15040 (when start-level
15041 (save-excursion
15042 (goto-char (region-beginning))
15043 (unless (org-at-heading-p) (outline-next-heading))
15044 (setq start-level (org-current-level))))
15045 (narrow-to-region (region-beginning)
15046 (save-excursion
15047 (goto-char (region-end))
15048 (unless (and (bolp) (org-at-heading-p))
15049 (outline-next-heading))
15050 (point)))
15051 (setq scope nil)))
15053 (if (not scope)
15054 (progn
15055 (org-agenda-prepare-buffers
15056 (list (buffer-file-name (current-buffer))))
15057 (setq res (org-scan-tags func matcher todo-only start-level)))
15058 ;; Get the right scope
15059 (cond
15060 ((and scope (listp scope) (symbolp (car scope)))
15061 (setq scope (eval scope)))
15062 ((eq scope 'agenda)
15063 (setq scope (org-agenda-files t)))
15064 ((eq scope 'agenda-with-archives)
15065 (setq scope (org-agenda-files t))
15066 (setq scope (org-add-archive-files scope)))
15067 ((eq scope 'file)
15068 (setq scope (list (buffer-file-name))))
15069 ((eq scope 'file-with-archives)
15070 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15071 (org-agenda-prepare-buffers scope)
15072 (while (setq file (pop scope))
15073 (with-current-buffer (org-find-base-buffer-visiting file)
15074 (save-excursion
15075 (save-restriction
15076 (widen)
15077 (goto-char (point-min))
15078 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
15079 res)))
15081 ;;;; Properties
15083 ;;; Setting and retrieving properties
15085 (defconst org-special-properties
15086 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
15087 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
15088 "The special properties valid in Org-mode.
15090 These are properties that are not defined in the property drawer,
15091 but in some other way.")
15093 (defconst org-default-properties
15094 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15095 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15096 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15097 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15098 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
15099 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15100 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15101 "Some properties that are used by Org-mode for various purposes.
15102 Being in this list makes sure that they are offered for completion.")
15104 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
15105 "Regular expression matching the first line of a property drawer.")
15107 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
15108 "Regular expression matching the last line of a property drawer.")
15110 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
15111 "Regular expression matching the first line of a property drawer.")
15113 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
15114 "Regular expression matching the first line of a property drawer.")
15116 (defconst org-property-drawer-re
15117 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
15118 org-property-end-re "\\)\n?")
15119 "Matches an entire property drawer.")
15121 (defconst org-clock-drawer-re
15122 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
15123 org-property-end-re "\\)\n?")
15124 "Matches an entire clock drawer.")
15126 (defun org-property-action ()
15127 "Do an action on properties."
15128 (interactive)
15129 (let (c)
15130 (org-at-property-p)
15131 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15132 (setq c (read-char-exclusive))
15133 (cond
15134 ((equal c ?s)
15135 (call-interactively 'org-set-property))
15136 ((equal c ?d)
15137 (call-interactively 'org-delete-property))
15138 ((equal c ?D)
15139 (call-interactively 'org-delete-property-globally))
15140 ((equal c ?c)
15141 (call-interactively 'org-compute-property-at-point))
15142 (t (user-error "No such property action %c" c)))))
15144 (defun org-inc-effort ()
15145 "Increment the value of the effort property in the current entry."
15146 (interactive)
15147 (org-set-effort nil t))
15149 (defvar org-clock-effort) ;; Defined in org-clock.el
15150 (defvar org-clock-current-task) ;; Defined in org-clock.el
15151 (defun org-set-effort (&optional value increment)
15152 "Set the effort property of the current entry.
15153 With numerical prefix arg, use the nth allowed value, 0 stands for the
15154 10th allowed value.
15156 When INCREMENT is non-nil, set the property to the next allowed value."
15157 (interactive "P")
15158 (if (equal value 0) (setq value 10))
15159 (let* ((completion-ignore-case t)
15160 (prop org-effort-property)
15161 (cur (org-entry-get nil prop))
15162 (allowed (org-property-get-allowed-values nil prop 'table))
15163 (existing (mapcar 'list (org-property-values prop)))
15164 (heading (nth 4 (org-heading-components)))
15166 (val (cond
15167 ((stringp value) value)
15168 ((and allowed (integerp value))
15169 (or (car (nth (1- value) allowed))
15170 (car (org-last allowed))))
15171 ((and allowed increment)
15172 (or (caadr (member (list cur) allowed))
15173 (user-error "Allowed effort values are not set")))
15174 (allowed
15175 (message "Select 1-9,0, [RET%s]: %s"
15176 (if cur (concat "=" cur) "")
15177 (mapconcat 'car allowed " "))
15178 (setq rpl (read-char-exclusive))
15179 (if (equal rpl ?\r)
15181 (setq rpl (- rpl ?0))
15182 (if (equal rpl 0) (setq rpl 10))
15183 (if (and (> rpl 0) (<= rpl (length allowed)))
15184 (car (nth (1- rpl) allowed))
15185 (org-completing-read "Effort: " allowed nil))))
15187 (let (org-completion-use-ido org-completion-use-iswitchb)
15188 (org-completing-read
15189 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15190 (concat "[" cur "]") "")
15191 ": ")
15192 existing nil nil "" nil cur))))))
15193 (unless (equal (org-entry-get nil prop) val)
15194 (org-entry-put nil prop val))
15195 (save-excursion
15196 (org-back-to-heading t)
15197 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
15198 (when (string= heading org-clock-current-task)
15199 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
15200 (org-clock-update-mode-line))
15201 (message "%s is now %s" prop val)))
15203 (defun org-at-property-p ()
15204 "Is cursor inside a property drawer?"
15205 (save-excursion
15206 (when (equal 'node-property (car (org-element-at-point)))
15207 (beginning-of-line 1)
15208 (looking-at org-property-re))))
15210 (defun org-get-property-block (&optional beg end force)
15211 "Return the (beg . end) range of the body of the property drawer.
15212 BEG and END are the beginning and end of the current subtree, or of
15213 the part before the first headline. If they are not given, they will
15214 be found. If the drawer does not exist and FORCE is non-nil, create
15215 the drawer."
15216 (catch 'exit
15217 (save-excursion
15218 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15219 (progn (org-back-to-heading t) (point))))
15220 (end (or end (and (not (outline-next-heading)) (point-max))
15221 (point))))
15222 (goto-char beg)
15223 (if (re-search-forward org-property-start-re end t)
15224 (setq beg (1+ (match-end 0)))
15225 (if force
15226 (save-excursion
15227 (org-insert-property-drawer)
15228 (setq end (progn (outline-next-heading) (point))))
15229 (throw 'exit nil))
15230 (goto-char beg)
15231 (if (re-search-forward org-property-start-re end t)
15232 (setq beg (1+ (match-end 0)))))
15233 (if (re-search-forward org-property-end-re end t)
15234 (setq end (match-beginning 0))
15235 (or force (throw 'exit nil))
15236 (goto-char beg)
15237 (setq end beg)
15238 (org-indent-line)
15239 (insert ":END:\n"))
15240 (cons beg end)))))
15242 (defun org-entry-properties (&optional pom which specific)
15243 "Get all properties of the entry at point-or-marker POM.
15244 This includes the TODO keyword, the tags, time strings for deadline,
15245 scheduled, and clocking, and any additional properties defined in the
15246 entry. The return value is an alist, keys may occur multiple times
15247 if the property key was used several times.
15248 POM may also be nil, in which case the current entry is used.
15249 If WHICH is nil or `all', get all properties. If WHICH is
15250 `special' or `standard', only get that subclass. If WHICH
15251 is a string only get exactly this property. SPECIFIC can be a string, the
15252 specific property we are interested in. Specifying it can speed
15253 things up because then unnecessary parsing is avoided."
15254 (setq which (or which 'all))
15255 (org-with-wide-buffer
15256 (org-with-point-at pom
15257 (let ((clockstr (substring org-clock-string 0 -1))
15258 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15259 (case-fold-search nil)
15260 beg end range props sum-props key key1 value string clocksum clocksumt)
15261 (when (and (derived-mode-p 'org-mode)
15262 (ignore-errors (org-back-to-heading t)))
15263 (setq beg (point))
15264 (setq sum-props (get-text-property (point) 'org-summaries))
15265 (setq clocksum (get-text-property (point) :org-clock-minutes)
15266 clocksumt (get-text-property (point) :org-clock-minutes-today))
15267 (outline-next-heading)
15268 (setq end (point))
15269 (when (memq which '(all special))
15270 ;; Get the special properties, like TODO and tags
15271 (goto-char beg)
15272 (when (and (or (not specific) (string= specific "TODO"))
15273 (looking-at org-todo-line-regexp) (match-end 2))
15274 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15275 (when (and (or (not specific) (string= specific "PRIORITY"))
15276 (looking-at org-priority-regexp))
15277 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15278 (when (or (not specific) (string= specific "FILE"))
15279 (push (cons "FILE" buffer-file-name) props))
15280 (when (and (or (not specific) (string= specific "TAGS"))
15281 (setq value (org-get-tags-string))
15282 (string-match "\\S-" value))
15283 (push (cons "TAGS" value) props))
15284 (when (and (or (not specific) (string= specific "ALLTAGS"))
15285 (setq value (org-get-tags-at)))
15286 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15287 ":"))
15288 props))
15289 (when (or (not specific) (string= specific "BLOCKED"))
15290 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15291 (when (or (not specific)
15292 (member specific
15293 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15294 "TIMESTAMP" "TIMESTAMP_IA")))
15295 (catch 'match
15296 (while (and (re-search-forward org-maybe-keyword-time-regexp end t)
15297 (not (text-property-any 0 (length (match-string 0))
15298 'face 'font-lock-comment-face
15299 (match-string 0))))
15300 (setq key (if (match-end 1)
15301 (substring (org-match-string-no-properties 1)
15302 0 -1))
15303 string (if (equal key clockstr)
15304 (org-trim
15305 (buffer-substring-no-properties
15306 (match-beginning 3) (goto-char
15307 (point-at-eol))))
15308 (substring (org-match-string-no-properties 3)
15309 1 -1)))
15310 ;; Get the correct property name from the key. This is
15311 ;; necessary if the user has configured time keywords.
15312 (setq key1 (concat key ":"))
15313 (cond
15314 ((not key)
15315 (setq key
15316 (if (= (char-after (match-beginning 3)) ?\[)
15317 "TIMESTAMP_IA" "TIMESTAMP")))
15318 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15319 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15320 ((equal key1 org-closed-string) (setq key "CLOSED"))
15321 ((equal key1 org-clock-string) (setq key "CLOCK")))
15322 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15323 (progn
15324 (push (cons key string) props)
15325 ;; no need to search further if match is found
15326 (throw 'match t))
15327 (when (or (equal key "CLOCK") (not (assoc key props)))
15328 (push (cons key string) props)))))))
15330 (when (memq which '(all standard))
15331 ;; Get the standard properties, like :PROP: ...
15332 (setq range (org-get-property-block beg end))
15333 (when range
15334 (goto-char (car range))
15335 (while (re-search-forward org-property-re
15336 (cdr range) t)
15337 (setq key (org-match-string-no-properties 2)
15338 value (org-trim (or (org-match-string-no-properties 3) "")))
15339 (unless (member key excluded)
15340 (push (cons key (or value "")) props)))))
15341 (if clocksum
15342 (push (cons "CLOCKSUM"
15343 (org-columns-number-to-string (/ (float clocksum) 60.)
15344 'add_times))
15345 props))
15346 (if clocksumt
15347 (push (cons "CLOCKSUM_T"
15348 (org-columns-number-to-string (/ (float clocksumt) 60.)
15349 'add_times))
15350 props))
15351 (unless (assoc "CATEGORY" props)
15352 (push (cons "CATEGORY" (org-get-category)) props))
15353 (append sum-props (nreverse props)))))))
15355 (defun org-entry-get (pom property &optional inherit literal-nil)
15356 "Get value of PROPERTY for entry or content at point-or-marker POM.
15357 If INHERIT is non-nil and the entry does not have the property,
15358 then also check higher levels of the hierarchy.
15359 If INHERIT is the symbol `selective', use inheritance only if the setting
15360 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15361 If the property is present but empty, the return value is the empty string.
15362 If the property is not present at all, nil is returned.
15364 Return the value as a string.
15366 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15367 do not interpret it as the list atom nil. This is used for inheritance
15368 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15369 (org-with-point-at pom
15370 (if (and inherit (if (eq inherit 'selective)
15371 (org-property-inherit-p property)
15373 (org-entry-get-with-inheritance property literal-nil)
15374 (if (member property org-special-properties)
15375 ;; We need a special property. Use `org-entry-properties'
15376 ;; to retrieve it, but specify the wanted property
15377 (cdr (assoc property (org-entry-properties nil 'special property)))
15378 (org-with-wide-buffer
15379 (let ((range (org-get-property-block)))
15380 (when (and range (not (eq (car range) (cdr range)))
15381 (save-excursion
15382 (goto-char (car range))
15383 (re-search-forward
15384 (concat (org-re-property property) "\\|"
15385 (org-re-property (concat property "+")))
15386 (cdr range) t)))
15387 (let* ((props
15388 (list (or (assoc property org-file-properties)
15389 (assoc property org-global-properties)
15390 (assoc property org-global-properties-fixed))))
15391 (ap (lambda (key)
15392 (when (re-search-forward
15393 (org-re-property key) (cdr range) t)
15394 (setq props
15395 (org-update-property-plist
15397 (if (match-end 3)
15398 (org-match-string-no-properties 3) "")
15399 props)))))
15400 val)
15401 (goto-char (car range))
15402 (funcall ap property)
15403 (goto-char (car range))
15404 (while (funcall ap (concat property "+")))
15405 (setq val (cdr (assoc property props)))
15406 (when val (if literal-nil val (org-not-nil val)))))))))))
15408 (defun org-property-or-variable-value (var &optional inherit)
15409 "Check if there is a property fixing the value of VAR.
15410 If yes, return this value. If not, return the current value of the variable."
15411 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15412 (if (and prop (stringp prop) (string-match "\\S-" prop))
15413 (read prop)
15414 (symbol-value var))))
15416 (defun org-entry-delete (pom property &optional delete-empty-drawer)
15417 "Delete the property PROPERTY from entry at point-or-marker POM.
15418 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15419 an empty drawer to delete."
15420 (org-with-point-at pom
15421 (if (member property org-special-properties)
15422 nil ; cannot delete these properties.
15423 (let ((range (org-get-property-block)))
15424 (if (and range
15425 (goto-char (car range))
15426 (re-search-forward
15427 (org-re-property property)
15428 (cdr range) t))
15429 (progn
15430 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15431 (and delete-empty-drawer
15432 (org-remove-empty-drawer-at
15433 delete-empty-drawer (car range)))
15435 nil)))))
15437 ;; Multi-values properties are properties that contain multiple values
15438 ;; These values are assumed to be single words, separated by whitespace.
15439 (defun org-entry-add-to-multivalued-property (pom property value)
15440 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15441 (let* ((old (org-entry-get pom property))
15442 (values (and old (org-split-string old "[ \t]"))))
15443 (setq value (org-entry-protect-space value))
15444 (unless (member value values)
15445 (setq values (append values (list value)))
15446 (org-entry-put pom property
15447 (mapconcat 'identity values " ")))))
15449 (defun org-entry-remove-from-multivalued-property (pom property value)
15450 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15451 (let* ((old (org-entry-get pom property))
15452 (values (and old (org-split-string old "[ \t]"))))
15453 (setq value (org-entry-protect-space value))
15454 (when (member value values)
15455 (setq values (delete value values))
15456 (org-entry-put pom property
15457 (mapconcat 'identity values " ")))))
15459 (defun org-entry-member-in-multivalued-property (pom property value)
15460 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15461 (let* ((old (org-entry-get pom property))
15462 (values (and old (org-split-string old "[ \t]"))))
15463 (setq value (org-entry-protect-space value))
15464 (member value values)))
15466 (defun org-entry-get-multivalued-property (pom property)
15467 "Return a list of values in a multivalued property."
15468 (let* ((value (org-entry-get pom property))
15469 (values (and value (org-split-string value "[ \t]"))))
15470 (mapcar 'org-entry-restore-space values)))
15472 (defun org-entry-put-multivalued-property (pom property &rest values)
15473 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15474 VALUES should be a list of strings. Spaces will be protected."
15475 (org-entry-put pom property
15476 (mapconcat 'org-entry-protect-space values " "))
15477 (let* ((value (org-entry-get pom property))
15478 (values (and value (org-split-string value "[ \t]"))))
15479 (mapcar 'org-entry-restore-space values)))
15481 (defun org-entry-protect-space (s)
15482 "Protect spaces and newline in string S."
15483 (while (string-match " " s)
15484 (setq s (replace-match "%20" t t s)))
15485 (while (string-match "\n" s)
15486 (setq s (replace-match "%0A" t t s)))
15489 (defun org-entry-restore-space (s)
15490 "Restore spaces and newline in string S."
15491 (while (string-match "%20" s)
15492 (setq s (replace-match " " t t s)))
15493 (while (string-match "%0A" s)
15494 (setq s (replace-match "\n" t t s)))
15497 (defvar org-entry-property-inherited-from (make-marker)
15498 "Marker pointing to the entry from where a property was inherited.
15499 Each call to `org-entry-get-with-inheritance' will set this marker to the
15500 location of the entry where the inheritance search matched. If there was
15501 no match, the marker will point nowhere.
15502 Note that also `org-entry-get' calls this function, if the INHERIT flag
15503 is set.")
15505 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15506 "Get PROPERTY of entry or content at point, search higher levels if needed.
15507 The search will stop at the first ancestor which has the property defined.
15508 If the value found is \"nil\", return nil to show that the property
15509 should be considered as undefined (this is the meaning of nil here).
15510 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15511 (move-marker org-entry-property-inherited-from nil)
15512 (let (tmp)
15513 (save-excursion
15514 (save-restriction
15515 (widen)
15516 (catch 'ex
15517 (while t
15518 (when (setq tmp (org-entry-get nil property nil literal-nil))
15519 (or (ignore-errors (org-back-to-heading t))
15520 (goto-char (point-min)))
15521 (move-marker org-entry-property-inherited-from (point))
15522 (throw 'ex tmp))
15523 (or (ignore-errors (org-up-heading-safe))
15524 (throw 'ex nil))))))
15525 (setq tmp (or tmp
15526 (cdr (assoc property org-file-properties))
15527 (cdr (assoc property org-global-properties))
15528 (cdr (assoc property org-global-properties-fixed))))
15529 (if literal-nil tmp (org-not-nil tmp))))
15531 (defvar org-property-changed-functions nil
15532 "Hook called when the value of a property has changed.
15533 Each hook function should accept two arguments, the name of the property
15534 and the new value.")
15536 (defun org-entry-put (pom property value)
15537 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15538 If the value is `nil', it is converted to the empty string.
15539 If it is not a string, an error is raised."
15540 (cond ((null value) (setq value ""))
15541 ((not (stringp value))
15542 (error "Properties values should be strings.")))
15543 (org-with-point-at pom
15544 (org-back-to-heading t)
15545 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15546 range)
15547 (cond
15548 ((equal property "TODO")
15549 (when (and (string-match "\\S-" value)
15550 (not (member value org-todo-keywords-1)))
15551 (user-error "\"%s\" is not a valid TODO state" value))
15552 (if (or (not value)
15553 (not (string-match "\\S-" value)))
15554 (setq value 'none))
15555 (org-todo value)
15556 (org-set-tags nil 'align))
15557 ((equal property "PRIORITY")
15558 (org-priority (if (and value (string-match "\\S-" value))
15559 (string-to-char value) ?\ ))
15560 (org-set-tags nil 'align))
15561 ((equal property "CLOCKSUM")
15562 (if (not (re-search-forward
15563 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15564 (error "Cannot find a clock log")
15565 (goto-char (- (match-end 1) 2))
15566 (cond
15567 ((eq value 'earlier) (org-timestamp-down))
15568 ((eq value 'later) (org-timestamp-up)))
15569 (org-clock-sum-current-item)))
15570 ((equal property "SCHEDULED")
15571 (if (re-search-forward org-scheduled-time-regexp end t)
15572 (cond
15573 ((eq value 'earlier) (org-timestamp-change -1 'day))
15574 ((eq value 'later) (org-timestamp-change 1 'day))
15575 (t (call-interactively 'org-schedule)))
15576 (call-interactively 'org-schedule)))
15577 ((equal property "DEADLINE")
15578 (if (re-search-forward org-deadline-time-regexp end t)
15579 (cond
15580 ((eq value 'earlier) (org-timestamp-change -1 'day))
15581 ((eq value 'later) (org-timestamp-change 1 'day))
15582 (t (call-interactively 'org-deadline)))
15583 (call-interactively 'org-deadline)))
15584 ((member property org-special-properties)
15585 (error "The %s property can not yet be set with `org-entry-put'"
15586 property))
15587 (t ; a non-special property
15588 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15589 (setq range (org-get-property-block beg end 'force))
15590 (goto-char (car range))
15591 (if (re-search-forward
15592 (org-re-property property) (cdr range) t)
15593 (progn
15594 (delete-region (match-beginning 0) (match-end 0))
15595 (goto-char (match-beginning 0)))
15596 (goto-char (cdr range))
15597 (insert "\n")
15598 (backward-char 1)
15599 (org-indent-line))
15600 (insert ":" property ":")
15601 (and value (insert " " value))
15602 (org-indent-line)))))
15603 (run-hook-with-args 'org-property-changed-functions property value)))
15605 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15606 "Get all property keys in the current buffer.
15607 With INCLUDE-SPECIALS, also list the special properties that reflect things
15608 like tags and TODO state.
15609 With INCLUDE-DEFAULTS, also include properties that has special meaning
15610 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15611 and others.
15612 With INCLUDE-COLUMNS, also include property names given in COLUMN
15613 formats in the current buffer."
15614 (let (rtn range cfmt s p)
15615 (save-excursion
15616 (save-restriction
15617 (widen)
15618 (goto-char (point-min))
15619 (while (re-search-forward org-property-start-re nil t)
15620 (setq range (org-get-property-block))
15621 (goto-char (car range))
15622 (while (re-search-forward org-property-re
15623 (cdr range) t)
15624 (add-to-list 'rtn (org-match-string-no-properties 2)))
15625 (outline-next-heading))))
15627 (when include-specials
15628 (setq rtn (append org-special-properties rtn)))
15630 (when include-defaults
15631 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15632 (add-to-list 'rtn org-effort-property))
15634 (when include-columns
15635 (save-excursion
15636 (save-restriction
15637 (widen)
15638 (goto-char (point-min))
15639 (while (re-search-forward
15640 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15641 nil t)
15642 (setq cfmt (match-string 2) s 0)
15643 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15644 cfmt s)
15645 (setq s (match-end 0)
15646 p (match-string 1 cfmt))
15647 (unless (or (equal p "ITEM")
15648 (member p org-special-properties))
15649 (add-to-list 'rtn (match-string 1 cfmt))))))))
15651 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15653 (defun org-property-values (key)
15654 "Return a list of all values of property KEY in the current buffer."
15655 (save-excursion
15656 (save-restriction
15657 (widen)
15658 (goto-char (point-min))
15659 (let ((re (org-re-property key))
15660 values)
15661 (while (re-search-forward re nil t)
15662 (add-to-list 'values (org-trim (match-string 3))))
15663 (delete "" values)))))
15665 (defun org-insert-property-drawer ()
15666 "Insert a property drawer into the current entry."
15667 (org-back-to-heading t)
15668 (looking-at org-outline-regexp)
15669 (let ((indent (if org-adapt-indentation
15670 (- (match-end 0) (match-beginning 0))
15672 (beg (point))
15673 (re (concat "^[ \t]*" org-keyword-time-regexp))
15674 end hiddenp)
15675 (outline-next-heading)
15676 (setq end (point))
15677 (goto-char beg)
15678 (while (re-search-forward re end t))
15679 (setq hiddenp (outline-invisible-p))
15680 (end-of-line 1)
15681 (and (equal (char-after) ?\n) (forward-char 1))
15682 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15683 (if (member (match-string 1) '("CLOCK:" ":END:"))
15684 ;; just skip this line
15685 (beginning-of-line 2)
15686 ;; Drawer start, find the end
15687 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15688 (beginning-of-line 1)))
15689 (org-skip-over-state-notes)
15690 (skip-chars-backward " \t\n\r")
15691 (if (and (eq (char-before) ?*) (not (eq (char-after) ?\n)))
15692 (forward-char 1))
15693 (goto-char (point-at-eol))
15694 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15695 (beginning-of-line 0)
15696 (org-indent-to-column indent)
15697 (beginning-of-line 2)
15698 (org-indent-to-column indent)
15699 (beginning-of-line 0)
15700 (if hiddenp
15701 (save-excursion
15702 (org-back-to-heading t)
15703 (hide-entry))
15704 (org-flag-drawer t))))
15706 (defun org-insert-drawer (&optional arg drawer)
15707 "Insert a drawer at point.
15709 Optional argument DRAWER, when non-nil, is a string representing
15710 drawer's name. Otherwise, the user is prompted for a name.
15712 If a region is active, insert the drawer around that region
15713 instead.
15715 Point is left between drawer's boundaries."
15716 (interactive "P")
15717 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15718 "LOGBOOK"))
15719 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15720 ;; internally by Org. They are meant to be inserted
15721 ;; automatically.
15722 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15723 ;; Remove system drawers from list. Note: For some reason,
15724 ;; `org-completing-read' ignores the predicate while
15725 ;; `completing-read' handles it fine.
15726 (drawer (if arg "PROPERTIES"
15727 (or drawer
15728 (completing-read
15729 "Drawer: " org-drawers
15730 (lambda (d) (not (member d system-drawers))))))))
15731 (cond
15732 ;; With C-u, fall back on `org-insert-property-drawer'
15733 (arg (org-insert-property-drawer))
15734 ;; With an active region, insert a drawer at point.
15735 ((not (org-region-active-p))
15736 (progn
15737 (unless (bolp) (insert "\n"))
15738 (insert (format ":%s:\n\n:END:\n" drawer))
15739 (forward-line -2)))
15740 ;; Otherwise, insert the drawer at point
15742 (let ((rbeg (region-beginning))
15743 (rend (copy-marker (region-end))))
15744 (unwind-protect
15745 (progn
15746 (goto-char rbeg)
15747 (beginning-of-line)
15748 (when (save-excursion
15749 (re-search-forward org-outline-regexp-bol rend t))
15750 (user-error "Drawers cannot contain headlines"))
15751 ;; Position point at the beginning of the first
15752 ;; non-blank line in region. Insert drawer's opening
15753 ;; there, then indent it.
15754 (org-skip-whitespace)
15755 (beginning-of-line)
15756 (insert ":" drawer ":\n")
15757 (forward-line -1)
15758 (indent-for-tab-command)
15759 ;; Move point to the beginning of the first blank line
15760 ;; after the last non-blank line in region. Insert
15761 ;; drawer's closing, then indent it.
15762 (goto-char rend)
15763 (skip-chars-backward " \r\t\n")
15764 (insert "\n:END:")
15765 (deactivate-mark t)
15766 (indent-for-tab-command)
15767 (unless (eolp) (insert "\n")))
15768 ;; Clear marker, whatever the outcome of insertion is.
15769 (set-marker rend nil)))))))
15771 (defvar org-property-set-functions-alist nil
15772 "Property set function alist.
15773 Each entry should have the following format:
15775 (PROPERTY . READ-FUNCTION)
15777 The read function will be called with the same argument as
15778 `org-completing-read'.")
15780 (defun org-set-property-function (property)
15781 "Get the function that should be used to set PROPERTY.
15782 This is computed according to `org-property-set-functions-alist'."
15783 (or (cdr (assoc property org-property-set-functions-alist))
15784 'org-completing-read))
15786 (defun org-read-property-value (property)
15787 "Read PROPERTY value from user."
15788 (let* ((completion-ignore-case t)
15789 (allowed (org-property-get-allowed-values nil property 'table))
15790 (cur (org-entry-get nil property))
15791 (prompt (concat property " value"
15792 (if (and cur (string-match "\\S-" cur))
15793 (concat " [" cur "]") "") ": "))
15794 (set-function (org-set-property-function property))
15795 (val (if allowed
15796 (funcall set-function prompt allowed nil
15797 (not (get-text-property 0 'org-unrestricted
15798 (caar allowed))))
15799 (let (org-completion-use-ido org-completion-use-iswitchb)
15800 (funcall set-function prompt
15801 (mapcar 'list (org-property-values property))
15802 nil nil "" nil cur)))))
15803 (if (equal val "")
15805 val)))
15807 (defvar org-last-set-property nil)
15808 (defvar org-last-set-property-value nil)
15809 (defun org-read-property-name ()
15810 "Read a property name."
15811 (let* ((completion-ignore-case t)
15812 (keys (org-buffer-property-keys nil t t))
15813 (default-prop (or (save-excursion
15814 (save-match-data
15815 (beginning-of-line)
15816 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15817 (null (string= (match-string 1) "END"))
15818 (match-string 1))))
15819 org-last-set-property))
15820 (property (org-icompleting-read
15821 (concat "Property"
15822 (if default-prop (concat " [" default-prop "]") "")
15823 ": ")
15824 (mapcar 'list keys)
15825 nil nil nil nil
15826 default-prop)))
15827 (if (member property keys)
15828 property
15829 (or (cdr (assoc (downcase property)
15830 (mapcar (lambda (x) (cons (downcase x) x))
15831 keys)))
15832 property))))
15834 (defun org-set-property-and-value (use-last)
15835 "Allow to set [PROPERTY]: [value] direction from prompt.
15836 When use-default, don't even ask, just use the last
15837 \"[PROPERTY]: [value]\" string from the history."
15838 (interactive "P")
15839 (let* ((completion-ignore-case t)
15840 (pv (or (and use-last org-last-set-property-value)
15841 (org-completing-read
15842 "Enter a \"[Property]: [value]\" pair: "
15843 nil nil nil nil nil
15844 org-last-set-property-value)))
15845 prop val)
15846 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15847 (setq prop (match-string 1 pv)
15848 val (match-string 2 pv))
15849 (org-set-property prop val))))
15851 (defun org-set-property (property value)
15852 "In the current entry, set PROPERTY to VALUE.
15853 When called interactively, this will prompt for a property name, offering
15854 completion on existing and default properties. And then it will prompt
15855 for a value, offering completion either on allowed values (via an inherited
15856 xxx_ALL property) or on existing values in other instances of this property
15857 in the current file."
15858 (interactive (list nil nil))
15859 (let* ((property (or property (org-read-property-name)))
15860 (value (or value (org-read-property-value property)))
15861 (fn (cdr (assoc property org-properties-postprocess-alist))))
15862 (setq org-last-set-property property)
15863 (setq org-last-set-property-value (concat property ": " value))
15864 ;; Possibly postprocess the inserted value:
15865 (when fn (setq value (funcall fn value)))
15866 (unless (equal (org-entry-get nil property) value)
15867 (org-entry-put nil property value))))
15869 (defun org-delete-property (property &optional delete-empty-drawer)
15870 "In the current entry, delete PROPERTY.
15871 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15872 an empty drawer to delete."
15873 (interactive
15874 (let* ((completion-ignore-case t)
15875 (cat (org-entry-get (point) "CATEGORY"))
15876 (props0 (org-entry-properties nil 'standard))
15877 (props (if cat props0
15878 (delete `("CATEGORY" . ,(org-get-category)) props0)))
15879 (prop (if (< 1 (length props))
15880 (org-icompleting-read "Property: " props nil t)
15881 (caar props))))
15882 (list prop)))
15883 (if (org-entry-delete nil property delete-empty-drawer)
15884 (message "Property %s deleted" property)))
15886 (defun org-delete-property-globally (property)
15887 "Remove PROPERTY globally, from all entries."
15888 (interactive
15889 (let* ((completion-ignore-case t)
15890 (prop (org-icompleting-read
15891 "Globally remove property: "
15892 (mapcar 'list (org-buffer-property-keys)))))
15893 (list prop)))
15894 (save-excursion
15895 (save-restriction
15896 (widen)
15897 (goto-char (point-min))
15898 (let ((cnt 0))
15899 (while (re-search-forward
15900 (org-re-property property)
15901 nil t)
15902 (setq cnt (1+ cnt))
15903 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15904 (message "Property \"%s\" removed from %d entries" property cnt)))))
15906 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15908 (defun org-compute-property-at-point ()
15909 "Compute the property at point.
15910 This looks for an enclosing column format, extracts the operator and
15911 then applies it to the property in the column format's scope."
15912 (interactive)
15913 (unless (org-at-property-p)
15914 (user-error "Not at a property"))
15915 (let ((prop (org-match-string-no-properties 2)))
15916 (org-columns-get-format-and-top-level)
15917 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15918 (user-error "No operator defined for property %s" prop))
15919 (org-columns-compute prop)))
15921 (defvar org-property-allowed-value-functions nil
15922 "Hook for functions supplying allowed values for a specific property.
15923 The functions must take a single argument, the name of the property, and
15924 return a flat list of allowed values. If \":ETC\" is one of
15925 the values, this means that these values are intended as defaults for
15926 completion, but that other values should be allowed too.
15927 The functions must return nil if they are not responsible for this
15928 property.")
15930 (defun org-property-get-allowed-values (pom property &optional table)
15931 "Get allowed values for the property PROPERTY.
15932 When TABLE is non-nil, return an alist that can directly be used for
15933 completion."
15934 (let (vals)
15935 (cond
15936 ((equal property "TODO")
15937 (setq vals (org-with-point-at pom
15938 (append org-todo-keywords-1 '("")))))
15939 ((equal property "PRIORITY")
15940 (let ((n org-lowest-priority))
15941 (while (>= n org-highest-priority)
15942 (push (char-to-string n) vals)
15943 (setq n (1- n)))))
15944 ((member property org-special-properties))
15945 ((setq vals (run-hook-with-args-until-success
15946 'org-property-allowed-value-functions property)))
15948 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15949 (when (and vals (string-match "\\S-" vals))
15950 (setq vals (car (read-from-string (concat "(" vals ")"))))
15951 (setq vals (mapcar (lambda (x)
15952 (cond ((stringp x) x)
15953 ((numberp x) (number-to-string x))
15954 ((symbolp x) (symbol-name x))
15955 (t "???")))
15956 vals)))))
15957 (when (member ":ETC" vals)
15958 (setq vals (remove ":ETC" vals))
15959 (org-add-props (car vals) '(org-unrestricted t)))
15960 (if table (mapcar 'list vals) vals)))
15962 (defun org-property-previous-allowed-value (&optional previous)
15963 "Switch to the next allowed value for this property."
15964 (interactive)
15965 (org-property-next-allowed-value t))
15967 (defun org-property-next-allowed-value (&optional previous)
15968 "Switch to the next allowed value for this property."
15969 (interactive)
15970 (unless (org-at-property-p)
15971 (user-error "Not at a property"))
15972 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15973 (key (match-string 2))
15974 (value (match-string 3))
15975 (allowed (or (org-property-get-allowed-values (point) key)
15976 (and (member value '("[ ]" "[-]" "[X]"))
15977 '("[ ]" "[X]"))))
15978 (heading (save-match-data (nth 4 (org-heading-components))))
15979 nval)
15980 (unless allowed
15981 (user-error "Allowed values for this property have not been defined"))
15982 (if previous (setq allowed (reverse allowed)))
15983 (if (member value allowed)
15984 (setq nval (car (cdr (member value allowed)))))
15985 (setq nval (or nval (car allowed)))
15986 (if (equal nval value)
15987 (user-error "Only one allowed value for this property"))
15988 (org-at-property-p)
15989 (replace-match (concat " :" key ": " nval) t t)
15990 (org-indent-line)
15991 (beginning-of-line 1)
15992 (skip-chars-forward " \t")
15993 (when (equal prop org-effort-property)
15994 (save-excursion
15995 (org-back-to-heading t)
15996 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
15997 (when (string= org-clock-current-task heading)
15998 (setq org-clock-effort nval)
15999 (org-clock-update-mode-line)))
16000 (run-hook-with-args 'org-property-changed-functions key nval)))
16002 (defun org-find-olp (path &optional this-buffer)
16003 "Return a marker pointing to the entry at outline path OLP.
16004 If anything goes wrong, throw an error.
16005 You can wrap this call to catch the error like this:
16007 (condition-case msg
16008 (org-mobile-locate-entry (match-string 4))
16009 (error (nth 1 msg)))
16011 The return value will then be either a string with the error message,
16012 or a marker if everything is OK.
16014 If THIS-BUFFER is set, the outline path does not contain a file,
16015 only headings."
16016 (let* ((file (if this-buffer buffer-file-name (pop path)))
16017 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16018 (level 1)
16019 (lmin 1)
16020 (lmax 1)
16021 limit re end found pos heading cnt flevel)
16022 (unless buffer (error "File not found :%s" file))
16023 (with-current-buffer buffer
16024 (save-excursion
16025 (save-restriction
16026 (widen)
16027 (setq limit (point-max))
16028 (goto-char (point-min))
16029 (while (setq heading (pop path))
16030 (setq re (format org-complex-heading-regexp-format
16031 (regexp-quote heading)))
16032 (setq cnt 0 pos (point))
16033 (while (re-search-forward re end t)
16034 (setq level (- (match-end 1) (match-beginning 1)))
16035 (if (and (>= level lmin) (<= level lmax))
16036 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16037 (when (= cnt 0) (error "Heading not found on level %d: %s"
16038 lmax heading))
16039 (when (> cnt 1) (error "Heading not unique on level %d: %s"
16040 lmax heading))
16041 (goto-char found)
16042 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16043 (setq end (save-excursion (org-end-of-subtree t t))))
16044 (when (org-at-heading-p)
16045 (point-marker)))))))
16047 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16048 "Find node HEADING in BUFFER.
16049 Return a marker to the heading if it was found, or nil if not.
16050 If POS-ONLY is set, return just the position instead of a marker.
16052 The heading text must match exact, but it may have a TODO keyword,
16053 a priority cookie and tags in the standard locations."
16054 (with-current-buffer (or buffer (current-buffer))
16055 (save-excursion
16056 (save-restriction
16057 (widen)
16058 (goto-char (point-min))
16059 (let (case-fold-search)
16060 (if (re-search-forward
16061 (format org-complex-heading-regexp-format
16062 (regexp-quote heading)) nil t)
16063 (if pos-only
16064 (match-beginning 0)
16065 (move-marker (make-marker) (match-beginning 0)))))))))
16067 (defun org-find-exact-heading-in-directory (heading &optional dir)
16068 "Find Org node headline HEADING in all .org files in directory DIR.
16069 When the target headline is found, return a marker to this location."
16070 (let ((files (directory-files (or dir default-directory)
16071 nil "\\`[^.#].*\\.org\\'"))
16072 file visiting m buffer)
16073 (catch 'found
16074 (while (setq file (pop files))
16075 (message "trying %s" file)
16076 (setq visiting (org-find-base-buffer-visiting file))
16077 (setq buffer (or visiting (find-file-noselect file)))
16078 (setq m (org-find-exact-headline-in-buffer
16079 heading buffer))
16080 (when (and (not m) (not visiting)) (kill-buffer buffer))
16081 (and m (throw 'found m))))))
16083 (defun org-find-entry-with-id (ident)
16084 "Locate the entry that contains the ID property with exact value IDENT.
16085 IDENT can be a string, a symbol or a number, this function will search for
16086 the string representation of it.
16087 Return the position where this entry starts, or nil if there is no such entry."
16088 (interactive "sID: ")
16089 (let ((id (cond
16090 ((stringp ident) ident)
16091 ((symbol-name ident) (symbol-name ident))
16092 ((numberp ident) (number-to-string ident))
16093 (t (error "IDENT %s must be a string, symbol or number" ident))))
16094 (case-fold-search nil))
16095 (save-excursion
16096 (save-restriction
16097 (widen)
16098 (goto-char (point-min))
16099 (when (re-search-forward
16100 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16101 nil t)
16102 (org-back-to-heading t)
16103 (point))))))
16105 ;;;; Timestamps
16107 (defvar org-last-changed-timestamp nil)
16108 (defvar org-last-inserted-timestamp nil
16109 "The last time stamp inserted with `org-insert-time-stamp'.")
16110 (defvar org-ts-what) ; dynamically scoped parameter
16112 (defun org-time-stamp (arg &optional inactive)
16113 "Prompt for a date/time and insert a time stamp.
16114 If the user specifies a time like HH:MM or if this command is
16115 called with at least one prefix argument, the time stamp contains
16116 the date and the time. Otherwise, only the date is be included.
16118 All parts of a date not specified by the user is filled in from
16119 the current date/time. So if you just press return without
16120 typing anything, the time stamp will represent the current
16121 date/time.
16123 If there is already a timestamp at the cursor, it will be
16124 modified.
16126 With two universal prefix arguments, insert an active timestamp
16127 with the current time without prompting the user.
16129 When called from lisp, the timestamp is inactive if INACTIVE is
16130 non-nil."
16131 (interactive "P")
16132 (let* ((ts nil)
16133 (default-time
16134 ;; Default time is either today, or, when entering a range,
16135 ;; the range start.
16136 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16137 (save-excursion
16138 (re-search-backward
16139 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16140 (- (point) 20) t)))
16141 (apply 'encode-time (org-parse-time-string (match-string 1)))
16142 (current-time)))
16143 (default-input (and ts (org-get-compact-tod ts)))
16144 (repeater (save-excursion
16145 (save-match-data
16146 (beginning-of-line)
16147 (when (re-search-forward
16148 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16149 (save-excursion (progn (end-of-line) (point))) t)
16150 (match-string 0)))))
16151 org-time-was-given org-end-time-was-given time)
16152 (cond
16153 ((and (org-at-timestamp-p t)
16154 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16155 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16156 (insert "--")
16157 (setq time (let ((this-command this-command))
16158 (org-read-date arg 'totime nil nil
16159 default-time default-input inactive)))
16160 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16161 ((org-at-timestamp-p t)
16162 (setq time (let ((this-command this-command))
16163 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16164 (when (org-at-timestamp-p t) ; just to get the match data
16165 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16166 (replace-match "")
16167 (setq org-last-changed-timestamp
16168 (org-insert-time-stamp
16169 time (or org-time-was-given arg)
16170 inactive nil nil (list org-end-time-was-given)))
16171 (when repeater (goto-char (1- (point))) (insert " " repeater)
16172 (setq org-last-changed-timestamp
16173 (concat (substring org-last-inserted-timestamp 0 -1)
16174 " " repeater ">"))))
16175 (message "Timestamp updated"))
16176 ((equal arg '(16))
16177 (org-insert-time-stamp (current-time) t inactive))
16179 (setq time (let ((this-command this-command))
16180 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16181 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16182 nil nil (list org-end-time-was-given))))))
16184 ;; FIXME: can we use this for something else, like computing time differences?
16185 (defun org-get-compact-tod (s)
16186 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16187 (let* ((t1 (match-string 1 s))
16188 (h1 (string-to-number (match-string 2 s)))
16189 (m1 (string-to-number (match-string 3 s)))
16190 (t2 (and (match-end 4) (match-string 5 s)))
16191 (h2 (and t2 (string-to-number (match-string 6 s))))
16192 (m2 (and t2 (string-to-number (match-string 7 s))))
16193 dh dm)
16194 (if (not t2)
16196 (setq dh (- h2 h1) dm (- m2 m1))
16197 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16198 (concat t1 "+" (number-to-string dh)
16199 (and (/= 0 dm) (format ":%02d" dm)))))))
16201 (defun org-time-stamp-inactive (&optional arg)
16202 "Insert an inactive time stamp.
16203 An inactive time stamp is enclosed in square brackets instead of angle
16204 brackets. It is inactive in the sense that it does not trigger agenda entries,
16205 does not link to the calendar and cannot be changed with the S-cursor keys.
16206 So these are more for recording a certain time/date."
16207 (interactive "P")
16208 (org-time-stamp arg 'inactive))
16210 (defvar org-date-ovl (make-overlay 1 1))
16211 (overlay-put org-date-ovl 'face 'org-date-selected)
16212 (org-detach-overlay org-date-ovl)
16214 (defvar org-ans1) ; dynamically scoped parameter
16215 (defvar org-ans2) ; dynamically scoped parameter
16217 (defvar org-plain-time-of-day-regexp) ; defined below
16219 (defvar org-overriding-default-time nil) ; dynamically scoped
16220 (defvar org-read-date-overlay nil)
16221 (defvar org-dcst nil) ; dynamically scoped
16222 (defvar org-read-date-history nil)
16223 (defvar org-read-date-final-answer nil)
16224 (defvar org-read-date-analyze-futurep nil)
16225 (defvar org-read-date-analyze-forced-year nil)
16226 (defvar org-read-date-inactive)
16228 (defvar org-read-date-minibuffer-local-map
16229 (let* ((org-replace-disputed-keys nil)
16230 (map (make-sparse-keymap)))
16231 (set-keymap-parent map minibuffer-local-map)
16232 (org-defkey map (kbd ".")
16233 (lambda () (interactive)
16234 ;; Are we at the beginning of the prompt?
16235 (if (looking-back "^[^:]+: ")
16236 (org-eval-in-calendar '(calendar-goto-today))
16237 (insert "."))))
16238 (org-defkey map (kbd "C-.")
16239 (lambda () (interactive)
16240 (org-eval-in-calendar '(calendar-goto-today))))
16241 (org-defkey map [(meta shift left)]
16242 (lambda () (interactive)
16243 (org-eval-in-calendar '(calendar-backward-month 1))))
16244 (org-defkey map [(meta shift right)]
16245 (lambda () (interactive)
16246 (org-eval-in-calendar '(calendar-forward-month 1))))
16247 (org-defkey map [(meta shift up)]
16248 (lambda () (interactive)
16249 (org-eval-in-calendar '(calendar-backward-year 1))))
16250 (org-defkey map [(meta shift down)]
16251 (lambda () (interactive)
16252 (org-eval-in-calendar '(calendar-forward-year 1))))
16253 (org-defkey map [?\e (shift left)]
16254 (lambda () (interactive)
16255 (org-eval-in-calendar '(calendar-backward-month 1))))
16256 (org-defkey map [?\e (shift right)]
16257 (lambda () (interactive)
16258 (org-eval-in-calendar '(calendar-forward-month 1))))
16259 (org-defkey map [?\e (shift up)]
16260 (lambda () (interactive)
16261 (org-eval-in-calendar '(calendar-backward-year 1))))
16262 (org-defkey map [?\e (shift down)]
16263 (lambda () (interactive)
16264 (org-eval-in-calendar '(calendar-forward-year 1))))
16265 (org-defkey map [(shift up)]
16266 (lambda () (interactive)
16267 (org-eval-in-calendar '(calendar-backward-week 1))))
16268 (org-defkey map [(shift down)]
16269 (lambda () (interactive)
16270 (org-eval-in-calendar '(calendar-forward-week 1))))
16271 (org-defkey map [(shift left)]
16272 (lambda () (interactive)
16273 (org-eval-in-calendar '(calendar-backward-day 1))))
16274 (org-defkey map [(shift right)]
16275 (lambda () (interactive)
16276 (org-eval-in-calendar '(calendar-forward-day 1))))
16277 (org-defkey map "!"
16278 (lambda () (interactive)
16279 (org-eval-in-calendar '(diary-view-entries))
16280 (message "")))
16281 (org-defkey map ">"
16282 (lambda () (interactive)
16283 (org-eval-in-calendar '(scroll-calendar-left 1))))
16284 (org-defkey map "<"
16285 (lambda () (interactive)
16286 (org-eval-in-calendar '(scroll-calendar-right 1))))
16287 (org-defkey map "\C-v"
16288 (lambda () (interactive)
16289 (org-eval-in-calendar
16290 '(calendar-scroll-left-three-months 1))))
16291 (org-defkey map "\M-v"
16292 (lambda () (interactive)
16293 (org-eval-in-calendar
16294 '(calendar-scroll-right-three-months 1))))
16295 map)
16296 "Keymap for minibuffer commands when using `org-read-date'.")
16298 (defvar org-def)
16299 (defvar org-defdecode)
16300 (defvar org-with-time)
16302 (defun org-read-date (&optional org-with-time to-time from-string prompt
16303 default-time default-input inactive)
16304 "Read a date, possibly a time, and make things smooth for the user.
16305 The prompt will suggest to enter an ISO date, but you can also enter anything
16306 which will at least partially be understood by `parse-time-string'.
16307 Unrecognized parts of the date will default to the current day, month, year,
16308 hour and minute. If this command is called to replace a timestamp at point,
16309 or to enter the second timestamp of a range, the default time is taken
16310 from the existing stamp. Furthermore, the command prefers the future,
16311 so if you are giving a date where the year is not given, and the day-month
16312 combination is already past in the current year, it will assume you
16313 mean next year. For details, see the manual. A few examples:
16315 3-2-5 --> 2003-02-05
16316 feb 15 --> currentyear-02-15
16317 2/15 --> currentyear-02-15
16318 sep 12 9 --> 2009-09-12
16319 12:45 --> today 12:45
16320 22 sept 0:34 --> currentyear-09-22 0:34
16321 12 --> currentyear-currentmonth-12
16322 Fri --> nearest Friday after today
16323 -Tue --> last Tuesday
16324 etc.
16326 Furthermore you can specify a relative date by giving, as the *first* thing
16327 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16328 change in days weeks, months, years.
16329 With a single plus or minus, the date is relative to today. With a double
16330 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16331 +4d --> four days from today
16332 +4 --> same as above
16333 +2w --> two weeks from today
16334 ++5 --> five days from default date
16336 The function understands only English month and weekday abbreviations.
16338 While prompting, a calendar is popped up - you can also select the
16339 date with the mouse (button 1). The calendar shows a period of three
16340 months. To scroll it to other months, use the keys `>' and `<'.
16341 If you don't like the calendar, turn it off with
16342 \(setq org-read-date-popup-calendar nil)
16344 With optional argument TO-TIME, the date will immediately be converted
16345 to an internal time.
16346 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16347 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16348 still enter a time, and this function will inform the calling routine
16349 about this change. The calling routine may then choose to change the
16350 format used to insert the time stamp into the buffer to include the time.
16351 With optional argument FROM-STRING, read from this string instead from
16352 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16353 the time/date that is used for everything that is not specified by the
16354 user."
16355 (require 'parse-time)
16356 (let* ((org-time-stamp-rounding-minutes
16357 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16358 (org-dcst org-display-custom-times)
16359 (ct (org-current-time))
16360 (org-def (or org-overriding-default-time default-time ct))
16361 (org-defdecode (decode-time org-def))
16362 (dummy (progn
16363 (when (< (nth 2 org-defdecode) org-extend-today-until)
16364 (setcar (nthcdr 2 org-defdecode) -1)
16365 (setcar (nthcdr 1 org-defdecode) 59)
16366 (setq org-def (apply 'encode-time org-defdecode)
16367 org-defdecode (decode-time org-def)))))
16368 (mouse-autoselect-window nil) ; Don't let the mouse jump
16369 (calendar-frame-setup nil)
16370 (calendar-setup nil)
16371 (calendar-move-hook nil)
16372 (calendar-view-diary-initially-flag nil)
16373 (calendar-view-holidays-initially-flag nil)
16374 (timestr (format-time-string
16375 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16376 (prompt (concat (if prompt (concat prompt " ") "")
16377 (format "Date+time [%s]: " timestr)))
16378 ans (org-ans0 "") org-ans1 org-ans2 final)
16380 (cond
16381 (from-string (setq ans from-string))
16382 (org-read-date-popup-calendar
16383 (save-excursion
16384 (save-window-excursion
16385 (calendar)
16386 (org-eval-in-calendar '(setq cursor-type nil) t)
16387 (unwind-protect
16388 (progn
16389 (calendar-forward-day (- (time-to-days org-def)
16390 (calendar-absolute-from-gregorian
16391 (calendar-current-date))))
16392 (org-eval-in-calendar nil t)
16393 (let* ((old-map (current-local-map))
16394 (map (copy-keymap calendar-mode-map))
16395 (minibuffer-local-map
16396 (copy-keymap org-read-date-minibuffer-local-map)))
16397 (org-defkey map (kbd "RET") 'org-calendar-select)
16398 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16399 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16400 (unwind-protect
16401 (progn
16402 (use-local-map map)
16403 (setq org-read-date-inactive inactive)
16404 (add-hook 'post-command-hook 'org-read-date-display)
16405 (setq org-ans0 (read-string prompt default-input
16406 'org-read-date-history nil))
16407 ;; org-ans0: from prompt
16408 ;; org-ans1: from mouse click
16409 ;; org-ans2: from calendar motion
16410 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16411 (remove-hook 'post-command-hook 'org-read-date-display)
16412 (use-local-map old-map)
16413 (when org-read-date-overlay
16414 (delete-overlay org-read-date-overlay)
16415 (setq org-read-date-overlay nil)))))
16416 (bury-buffer "*Calendar*")))))
16418 (t ; Naked prompt only
16419 (unwind-protect
16420 (setq ans (read-string prompt default-input
16421 'org-read-date-history timestr))
16422 (when org-read-date-overlay
16423 (delete-overlay org-read-date-overlay)
16424 (setq org-read-date-overlay nil)))))
16426 (setq final (org-read-date-analyze ans org-def org-defdecode))
16428 (when org-read-date-analyze-forced-year
16429 (message "Year was forced into %s"
16430 (if org-read-date-force-compatible-dates
16431 "compatible range (1970-2037)"
16432 "range representable on this machine"))
16433 (ding))
16435 ;; One round trip to get rid of 34th of August and stuff like that....
16436 (setq final (decode-time (apply 'encode-time final)))
16438 (setq org-read-date-final-answer ans)
16440 (if to-time
16441 (apply 'encode-time final)
16442 (if (and (boundp 'org-time-was-given) org-time-was-given)
16443 (format "%04d-%02d-%02d %02d:%02d"
16444 (nth 5 final) (nth 4 final) (nth 3 final)
16445 (nth 2 final) (nth 1 final))
16446 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16448 (defun org-read-date-display ()
16449 "Display the current date prompt interpretation in the minibuffer."
16450 (when org-read-date-display-live
16451 (when org-read-date-overlay
16452 (delete-overlay org-read-date-overlay))
16453 (when (minibufferp (current-buffer))
16454 (save-excursion
16455 (end-of-line 1)
16456 (while (not (equal (buffer-substring
16457 (max (point-min) (- (point) 4)) (point))
16458 " "))
16459 (insert " ")))
16460 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16461 " " (or org-ans1 org-ans2)))
16462 (org-end-time-was-given nil)
16463 (f (org-read-date-analyze ans org-def org-defdecode))
16464 (fmts (if org-dcst
16465 org-time-stamp-custom-formats
16466 org-time-stamp-formats))
16467 (fmt (if (or org-with-time
16468 (and (boundp 'org-time-was-given) org-time-was-given))
16469 (cdr fmts)
16470 (car fmts)))
16471 (txt (format-time-string fmt (apply 'encode-time f)))
16472 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16473 (txt (concat "=> " txt)))
16474 (when (and org-end-time-was-given
16475 (string-match org-plain-time-of-day-regexp txt))
16476 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16477 org-end-time-was-given
16478 (substring txt (match-end 0)))))
16479 (when org-read-date-analyze-futurep
16480 (setq txt (concat txt " (=>F)")))
16481 (setq org-read-date-overlay
16482 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16483 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16485 (defun org-read-date-analyze (ans org-def org-defdecode)
16486 "Analyze the combined answer of the date prompt."
16487 ;; FIXME: cleanup and comment
16488 (let ((nowdecode (decode-time (current-time)))
16489 delta deltan deltaw deltadef year month day
16490 hour minute second wday pm h2 m2 tl wday1
16491 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16492 (setq org-read-date-analyze-futurep nil
16493 org-read-date-analyze-forced-year nil)
16494 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16495 (setq ans "+0"))
16497 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16498 (setq ans (replace-match "" t t ans)
16499 deltan (car delta)
16500 deltaw (nth 1 delta)
16501 deltadef (nth 2 delta)))
16503 ;; Check if there is an iso week date in there. If yes, store the
16504 ;; info and postpone interpreting it until the rest of the parsing
16505 ;; is done.
16506 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16507 (setq iso-year (if (match-end 1)
16508 (org-small-year-to-year
16509 (string-to-number (match-string 1 ans))))
16510 iso-weekday (if (match-end 3)
16511 (string-to-number (match-string 3 ans)))
16512 iso-week (string-to-number (match-string 2 ans)))
16513 (setq ans (replace-match "" t t ans)))
16515 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16516 (when (string-match
16517 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16518 (setq year (if (match-end 2)
16519 (string-to-number (match-string 2 ans))
16520 (progn (setq kill-year t)
16521 (string-to-number (format-time-string "%Y"))))
16522 month (string-to-number (match-string 3 ans))
16523 day (string-to-number (match-string 4 ans)))
16524 (if (< year 100) (setq year (+ 2000 year)))
16525 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16526 t nil ans)))
16528 ;; Help matching dotted european dates
16529 (when (string-match
16530 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16531 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16532 (setq kill-year t)
16533 (string-to-number (format-time-string "%Y")))
16534 day (string-to-number (match-string 1 ans))
16535 month (string-to-number (match-string 2 ans))
16536 ans (replace-match (format "%04d-%02d-%02d" year month day)
16537 t nil ans)))
16539 ;; Help matching american dates, like 5/30 or 5/30/7
16540 (when (string-match
16541 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16542 (setq year (if (match-end 4)
16543 (string-to-number (match-string 4 ans))
16544 (progn (setq kill-year t)
16545 (string-to-number (format-time-string "%Y"))))
16546 month (string-to-number (match-string 1 ans))
16547 day (string-to-number (match-string 2 ans)))
16548 (if (< year 100) (setq year (+ 2000 year)))
16549 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16550 t nil ans)))
16551 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16552 ;; If there is a time with am/pm, and *no* time without it, we convert
16553 ;; so that matching will be successful.
16554 (loop for i from 1 to 2 do ; twice, for end time as well
16555 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16556 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16557 (setq hour (string-to-number (match-string 1 ans))
16558 minute (if (match-end 3)
16559 (string-to-number (match-string 3 ans))
16561 pm (equal ?p
16562 (string-to-char (downcase (match-string 4 ans)))))
16563 (if (and (= hour 12) (not pm))
16564 (setq hour 0)
16565 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16566 (setq ans (replace-match (format "%02d:%02d" hour minute)
16567 t t ans))))
16569 ;; Check if a time range is given as a duration
16570 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16571 (setq hour (string-to-number (match-string 1 ans))
16572 h2 (+ hour (string-to-number (match-string 3 ans)))
16573 minute (string-to-number (match-string 2 ans))
16574 m2 (+ minute (if (match-end 5) (string-to-number
16575 (match-string 5 ans))0)))
16576 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16577 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16578 t t ans)))
16580 ;; Check if there is a time range
16581 (when (boundp 'org-end-time-was-given)
16582 (setq org-time-was-given nil)
16583 (when (and (string-match org-plain-time-of-day-regexp ans)
16584 (match-end 8))
16585 (setq org-end-time-was-given (match-string 8 ans))
16586 (setq ans (concat (substring ans 0 (match-beginning 7))
16587 (substring ans (match-end 7))))))
16589 (setq tl (parse-time-string ans)
16590 day (or (nth 3 tl) (nth 3 org-defdecode))
16591 month (or (nth 4 tl)
16592 (if (and org-read-date-prefer-future
16593 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16594 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16595 (nth 4 org-defdecode)))
16596 year (or (and (not kill-year) (nth 5 tl))
16597 (if (and org-read-date-prefer-future
16598 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16599 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16600 (nth 5 org-defdecode)))
16601 hour (or (nth 2 tl) (nth 2 org-defdecode))
16602 minute (or (nth 1 tl) (nth 1 org-defdecode))
16603 second (or (nth 0 tl) 0)
16604 wday (nth 6 tl))
16606 (when (and (eq org-read-date-prefer-future 'time)
16607 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16608 (equal day (nth 3 nowdecode))
16609 (equal month (nth 4 nowdecode))
16610 (equal year (nth 5 nowdecode))
16611 (nth 2 tl)
16612 (or (< (nth 2 tl) (nth 2 nowdecode))
16613 (and (= (nth 2 tl) (nth 2 nowdecode))
16614 (nth 1 tl)
16615 (< (nth 1 tl) (nth 1 nowdecode)))))
16616 (setq day (1+ day)
16617 futurep t))
16619 ;; Special date definitions below
16620 (cond
16621 (iso-week
16622 ;; There was an iso week
16623 (require 'cal-iso)
16624 (setq futurep nil)
16625 (setq year (or iso-year year)
16626 day (or iso-weekday wday 1)
16627 wday nil ; to make sure that the trigger below does not match
16628 iso-date (calendar-gregorian-from-absolute
16629 (calendar-absolute-from-iso
16630 (list iso-week day year))))
16631 ; FIXME: Should we also push ISO weeks into the future?
16632 ; (when (and org-read-date-prefer-future
16633 ; (not iso-year)
16634 ; (< (calendar-absolute-from-gregorian iso-date)
16635 ; (time-to-days (current-time))))
16636 ; (setq year (1+ year)
16637 ; iso-date (calendar-gregorian-from-absolute
16638 ; (calendar-absolute-from-iso
16639 ; (list iso-week day year)))))
16640 (setq month (car iso-date)
16641 year (nth 2 iso-date)
16642 day (nth 1 iso-date)))
16643 (deltan
16644 (setq futurep nil)
16645 (unless deltadef
16646 (let ((now (decode-time (current-time))))
16647 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16648 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16649 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16650 ((equal deltaw "m") (setq month (+ month deltan)))
16651 ((equal deltaw "y") (setq year (+ year deltan)))))
16652 ((and wday (not (nth 3 tl)))
16653 ;; Weekday was given, but no day, so pick that day in the week
16654 ;; on or after the derived date.
16655 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16656 (unless (equal wday wday1)
16657 (setq day (+ day (% (- wday wday1 -7) 7))))))
16658 (if (and (boundp 'org-time-was-given)
16659 (nth 2 tl))
16660 (setq org-time-was-given t))
16661 (if (< year 100) (setq year (+ 2000 year)))
16662 ;; Check of the date is representable
16663 (if org-read-date-force-compatible-dates
16664 (progn
16665 (if (< year 1970)
16666 (setq year 1970 org-read-date-analyze-forced-year t))
16667 (if (> year 2037)
16668 (setq year 2037 org-read-date-analyze-forced-year t)))
16669 (condition-case nil
16670 (ignore (encode-time second minute hour day month year))
16671 (error
16672 (setq year (nth 5 org-defdecode))
16673 (setq org-read-date-analyze-forced-year t))))
16674 (setq org-read-date-analyze-futurep futurep)
16675 (list second minute hour day month year)))
16677 (defvar parse-time-weekdays)
16678 (defun org-read-date-get-relative (s today default)
16679 "Check string S for special relative date string.
16680 TODAY and DEFAULT are internal times, for today and for a default.
16681 Return shift list (N what def-flag)
16682 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16683 N is the number of WHATs to shift.
16684 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16685 the DEFAULT date rather than TODAY."
16686 (require 'parse-time)
16687 (when (and
16688 (string-match
16689 (concat
16690 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16691 "\\([0-9]+\\)?"
16692 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16693 "\\([ \t]\\|$\\)") s)
16694 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16695 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16696 (string-to-char (substring (match-string 1 s) -1))
16697 ?+))
16698 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16699 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16700 (what (if (match-end 3) (match-string 3 s) "d"))
16701 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16702 (date (if rel default today))
16703 (wday (nth 6 (decode-time date)))
16704 delta)
16705 (if wday1
16706 (progn
16707 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16708 (if (= delta 0) (setq delta 7))
16709 (if (= dir ?-)
16710 (progn
16711 (setq delta (- delta 7))
16712 (if (= delta 0) (setq delta -7))))
16713 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16714 (list delta "d" rel))
16715 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16717 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16718 "Turn a user-specified date into the internal representation.
16719 The internal representation needed by the calendar is (month day year).
16720 This is a wrapper to handle the brain-dead convention in calendar that
16721 user function argument order change dependent on argument order."
16722 (if (boundp 'calendar-date-style)
16723 (cond
16724 ((eq calendar-date-style 'american)
16725 (list arg1 arg2 arg3))
16726 ((eq calendar-date-style 'european)
16727 (list arg2 arg1 arg3))
16728 ((eq calendar-date-style 'iso)
16729 (list arg2 arg3 arg1)))
16730 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16731 (if (org-bound-and-true-p european-calendar-style)
16732 (list arg2 arg1 arg3)
16733 (list arg1 arg2 arg3)))))
16735 (defun org-eval-in-calendar (form &optional keepdate)
16736 "Eval FORM in the calendar window and return to current window.
16737 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16738 otherwise stick to the current value of `org-ans2'."
16739 (let ((sf (selected-frame))
16740 (sw (selected-window)))
16741 (select-window (get-buffer-window "*Calendar*" t))
16742 (eval form)
16743 (when (and (not keepdate) (calendar-cursor-to-date))
16744 (let* ((date (calendar-cursor-to-date))
16745 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16746 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16747 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16748 (select-window sw)
16749 (org-select-frame-set-input-focus sf)))
16751 (defun org-calendar-select ()
16752 "Return to `org-read-date' with the date currently selected.
16753 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16754 (interactive)
16755 (when (calendar-cursor-to-date)
16756 (let* ((date (calendar-cursor-to-date))
16757 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16758 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16759 (if (active-minibuffer-window) (exit-minibuffer))))
16761 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16762 "Insert a date stamp for the date given by the internal TIME.
16763 WITH-HM means use the stamp format that includes the time of the day.
16764 INACTIVE means use square brackets instead of angular ones, so that the
16765 stamp will not contribute to the agenda.
16766 PRE and POST are optional strings to be inserted before and after the
16767 stamp.
16768 The command returns the inserted time stamp."
16769 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16770 stamp)
16771 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16772 (insert-before-markers (or pre ""))
16773 (when (listp extra)
16774 (setq extra (car extra))
16775 (if (and (stringp extra)
16776 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16777 (setq extra (format "-%02d:%02d"
16778 (string-to-number (match-string 1 extra))
16779 (string-to-number (match-string 2 extra))))
16780 (setq extra nil)))
16781 (when extra
16782 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16783 (insert-before-markers (setq stamp (format-time-string fmt time)))
16784 (insert-before-markers (or post ""))
16785 (setq org-last-inserted-timestamp stamp)))
16787 (defun org-toggle-time-stamp-overlays ()
16788 "Toggle the use of custom time stamp formats."
16789 (interactive)
16790 (setq org-display-custom-times (not org-display-custom-times))
16791 (unless org-display-custom-times
16792 (let ((p (point-min)) (bmp (buffer-modified-p)))
16793 (while (setq p (next-single-property-change p 'display))
16794 (if (and (get-text-property p 'display)
16795 (eq (get-text-property p 'face) 'org-date))
16796 (remove-text-properties
16797 p (setq p (next-single-property-change p 'display))
16798 '(display t))))
16799 (set-buffer-modified-p bmp)))
16800 (if (featurep 'xemacs)
16801 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16802 (org-restart-font-lock)
16803 (setq org-table-may-need-update t)
16804 (if org-display-custom-times
16805 (message "Time stamps are overlaid with custom format")
16806 (message "Time stamp overlays removed")))
16808 (defun org-display-custom-time (beg end)
16809 "Overlay modified time stamp format over timestamp between BEG and END."
16810 (let* ((ts (buffer-substring beg end))
16811 t1 w1 with-hm tf time str w2 (off 0))
16812 (save-match-data
16813 (setq t1 (org-parse-time-string ts t))
16814 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16815 (setq off (- (match-end 0) (match-beginning 0)))))
16816 (setq end (- end off))
16817 (setq w1 (- end beg)
16818 with-hm (and (nth 1 t1) (nth 2 t1))
16819 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16820 time (org-fix-decoded-time t1)
16821 str (org-add-props
16822 (format-time-string
16823 (substring tf 1 -1) (apply 'encode-time time))
16824 nil 'mouse-face 'highlight)
16825 w2 (length str))
16826 (if (not (= w2 w1))
16827 (add-text-properties (1+ beg) (+ 2 beg)
16828 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16829 (if (featurep 'xemacs)
16830 (progn
16831 (put-text-property beg end 'invisible t)
16832 (put-text-property beg end 'end-glyph (make-glyph str)))
16833 (put-text-property beg end 'display str))))
16835 (defun org-translate-time (string)
16836 "Translate all timestamps in STRING to custom format.
16837 But do this only if the variable `org-display-custom-times' is set."
16838 (when org-display-custom-times
16839 (save-match-data
16840 (let* ((start 0)
16841 (re org-ts-regexp-both)
16842 t1 with-hm inactive tf time str beg end)
16843 (while (setq start (string-match re string start))
16844 (setq beg (match-beginning 0)
16845 end (match-end 0)
16846 t1 (save-match-data
16847 (org-parse-time-string (substring string beg end) t))
16848 with-hm (and (nth 1 t1) (nth 2 t1))
16849 inactive (equal (substring string beg (1+ beg)) "[")
16850 tf (funcall (if with-hm 'cdr 'car)
16851 org-time-stamp-custom-formats)
16852 time (org-fix-decoded-time t1)
16853 str (format-time-string
16854 (concat
16855 (if inactive "[" "<") (substring tf 1 -1)
16856 (if inactive "]" ">"))
16857 (apply 'encode-time time))
16858 string (replace-match str t t string)
16859 start (+ start (length str)))))))
16860 string)
16862 (defun org-fix-decoded-time (time)
16863 "Set 0 instead of nil for the first 6 elements of time.
16864 Don't touch the rest."
16865 (let ((n 0))
16866 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16868 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16870 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16871 "Difference between TIMESTAMP-STRING and now in days.
16872 If SECONDS is non-nil, return the difference in seconds."
16873 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16874 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16875 (funcall fdiff (current-time)))))
16877 (defun org-deadline-close (timestamp-string &optional ndays)
16878 "Is the time in TIMESTAMP-STRING close to the current date?"
16879 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16880 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16881 (not (org-entry-is-done-p))))
16883 (defun org-get-wdays (ts &optional delay zero-delay)
16884 "Get the deadline lead time appropriate for timestring TS.
16885 When DELAY is non-nil, get the delay time for scheduled items
16886 instead of the deadline lead time. When ZERO-DELAY is non-nil
16887 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16888 don't try to find the delay cookie in the scheduled timestamp."
16889 (let ((tv (if delay org-scheduled-delay-days
16890 org-deadline-warning-days)))
16891 (cond
16892 ((or (and delay (< tv 0))
16893 (and delay zero-delay (<= tv 0))
16894 (and (not delay) (<= tv 0)))
16895 ;; Enforce this value no matter what
16896 (- tv))
16897 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16898 ;; lead time is specified.
16899 (floor (* (string-to-number (match-string 1 ts))
16900 (cdr (assoc (match-string 2 ts)
16901 '(("d" . 1) ("w" . 7)
16902 ("m" . 30.4) ("y" . 365.25)
16903 ("h" . 0.041667)))))))
16904 ;; go for the default.
16905 (t tv))))
16907 (defun org-calendar-select-mouse (ev)
16908 "Return to `org-read-date' with the date currently selected.
16909 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16910 (interactive "e")
16911 (mouse-set-point ev)
16912 (when (calendar-cursor-to-date)
16913 (let* ((date (calendar-cursor-to-date))
16914 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16915 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16916 (if (active-minibuffer-window) (exit-minibuffer))))
16918 (defun org-check-deadlines (ndays)
16919 "Check if there are any deadlines due or past due.
16920 A deadline is considered due if it happens within `org-deadline-warning-days'
16921 days from today's date. If the deadline appears in an entry marked DONE,
16922 it is not shown. The prefix arg NDAYS can be used to test that many
16923 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16924 (interactive "P")
16925 (let* ((org-warn-days
16926 (cond
16927 ((equal ndays '(4)) 100000)
16928 (ndays (prefix-numeric-value ndays))
16929 (t (abs org-deadline-warning-days))))
16930 (case-fold-search nil)
16931 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16932 (callback
16933 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16935 (message "%d deadlines past-due or due within %d days"
16936 (org-occur regexp nil callback)
16937 org-warn-days)))
16939 (defsubst org-re-timestamp (type)
16940 "Return a regexp for timestamp TYPE.
16941 Allowed values for TYPE are:
16943 all: all timestamps
16944 active: only active timestamps (<...>)
16945 inactive: only inactive timestamps ([...])
16946 scheduled: only scheduled timestamps
16947 deadline: only deadline timestamps
16948 closed: only closed time-stamps
16950 When TYPE is nil, fall back on returning a regexp that matches
16951 both scheduled and deadline timestamps."
16952 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16953 ((eq type 'active) org-ts-regexp)
16954 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16955 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16956 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16957 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
16958 ((eq type 'scheduled-or-deadline)
16959 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16961 (defun org-check-before-date (date)
16962 "Check if there are deadlines or scheduled entries before DATE."
16963 (interactive (list (org-read-date)))
16964 (let ((case-fold-search nil)
16965 (regexp (org-re-timestamp org-ts-type))
16966 (callback
16967 (lambda () (time-less-p
16968 (org-time-string-to-time (match-string 1))
16969 (org-time-string-to-time date)))))
16970 (message "%d entries before %s"
16971 (org-occur regexp nil callback) date)))
16973 (defun org-check-after-date (date)
16974 "Check if there are deadlines or scheduled entries after DATE."
16975 (interactive (list (org-read-date)))
16976 (let ((case-fold-search nil)
16977 (regexp (org-re-timestamp org-ts-type))
16978 (callback
16979 (lambda () (not
16980 (time-less-p
16981 (org-time-string-to-time (match-string 1))
16982 (org-time-string-to-time date))))))
16983 (message "%d entries after %s"
16984 (org-occur regexp nil callback) date)))
16986 (defun org-check-dates-range (start-date end-date)
16987 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16988 (interactive (list (org-read-date nil nil nil "Range starts")
16989 (org-read-date nil nil nil "Range end")))
16990 (let ((case-fold-search nil)
16991 (regexp (org-re-timestamp org-ts-type))
16992 (callback
16993 (lambda ()
16994 (let ((match (match-string 1)))
16995 (and
16996 (not (time-less-p
16997 (org-time-string-to-time match)
16998 (org-time-string-to-time start-date)))
16999 (time-less-p
17000 (org-time-string-to-time match)
17001 (org-time-string-to-time end-date)))))))
17002 (message "%d entries between %s and %s"
17003 (org-occur regexp nil callback) start-date end-date)))
17005 (defun org-evaluate-time-range (&optional to-buffer)
17006 "Evaluate a time range by computing the difference between start and end.
17007 Normally the result is just printed in the echo area, but with prefix arg
17008 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17009 If the time range is actually in a table, the result is inserted into the
17010 next column.
17011 For time difference computation, a year is assumed to be exactly 365
17012 days in order to avoid rounding problems."
17013 (interactive "P")
17015 (org-clock-update-time-maybe)
17016 (save-excursion
17017 (unless (org-at-date-range-p t)
17018 (goto-char (point-at-bol))
17019 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17020 (if (not (org-at-date-range-p t))
17021 (user-error "Not at a time-stamp range, and none found in current line")))
17022 (let* ((ts1 (match-string 1))
17023 (ts2 (match-string 2))
17024 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17025 (match-end (match-end 0))
17026 (time1 (org-time-string-to-time ts1))
17027 (time2 (org-time-string-to-time ts2))
17028 (t1 (org-float-time time1))
17029 (t2 (org-float-time time2))
17030 (diff (abs (- t2 t1)))
17031 (negative (< (- t2 t1) 0))
17032 ;; (ys (floor (* 365 24 60 60)))
17033 (ds (* 24 60 60))
17034 (hs (* 60 60))
17035 (fy "%dy %dd %02d:%02d")
17036 (fy1 "%dy %dd")
17037 (fd "%dd %02d:%02d")
17038 (fd1 "%dd")
17039 (fh "%02d:%02d")
17040 y d h m align)
17041 (if havetime
17042 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17044 d (floor (/ diff ds)) diff (mod diff ds)
17045 h (floor (/ diff hs)) diff (mod diff hs)
17046 m (floor (/ diff 60)))
17047 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17049 d (floor (+ (/ diff ds) 0.5))
17050 h 0 m 0))
17051 (if (not to-buffer)
17052 (message "%s" (org-make-tdiff-string y d h m))
17053 (if (org-at-table-p)
17054 (progn
17055 (goto-char match-end)
17056 (setq align t)
17057 (and (looking-at " *|") (goto-char (match-end 0))))
17058 (goto-char match-end))
17059 (if (looking-at
17060 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17061 (replace-match ""))
17062 (if negative (insert " -"))
17063 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17064 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17065 (insert " " (format fh h m))))
17066 (if align (org-table-align))
17067 (message "Time difference inserted")))))
17069 (defun org-make-tdiff-string (y d h m)
17070 (let ((fmt "")
17071 (l nil))
17072 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
17073 l (push y l)))
17074 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
17075 l (push d l)))
17076 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
17077 l (push h l)))
17078 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
17079 l (push m l)))
17080 (apply 'format fmt (nreverse l))))
17082 (defun org-time-string-to-time (s &optional buffer pos)
17083 "Convert a timestamp string into internal time."
17084 (condition-case errdata
17085 (apply 'encode-time (org-parse-time-string s))
17086 (error (error "Bad timestamp `%s'%s\nError was: %s"
17087 s (if (not (and buffer pos))
17089 (format " at %d in buffer `%s'" pos buffer))
17090 (cdr errdata)))))
17092 (defun org-time-string-to-seconds (s)
17093 "Convert a timestamp string to a number of seconds."
17094 (org-float-time (org-time-string-to-time s)))
17096 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17097 "Convert a time stamp to an absolute day number.
17098 If there is a specifier for a cyclic time stamp, get the closest
17099 date to DAYNR.
17100 PREFER and SHOW-ALL are passed through to `org-closest-date'.
17101 The variable `date' is bound by the calendar when this is called."
17102 (cond
17103 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17104 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17105 daynr
17106 (+ daynr 1000)))
17107 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
17108 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17109 (time-to-days (current-time))) (match-string 0 s)
17110 prefer show-all))
17111 (t (time-to-days
17112 (condition-case errdata
17113 (apply 'encode-time (org-parse-time-string s))
17114 (error (error "Bad timestamp `%s'%s\nError was: %s"
17115 s (if (not (and buffer pos))
17117 (format " at %d in buffer `%s'" pos buffer))
17118 (cdr errdata))))))))
17120 (defun org-days-to-iso-week (days)
17121 "Return the iso week number."
17122 (require 'cal-iso)
17123 (car (calendar-iso-from-absolute days)))
17125 (defun org-small-year-to-year (year)
17126 "Convert 2-digit years into 4-digit years.
17127 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
17128 The year 2000 cannot be abbreviated. Any year larger than 99
17129 is returned unchanged."
17130 (if (< year 38)
17131 (setq year (+ 2000 year))
17132 (if (< year 100)
17133 (setq year (+ 1900 year))))
17134 year)
17136 (defun org-time-from-absolute (d)
17137 "Return the time corresponding to date D.
17138 D may be an absolute day number, or a calendar-type list (month day year)."
17139 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17140 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17142 (defun org-calendar-holiday ()
17143 "List of holidays, for Diary display in Org-mode."
17144 (require 'holidays)
17145 (let ((hl (funcall
17146 (if (fboundp 'calendar-check-holidays)
17147 'calendar-check-holidays 'check-calendar-holidays) date)))
17148 (if hl (mapconcat 'identity hl "; "))))
17150 (defun org-diary-sexp-entry (sexp entry date)
17151 "Process a SEXP diary ENTRY for DATE."
17152 (require 'diary-lib)
17153 (let ((result (if calendar-debug-sexp
17154 (let ((stack-trace-on-error t))
17155 (eval (car (read-from-string sexp))))
17156 (condition-case nil
17157 (eval (car (read-from-string sexp)))
17158 (error
17159 (beep)
17160 (message "Bad sexp at line %d in %s: %s"
17161 (org-current-line)
17162 (buffer-file-name) sexp)
17163 (sleep-for 2))))))
17164 (cond ((stringp result) (split-string result "; "))
17165 ((and (consp result)
17166 (not (consp (cdr result)))
17167 (stringp (cdr result))) (cdr result))
17168 ((and (consp result)
17169 (stringp (car result))) result)
17170 (result entry))))
17172 (defun org-diary-to-ical-string (frombuf)
17173 "Get iCalendar entries from diary entries in buffer FROMBUF.
17174 This uses the icalendar.el library."
17175 (let* ((tmpdir (if (featurep 'xemacs)
17176 (temp-directory)
17177 temporary-file-directory))
17178 (tmpfile (make-temp-name
17179 (expand-file-name "orgics" tmpdir)))
17180 buf rtn b e)
17181 (with-current-buffer frombuf
17182 (icalendar-export-region (point-min) (point-max) tmpfile)
17183 (setq buf (find-buffer-visiting tmpfile))
17184 (set-buffer buf)
17185 (goto-char (point-min))
17186 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17187 (setq b (match-beginning 0)))
17188 (goto-char (point-max))
17189 (if (re-search-backward "^END:VEVENT" nil t)
17190 (setq e (match-end 0)))
17191 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17192 (kill-buffer buf)
17193 (delete-file tmpfile)
17194 rtn))
17196 (defun org-closest-date (start current change prefer show-all)
17197 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17198 When PREFER is `past', return a date that is either CURRENT or past.
17199 When PREFER is `future', return a date that is either CURRENT or future.
17200 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17201 ;; Make the proper lists from the dates
17202 (catch 'exit
17203 (let ((a1 '(("h" . hour)
17204 ("d" . day)
17205 ("w" . week)
17206 ("m" . month)
17207 ("y" . year)))
17208 (shour (nth 2 (org-parse-time-string start)))
17209 dn dw sday cday n1 n2 n0
17210 d m y y1 y2 date1 date2 nmonths nm ny m2)
17212 (setq start (org-date-to-gregorian start)
17213 current (org-date-to-gregorian
17214 (if show-all
17215 current
17216 (time-to-days (current-time))))
17217 sday (calendar-absolute-from-gregorian start)
17218 cday (calendar-absolute-from-gregorian current))
17220 (if (<= cday sday) (throw 'exit sday))
17222 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17223 (setq dn (string-to-number (match-string 1 change))
17224 dw (cdr (assoc (match-string 2 change) a1)))
17225 (user-error "Invalid change specifier: %s" change))
17226 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17227 (cond
17228 ((eq dw 'hour)
17229 (let ((missing-hours
17230 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17231 dn)))
17232 (setq n1 (if (zerop missing-hours) cday
17233 (- cday (1+ (floor (/ missing-hours 24)))))
17234 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17235 ((eq dw 'day)
17236 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17237 n2 (+ n1 dn)))
17238 ((eq dw 'year)
17239 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17240 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17241 (setq date1 (list m d y1)
17242 n1 (calendar-absolute-from-gregorian date1)
17243 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17244 n2 (calendar-absolute-from-gregorian date2)))
17245 ((eq dw 'month)
17246 ;; approx number of month between the two dates
17247 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17248 ;; How often does dn fit in there?
17249 (setq d (nth 1 start) m (car start) y (nth 2 start)
17250 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17251 m (+ m nm)
17252 ny (floor (/ m 12))
17253 y (+ y ny)
17254 m (- m (* ny 12)))
17255 (while (> m 12) (setq m (- m 12) y (1+ y)))
17256 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17257 (setq m2 (+ m dn) y2 y)
17258 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17259 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17260 (while (<= n2 cday)
17261 (setq n1 n2 m m2 y y2)
17262 (setq m2 (+ m dn) y2 y)
17263 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17264 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17265 ;; Make sure n1 is the earlier date
17266 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17267 (if show-all
17268 (cond
17269 ((eq prefer 'past) (if (= cday n2) n2 n1))
17270 ((eq prefer 'future) (if (= cday n1) n1 n2))
17271 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17272 (cond
17273 ((eq prefer 'past) (if (= cday n2) n2 n1))
17274 ((eq prefer 'future) (if (= cday n1) n1 n2))
17275 (t (if (= cday n1) n1 n2)))))))
17277 (defun org-date-to-gregorian (date)
17278 "Turn any specification of DATE into a Gregorian date for the calendar."
17279 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17280 ((and (listp date) (= (length date) 3)) date)
17281 ((stringp date)
17282 (setq date (org-parse-time-string date))
17283 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17284 ((listp date)
17285 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17287 (defun org-parse-time-string (s &optional nodefault)
17288 "Parse the standard Org-mode time string.
17289 This should be a lot faster than the normal `parse-time-string'.
17290 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17291 hour and minute fields will be nil if not given."
17292 (cond ((string-match org-ts-regexp0 s)
17293 (list 0
17294 (if (or (match-beginning 8) (not nodefault))
17295 (string-to-number (or (match-string 8 s) "0")))
17296 (if (or (match-beginning 7) (not nodefault))
17297 (string-to-number (or (match-string 7 s) "0")))
17298 (string-to-number (match-string 4 s))
17299 (string-to-number (match-string 3 s))
17300 (string-to-number (match-string 2 s))
17301 nil nil nil))
17302 ((string-match "^<[^>]+>$" s)
17303 (decode-time (seconds-to-time (org-matcher-time s))))
17304 (t (error "Not a standard Org-mode time string: %s" s))))
17306 (defun org-timestamp-up (&optional arg)
17307 "Increase the date item at the cursor by one.
17308 If the cursor is on the year, change the year. If it is on the month,
17309 the day or the time, change that.
17310 With prefix ARG, change by that many units."
17311 (interactive "p")
17312 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17314 (defun org-timestamp-down (&optional arg)
17315 "Decrease the date item at the cursor by one.
17316 If the cursor is on the year, change the year. If it is on the month,
17317 the day or the time, change that.
17318 With prefix ARG, change by that many units."
17319 (interactive "p")
17320 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17322 (defun org-timestamp-up-day (&optional arg)
17323 "Increase the date in the time stamp by one day.
17324 With prefix ARG, change that many days."
17325 (interactive "p")
17326 (if (and (not (org-at-timestamp-p t))
17327 (org-at-heading-p))
17328 (org-todo 'up)
17329 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17331 (defun org-timestamp-down-day (&optional arg)
17332 "Decrease the date in the time stamp by one day.
17333 With prefix ARG, change that many days."
17334 (interactive "p")
17335 (if (and (not (org-at-timestamp-p t))
17336 (org-at-heading-p))
17337 (org-todo 'down)
17338 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17340 (defun org-at-timestamp-p (&optional inactive-ok)
17341 "Determine if the cursor is in or at a timestamp."
17342 (interactive)
17343 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17344 (pos (point))
17345 (ans (or (looking-at tsr)
17346 (save-excursion
17347 (skip-chars-backward "^[<\n\r\t")
17348 (if (> (point) (point-min)) (backward-char 1))
17349 (and (looking-at tsr)
17350 (> (- (match-end 0) pos) -1))))))
17351 (and ans
17352 (boundp 'org-ts-what)
17353 (setq org-ts-what
17354 (cond
17355 ((= pos (match-beginning 0)) 'bracket)
17356 ;; Point is considered to be "on the bracket" whether
17357 ;; it's really on it or right after it.
17358 ((= pos (1- (match-end 0))) 'bracket)
17359 ((= pos (match-end 0)) 'after)
17360 ((org-pos-in-match-range pos 2) 'year)
17361 ((org-pos-in-match-range pos 3) 'month)
17362 ((org-pos-in-match-range pos 7) 'hour)
17363 ((org-pos-in-match-range pos 8) 'minute)
17364 ((or (org-pos-in-match-range pos 4)
17365 (org-pos-in-match-range pos 5)) 'day)
17366 ((and (> pos (or (match-end 8) (match-end 5)))
17367 (< pos (match-end 0)))
17368 (- pos (or (match-end 8) (match-end 5))))
17369 (t 'day))))
17370 ans))
17372 (defun org-toggle-timestamp-type ()
17373 "Toggle the type (<active> or [inactive]) of a time stamp."
17374 (interactive)
17375 (when (org-at-timestamp-p t)
17376 (let ((beg (match-beginning 0)) (end (match-end 0))
17377 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17378 (save-excursion
17379 (goto-char beg)
17380 (while (re-search-forward "[][<>]" end t)
17381 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17382 t t)))
17383 (message "Timestamp is now %sactive"
17384 (if (equal (char-after beg) ?<) "" "in")))))
17386 (defun org-at-clock-log-p nil
17387 "Is the cursor on the clock log line?"
17388 (save-excursion
17389 (move-beginning-of-line 1)
17390 (looking-at "^[ \t]*CLOCK:")))
17392 (defvar org-clock-history) ; defined in org-clock.el
17393 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17394 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17395 "Change the date in the time stamp at point.
17396 The date will be changed by N times WHAT. WHAT can be `day', `month',
17397 `year', `minute', `second'. If WHAT is not given, the cursor position
17398 in the timestamp determines what will be changed.
17399 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17400 (let ((origin (point)) origin-cat
17401 with-hm inactive
17402 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17403 org-ts-what
17404 extra rem
17405 ts time time0 fixnext clrgx)
17406 (if (not (org-at-timestamp-p t))
17407 (user-error "Not at a timestamp"))
17408 (if (and (not what) (eq org-ts-what 'bracket))
17409 (org-toggle-timestamp-type)
17410 ;; Point isn't on brackets. Remember the part of the time-stamp
17411 ;; the point was in. Indeed, size of time-stamps may change,
17412 ;; but point must be kept in the same category nonetheless.
17413 (setq origin-cat org-ts-what)
17414 (if (and (not what) (not (eq org-ts-what 'day))
17415 org-display-custom-times
17416 (get-text-property (point) 'display)
17417 (not (get-text-property (1- (point)) 'display)))
17418 (setq org-ts-what 'day))
17419 (setq org-ts-what (or what org-ts-what)
17420 inactive (= (char-after (match-beginning 0)) ?\[)
17421 ts (match-string 0))
17422 (replace-match "")
17423 (when (string-match
17424 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17426 (setq extra (match-string 1 ts))
17427 (if suppress-tmp-delay
17428 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17429 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17430 (setq with-hm t))
17431 (setq time0 (org-parse-time-string ts))
17432 (when (and updown
17433 (eq org-ts-what 'minute)
17434 (not current-prefix-arg))
17435 ;; This looks like s-up and s-down. Change by one rounding step.
17436 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17437 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17438 (setcar (cdr time0) (+ (nth 1 time0)
17439 (if (> n 0) (- rem) (- dm rem))))))
17440 (setq time
17441 (encode-time (or (car time0) 0)
17442 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17443 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17444 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17445 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17446 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17447 (nthcdr 6 time0)))
17448 (when (and (member org-ts-what '(hour minute))
17449 extra
17450 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17451 (setq extra (org-modify-ts-extra
17452 extra
17453 (if (eq org-ts-what 'hour) 2 5)
17454 n dm)))
17455 (when (integerp org-ts-what)
17456 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17457 (if (eq what 'calendar)
17458 (let ((cal-date (org-get-date-from-calendar)))
17459 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17460 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17461 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17462 (setcar time0 (or (car time0) 0))
17463 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17464 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17465 (setq time (apply 'encode-time time0))))
17466 ;; Insert the new time-stamp, and ensure point stays in the same
17467 ;; category as before (i.e. not after the last position in that
17468 ;; category).
17469 (let ((pos (point)))
17470 ;; Stay before inserted string. `save-excursion' is of no use.
17471 (setq org-last-changed-timestamp
17472 (org-insert-time-stamp time with-hm inactive nil nil extra))
17473 (goto-char pos))
17474 (save-match-data
17475 (looking-at org-ts-regexp3)
17476 (goto-char (cond
17477 ;; `day' category ends before `hour' if any, or at
17478 ;; the end of the day name.
17479 ((eq origin-cat 'day)
17480 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17481 ((eq origin-cat 'hour) (min (match-end 7) origin))
17482 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17483 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17484 ;; `year' and `month' have both fixed size: point
17485 ;; couldn't have moved into another part.
17486 (t origin))))
17487 ;; Update clock if on a CLOCK line.
17488 (org-clock-update-time-maybe)
17489 ;; Maybe adjust the closest clock in `org-clock-history'
17490 (when org-clock-adjust-closest
17491 (if (not (and (org-at-clock-log-p)
17492 (< 1 (length (delq nil (mapcar 'marker-position
17493 org-clock-history))))))
17494 (message "No clock to adjust")
17495 (cond ((save-excursion ; fix previous clock?
17496 (re-search-backward org-ts-regexp0 nil t)
17497 (org-looking-back (concat org-clock-string " \\[")))
17498 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17499 ((save-excursion ; fix next clock?
17500 (re-search-backward org-ts-regexp0 nil t)
17501 (looking-at (concat org-ts-regexp0 "\\] =>")))
17502 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17503 (save-window-excursion
17504 ;; Find closest clock to point, adjust the previous/next one in history
17505 (let* ((p (save-excursion (org-back-to-heading t)))
17506 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17507 (clfixnth
17508 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17509 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17510 (if (not clfixpos)
17511 (message "No clock to adjust")
17512 (save-excursion
17513 (org-goto-marker-or-bmk clfixpos)
17514 (org-show-subtree)
17515 (when (re-search-forward clrgx nil t)
17516 (goto-char (match-beginning 1))
17517 (let (org-clock-adjust-closest)
17518 (org-timestamp-change n org-ts-what updown))
17519 (message "Clock adjusted in %s for heading: %s"
17520 (file-name-nondirectory (buffer-file-name))
17521 (org-get-heading t t)))))))))
17522 ;; Try to recenter the calendar window, if any.
17523 (if (and org-calendar-follow-timestamp-change
17524 (get-buffer-window "*Calendar*" t)
17525 (memq org-ts-what '(day month year)))
17526 (org-recenter-calendar (time-to-days time))))))
17528 (defun org-modify-ts-extra (s pos n dm)
17529 "Change the different parts of the lead-time and repeat fields in timestamp."
17530 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17531 ng h m new rem)
17532 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17533 (cond
17534 ((or (org-pos-in-match-range pos 2)
17535 (org-pos-in-match-range pos 3))
17536 (setq m (string-to-number (match-string 3 s))
17537 h (string-to-number (match-string 2 s)))
17538 (if (org-pos-in-match-range pos 2)
17539 (setq h (+ h n))
17540 (setq n (* dm (org-no-warnings (signum n))))
17541 (when (not (= 0 (setq rem (% m dm))))
17542 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17543 (setq m (+ m n)))
17544 (if (< m 0) (setq m (+ m 60) h (1- h)))
17545 (if (> m 59) (setq m (- m 60) h (1+ h)))
17546 (setq h (min 24 (max 0 h)))
17547 (setq ng 1 new (format "-%02d:%02d" h m)))
17548 ((org-pos-in-match-range pos 6)
17549 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17550 ((org-pos-in-match-range pos 5)
17551 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17553 ((org-pos-in-match-range pos 9)
17554 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17555 ((org-pos-in-match-range pos 8)
17556 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17558 (when ng
17559 (setq s (concat
17560 (substring s 0 (match-beginning ng))
17562 (substring s (match-end ng))))))
17565 (defun org-recenter-calendar (date)
17566 "If the calendar is visible, recenter it to DATE."
17567 (let ((cwin (get-buffer-window "*Calendar*" t)))
17568 (when cwin
17569 (let ((calendar-move-hook nil))
17570 (with-selected-window cwin
17571 (calendar-goto-date (if (listp date) date
17572 (calendar-gregorian-from-absolute date))))))))
17574 (defun org-goto-calendar (&optional arg)
17575 "Go to the Emacs calendar at the current date.
17576 If there is a time stamp in the current line, go to that date.
17577 A prefix ARG can be used to force the current date."
17578 (interactive "P")
17579 (let ((tsr org-ts-regexp) diff
17580 (calendar-move-hook nil)
17581 (calendar-view-holidays-initially-flag nil)
17582 (calendar-view-diary-initially-flag nil))
17583 (if (or (org-at-timestamp-p)
17584 (save-excursion
17585 (beginning-of-line 1)
17586 (looking-at (concat ".*" tsr))))
17587 (let ((d1 (time-to-days (current-time)))
17588 (d2 (time-to-days
17589 (org-time-string-to-time (match-string 1)))))
17590 (setq diff (- d2 d1))))
17591 (calendar)
17592 (calendar-goto-today)
17593 (if (and diff (not arg)) (calendar-forward-day diff))))
17595 (defun org-get-date-from-calendar ()
17596 "Return a list (month day year) of date at point in calendar."
17597 (with-current-buffer "*Calendar*"
17598 (save-match-data
17599 (calendar-cursor-to-date))))
17601 (defun org-date-from-calendar ()
17602 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17603 If there is already a time stamp at the cursor position, update it."
17604 (interactive)
17605 (if (org-at-timestamp-p t)
17606 (org-timestamp-change 0 'calendar)
17607 (let ((cal-date (org-get-date-from-calendar)))
17608 (org-insert-time-stamp
17609 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17611 (defcustom org-effort-durations
17612 `(("h" . 60)
17613 ("d" . ,(* 60 8))
17614 ("w" . ,(* 60 8 5))
17615 ("m" . ,(* 60 8 5 4))
17616 ("y" . ,(* 60 8 5 40)))
17617 "Conversion factor to minutes for an effort modifier.
17619 Each entry has the form (MODIFIER . MINUTES).
17621 In an effort string, a number followed by MODIFIER is multiplied
17622 by the specified number of MINUTES to obtain an effort in
17623 minutes.
17625 For example, if the value of this variable is ((\"hours\" . 60)), then an
17626 effort string \"2hours\" is equivalent to 120 minutes."
17627 :group 'org-agenda
17628 :version "24.1"
17629 :type '(alist :key-type (string :tag "Modifier")
17630 :value-type (number :tag "Minutes")))
17632 (defun org-minutes-to-clocksum-string (m)
17633 "Format number of minutes as a clocksum string.
17634 The format is determined by `org-time-clocksum-format',
17635 `org-time-clocksum-use-fractional' and
17636 `org-time-clocksum-fractional-format' and
17637 `org-time-clocksum-use-effort-durations'."
17638 (let ((clocksum "")
17639 (m (round m)) ; Don't allow fractions of minutes
17640 h d w mo y fmt n)
17641 (setq h (if org-time-clocksum-use-effort-durations
17642 (cdr (assoc "h" org-effort-durations)) 60)
17643 d (if org-time-clocksum-use-effort-durations
17644 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17645 w (if org-time-clocksum-use-effort-durations
17646 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17647 mo (if org-time-clocksum-use-effort-durations
17648 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17649 y (if org-time-clocksum-use-effort-durations
17650 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17651 ;; fractional format
17652 (if org-time-clocksum-use-fractional
17653 (cond
17654 ;; single format string
17655 ((stringp org-time-clocksum-fractional-format)
17656 (format org-time-clocksum-fractional-format (/ m (float h))))
17657 ;; choice of fractional formats for different time units
17658 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17659 (> (/ (truncate m) (* y d h)) 0))
17660 (format fmt (/ m (* y d (float h)))))
17661 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17662 (> (/ (truncate m) (* mo d h)) 0))
17663 (format fmt (/ m (* mo d (float h)))))
17664 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17665 (> (/ (truncate m) (* w d h)) 0))
17666 (format fmt (/ m (* w d (float h)))))
17667 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17668 (> (/ (truncate m) (* d h)) 0))
17669 (format fmt (/ m (* d (float h)))))
17670 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17671 (> (/ (truncate m) h) 0))
17672 (format fmt (/ m (float h))))
17673 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17674 (format fmt m))
17675 ;; fall back to smallest time unit with a format
17676 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17677 (format fmt (/ m (float h))))
17678 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17679 (format fmt (/ m (* d (float h)))))
17680 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17681 (format fmt (/ m (* w d (float h)))))
17682 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17683 (format fmt (/ m (* mo d (float h)))))
17684 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17685 (format fmt (/ m (* y d (float h))))))
17686 ;; standard (non-fractional) format, with single format string
17687 (if (stringp org-time-clocksum-format)
17688 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17689 ;; separate formats components
17690 (and (setq fmt (plist-get org-time-clocksum-format :years))
17691 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17692 (plist-get org-time-clocksum-format :require-years))
17693 (setq clocksum (concat clocksum (format fmt n))
17694 m (- m (* n y d h))))
17695 (and (setq fmt (plist-get org-time-clocksum-format :months))
17696 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17697 (plist-get org-time-clocksum-format :require-months))
17698 (setq clocksum (concat clocksum (format fmt n))
17699 m (- m (* n mo d h))))
17700 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17701 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17702 (plist-get org-time-clocksum-format :require-weeks))
17703 (setq clocksum (concat clocksum (format fmt n))
17704 m (- m (* n w d h))))
17705 (and (setq fmt (plist-get org-time-clocksum-format :days))
17706 (or (> (setq n (/ (truncate m) (* d h))) 0)
17707 (plist-get org-time-clocksum-format :require-days))
17708 (setq clocksum (concat clocksum (format fmt n))
17709 m (- m (* n d h))))
17710 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17711 (or (> (setq n (/ (truncate m) h)) 0)
17712 (plist-get org-time-clocksum-format :require-hours))
17713 (setq clocksum (concat clocksum (format fmt n))
17714 m (- m (* n h))))
17715 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17716 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17717 (setq clocksum (concat clocksum (format fmt m))))
17718 ;; return formatted time duration
17719 clocksum))))
17721 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17722 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17723 "Org mode version 8.0")
17725 (defun org-hours-to-clocksum-string (n)
17726 (org-minutes-to-clocksum-string (* n 60)))
17728 (defun org-hh:mm-string-to-minutes (s)
17729 "Convert a string H:MM to a number of minutes.
17730 If the string is just a number, interpret it as minutes.
17731 In fact, the first hh:mm or number in the string will be taken,
17732 there can be extra stuff in the string.
17733 If no number is found, the return value is 0."
17734 (cond
17735 ((integerp s) s)
17736 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17737 (+ (* (string-to-number (match-string 1 s)) 60)
17738 (string-to-number (match-string 2 s))))
17739 ((string-match "\\([0-9]+\\)" s)
17740 (string-to-number (match-string 1 s)))
17741 (t 0)))
17743 (defcustom org-image-actual-width t
17744 "Should we use the actual width of images when inlining them?
17746 When set to `t', always use the image width.
17748 When set to a number, use imagemagick (when available) to set
17749 the image's width to this value.
17751 When set to a number in a list, try to get the width from any
17752 #+ATTR.* keyword if it matches a width specification like
17754 #+ATTR_HTML: :width 300px
17756 and fall back on that number if none is found.
17758 When set to nil, try to get the width from an #+ATTR.* keyword
17759 and fall back on the original width if none is found.
17761 This requires Emacs >= 24.1, build with imagemagick support."
17762 :group 'org-appearance
17763 :version "24.4"
17764 :package-version '(Org . "8.0")
17765 :type '(choice
17766 (const :tag "Use the image width" t)
17767 (integer :tag "Use a number of pixels")
17768 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17769 (const :tag "Use #+ATTR* or don't resize" nil)))
17771 (defcustom org-agenda-inhibit-startup nil
17772 "Inhibit startup when preparing agenda buffers.
17773 When this variable is `t' (the default), the initialization of
17774 the Org agenda buffers is inhibited: e.g. the visibility state
17775 is not set, the tables are not re-aligned, etc."
17776 :type 'boolean
17777 :version "24.3"
17778 :group 'org-agenda)
17780 (defcustom org-agenda-ignore-drawer-properties nil
17781 "Avoid updating text properties when building the agenda.
17782 Properties are used to prepare buffers for effort estimates, appointments,
17783 and subtree-local categories.
17784 If you don't use these in the agenda, you can add them to this list and
17785 agenda building will be a bit faster.
17786 The value is a list, with zero or more of the symbols `effort', `appt',
17787 or `category'."
17788 :type '(set :greedy t
17789 (const effort)
17790 (const appt)
17791 (const category))
17792 :version "24.3"
17793 :group 'org-agenda)
17795 (defun org-duration-string-to-minutes (s &optional output-to-string)
17796 "Convert a duration string S to minutes.
17798 A bare number is interpreted as minutes, modifiers can be set by
17799 customizing `org-effort-durations' (which see).
17801 Entries containing a colon are interpreted as H:MM by
17802 `org-hh:mm-string-to-minutes'."
17803 (let ((result 0)
17804 (re (concat "\\([0-9.]+\\) *\\("
17805 (regexp-opt (mapcar 'car org-effort-durations))
17806 "\\)")))
17807 (while (string-match re s)
17808 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17809 (string-to-number (match-string 1 s))))
17810 (setq s (replace-match "" nil t s)))
17811 (setq result (floor result))
17812 (incf result (org-hh:mm-string-to-minutes s))
17813 (if output-to-string (number-to-string result) result)))
17815 ;;;; Files
17817 (defun org-save-all-org-buffers ()
17818 "Save all Org-mode buffers without user confirmation."
17819 (interactive)
17820 (message "Saving all Org-mode buffers...")
17821 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17822 (when (featurep 'org-id) (org-id-locations-save))
17823 (message "Saving all Org-mode buffers... done"))
17825 (defun org-revert-all-org-buffers ()
17826 "Revert all Org-mode buffers.
17827 Prompt for confirmation when there are unsaved changes.
17828 Be sure you know what you are doing before letting this function
17829 overwrite your changes.
17831 This function is useful in a setup where one tracks org files
17832 with a version control system, to revert on one machine after pulling
17833 changes from another. I believe the procedure must be like this:
17835 1. M-x org-save-all-org-buffers
17836 2. Pull changes from the other machine, resolve conflicts
17837 3. M-x org-revert-all-org-buffers"
17838 (interactive)
17839 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17840 (user-error "Abort"))
17841 (save-excursion
17842 (save-window-excursion
17843 (mapc
17844 (lambda (b)
17845 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17846 (with-current-buffer b buffer-file-name))
17847 (org-pop-to-buffer-same-window b)
17848 (revert-buffer t 'no-confirm)))
17849 (buffer-list))
17850 (when (and (featurep 'org-id) org-id-track-globally)
17851 (org-id-locations-load)))))
17853 ;;;; Agenda files
17855 ;;;###autoload
17856 (defun org-switchb (&optional arg)
17857 "Switch between Org buffers.
17858 With one prefix argument, restrict available buffers to files.
17859 With two prefix arguments, restrict available buffers to agenda files.
17861 Defaults to `iswitchb' for buffer name completion.
17862 Set `org-completion-use-ido' to make it use ido instead."
17863 (interactive "P")
17864 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17865 ((equal arg '(16)) (org-buffer-list 'agenda))
17866 (t (org-buffer-list))))
17867 (org-completion-use-iswitchb org-completion-use-iswitchb)
17868 (org-completion-use-ido org-completion-use-ido))
17869 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17870 (setq org-completion-use-iswitchb t))
17871 (org-pop-to-buffer-same-window
17872 (org-icompleting-read "Org buffer: "
17873 (mapcar 'list (mapcar 'buffer-name blist))
17874 nil t))))
17876 ;;; Define some older names previously used for this functionality
17877 ;;;###autoload
17878 (defalias 'org-ido-switchb 'org-switchb)
17879 ;;;###autoload
17880 (defalias 'org-iswitchb 'org-switchb)
17882 (defun org-buffer-list (&optional predicate exclude-tmp)
17883 "Return a list of Org buffers.
17884 PREDICATE can be `export', `files' or `agenda'.
17886 export restrict the list to Export buffers.
17887 files restrict the list to buffers visiting Org files.
17888 agenda restrict the list to buffers visiting agenda files.
17890 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17891 (let* ((bfn nil)
17892 (agenda-files (and (eq predicate 'agenda)
17893 (mapcar 'file-truename (org-agenda-files t))))
17894 (filter
17895 (cond
17896 ((eq predicate 'files)
17897 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17898 ((eq predicate 'export)
17899 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17900 ((eq predicate 'agenda)
17901 (lambda (b)
17902 (with-current-buffer b
17903 (and (derived-mode-p 'org-mode)
17904 (setq bfn (buffer-file-name b))
17905 (member (file-truename bfn) agenda-files)))))
17906 (t (lambda (b) (with-current-buffer b
17907 (or (derived-mode-p 'org-mode)
17908 (string-match "\*Org .*Export"
17909 (buffer-name b)))))))))
17910 (delq nil
17911 (mapcar
17912 (lambda(b)
17913 (if (and (funcall filter b)
17914 (or (not exclude-tmp)
17915 (not (string-match "tmp" (buffer-name b)))))
17917 nil))
17918 (buffer-list)))))
17920 (defun org-agenda-files (&optional unrestricted archives)
17921 "Get the list of agenda files.
17922 Optional UNRESTRICTED means return the full list even if a restriction
17923 is currently in place.
17924 When ARCHIVES is t, include all archive files that are really being
17925 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17926 `org-agenda-archives-mode' is t."
17927 (let ((files
17928 (cond
17929 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17930 ((stringp org-agenda-files) (org-read-agenda-file-list))
17931 ((listp org-agenda-files) org-agenda-files)
17932 (t (error "Invalid value of `org-agenda-files'")))))
17933 (setq files (apply 'append
17934 (mapcar (lambda (f)
17935 (if (file-directory-p f)
17936 (directory-files
17937 f t org-agenda-file-regexp)
17938 (list f)))
17939 files)))
17940 (when org-agenda-skip-unavailable-files
17941 (setq files (delq nil
17942 (mapcar (function
17943 (lambda (file)
17944 (and (file-readable-p file) file)))
17945 files))))
17946 (when (or (eq archives t)
17947 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17948 (setq files (org-add-archive-files files)))
17949 files))
17951 (defun org-agenda-file-p (&optional file)
17952 "Return non-nil, if FILE is an agenda file.
17953 If FILE is omitted, use the file associated with the current
17954 buffer."
17955 (member (or file (buffer-file-name))
17956 (org-agenda-files t)))
17958 (defun org-edit-agenda-file-list ()
17959 "Edit the list of agenda files.
17960 Depending on setup, this either uses customize to edit the variable
17961 `org-agenda-files', or it visits the file that is holding the list. In the
17962 latter case, the buffer is set up in a way that saving it automatically kills
17963 the buffer and restores the previous window configuration."
17964 (interactive)
17965 (if (stringp org-agenda-files)
17966 (let ((cw (current-window-configuration)))
17967 (find-file org-agenda-files)
17968 (org-set-local 'org-window-configuration cw)
17969 (org-add-hook 'after-save-hook
17970 (lambda ()
17971 (set-window-configuration
17972 (prog1 org-window-configuration
17973 (kill-buffer (current-buffer))))
17974 (org-install-agenda-files-menu)
17975 (message "New agenda file list installed"))
17976 nil 'local)
17977 (message "%s" (substitute-command-keys
17978 "Edit list and finish with \\[save-buffer]")))
17979 (customize-variable 'org-agenda-files)))
17981 (defun org-store-new-agenda-file-list (list)
17982 "Set new value for the agenda file list and save it correctly."
17983 (if (stringp org-agenda-files)
17984 (let ((fe (org-read-agenda-file-list t)) b u)
17985 (while (setq b (find-buffer-visiting org-agenda-files))
17986 (kill-buffer b))
17987 (with-temp-file org-agenda-files
17988 (insert
17989 (mapconcat
17990 (lambda (f) ;; Keep un-expanded entries.
17991 (if (setq u (assoc f fe))
17992 (cdr u)
17994 list "\n")
17995 "\n")))
17996 (let ((org-mode-hook nil) (org-inhibit-startup t)
17997 (org-insert-mode-line-in-empty-file nil))
17998 (setq org-agenda-files list)
17999 (customize-save-variable 'org-agenda-files org-agenda-files))))
18001 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18002 "Read the list of agenda files from a file.
18003 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18004 filenames, used by `org-store-new-agenda-file-list' to write back
18005 un-expanded file names."
18006 (when (file-directory-p org-agenda-files)
18007 (error "`org-agenda-files' cannot be a single directory"))
18008 (when (stringp org-agenda-files)
18009 (with-temp-buffer
18010 (insert-file-contents org-agenda-files)
18011 (mapcar
18012 (lambda (f)
18013 (let ((e (expand-file-name (substitute-in-file-name f)
18014 org-directory)))
18015 (if pair-with-expansion
18016 (cons e f)
18017 e)))
18018 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18020 ;;;###autoload
18021 (defun org-cycle-agenda-files ()
18022 "Cycle through the files in `org-agenda-files'.
18023 If the current buffer visits an agenda file, find the next one in the list.
18024 If the current buffer does not, find the first agenda file."
18025 (interactive)
18026 (let* ((fs (org-agenda-files t))
18027 (files (append fs (list (car fs))))
18028 (tcf (if buffer-file-name (file-truename buffer-file-name)))
18029 file)
18030 (unless files (user-error "No agenda files"))
18031 (catch 'exit
18032 (while (setq file (pop files))
18033 (if (equal (file-truename file) tcf)
18034 (when (car files)
18035 (find-file (car files))
18036 (throw 'exit t))))
18037 (find-file (car fs)))
18038 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
18040 (defun org-agenda-file-to-front (&optional to-end)
18041 "Move/add the current file to the top of the agenda file list.
18042 If the file is not present in the list, it is added to the front. If it is
18043 present, it is moved there. With optional argument TO-END, add/move to the
18044 end of the list."
18045 (interactive "P")
18046 (let ((org-agenda-skip-unavailable-files nil)
18047 (file-alist (mapcar (lambda (x)
18048 (cons (file-truename x) x))
18049 (org-agenda-files t)))
18050 (ctf (file-truename
18051 (or buffer-file-name
18052 (user-error "Please save the current buffer to a file"))))
18053 x had)
18054 (setq x (assoc ctf file-alist) had x)
18056 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18057 (if to-end
18058 (setq file-alist (append (delq x file-alist) (list x)))
18059 (setq file-alist (cons x (delq x file-alist))))
18060 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18061 (org-install-agenda-files-menu)
18062 (message "File %s to %s of agenda file list"
18063 (if had "moved" "added") (if to-end "end" "front"))))
18065 (defun org-remove-file (&optional file)
18066 "Remove current file from the list of files in variable `org-agenda-files'.
18067 These are the files which are being checked for agenda entries.
18068 Optional argument FILE means use this file instead of the current."
18069 (interactive)
18070 (let* ((org-agenda-skip-unavailable-files nil)
18071 (file (or file buffer-file-name
18072 (user-error "Current buffer does not visit a file")))
18073 (true-file (file-truename file))
18074 (afile (abbreviate-file-name file))
18075 (files (delq nil (mapcar
18076 (lambda (x)
18077 (if (equal true-file
18078 (file-truename x))
18079 nil x))
18080 (org-agenda-files t)))))
18081 (if (not (= (length files) (length (org-agenda-files t))))
18082 (progn
18083 (org-store-new-agenda-file-list files)
18084 (org-install-agenda-files-menu)
18085 (message "Removed file: %s" afile))
18086 (message "File was not in list: %s (not removed)" afile))))
18088 (defun org-file-menu-entry (file)
18089 (vector file (list 'find-file file) t))
18091 (defun org-check-agenda-file (file)
18092 "Make sure FILE exists. If not, ask user what to do."
18093 (when (not (file-exists-p file))
18094 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18095 (abbreviate-file-name file))
18096 (let ((r (downcase (read-char-exclusive))))
18097 (cond
18098 ((equal r ?r)
18099 (org-remove-file file)
18100 (throw 'nextfile t))
18101 (t (error "Abort"))))))
18103 (defun org-get-agenda-file-buffer (file)
18104 "Get a buffer visiting FILE. If the buffer needs to be created, add
18105 it to the list of buffers which might be released later."
18106 (let ((buf (org-find-base-buffer-visiting file)))
18107 (if buf
18108 buf ; just return it
18109 ;; Make a new buffer and remember it
18110 (setq buf (find-file-noselect file))
18111 (if buf (push buf org-agenda-new-buffers))
18112 buf)))
18114 (defun org-release-buffers (blist)
18115 "Release all buffers in list, asking the user for confirmation when needed.
18116 When a buffer is unmodified, it is just killed. When modified, it is saved
18117 \(if the user agrees) and then killed."
18118 (let (buf file)
18119 (while (setq buf (pop blist))
18120 (setq file (buffer-file-name buf))
18121 (when (and (buffer-modified-p buf)
18122 file
18123 (y-or-n-p (format "Save file %s? " file)))
18124 (with-current-buffer buf (save-buffer)))
18125 (kill-buffer buf))))
18127 (defun org-agenda-prepare-buffers (files)
18128 "Create buffers for all agenda files, protect archived trees and comments."
18129 (interactive)
18130 (let ((pa '(:org-archived t))
18131 (pc '(:org-comment t))
18132 (pall '(:org-archived t :org-comment t))
18133 (inhibit-read-only t)
18134 (org-inhibit-startup org-agenda-inhibit-startup)
18135 (rea (concat ":" org-archive-tag ":"))
18136 file re pos)
18137 (setq org-tag-alist-for-agenda nil
18138 org-tag-groups-alist-for-agenda nil)
18139 (save-excursion
18140 (save-restriction
18141 (while (setq file (pop files))
18142 (catch 'nextfile
18143 (if (bufferp file)
18144 (set-buffer file)
18145 (org-check-agenda-file file)
18146 (set-buffer (org-get-agenda-file-buffer file)))
18147 (widen)
18148 (org-set-regexps-and-options-for-tags)
18149 (setq pos (point))
18150 (goto-char (point-min))
18151 (let ((case-fold-search t))
18152 (when (search-forward "#+setupfile" nil t)
18153 ;; Don't set all regexps and options systematically as
18154 ;; this is only run for setting agenda tags from setup
18155 ;; file
18156 (org-set-regexps-and-options)))
18157 (or (memq 'category org-agenda-ignore-drawer-properties)
18158 (org-refresh-category-properties))
18159 (or (memq 'effort org-agenda-ignore-drawer-properties)
18160 (org-refresh-properties org-effort-property 'org-effort))
18161 (or (memq 'appt org-agenda-ignore-drawer-properties)
18162 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18163 (setq org-todo-keywords-for-agenda
18164 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18165 (setq org-done-keywords-for-agenda
18166 (append org-done-keywords-for-agenda org-done-keywords))
18167 (setq org-todo-keyword-alist-for-agenda
18168 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18169 (setq org-drawers-for-agenda
18170 (append org-drawers-for-agenda org-drawers))
18171 (setq org-tag-alist-for-agenda
18172 (org-uniquify
18173 (append org-tag-alist-for-agenda
18174 org-tag-alist
18175 org-tag-persistent-alist)))
18176 (if org-group-tags
18177 (setq org-tag-groups-alist-for-agenda
18178 (org-uniquify-alist
18179 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18180 (org-with-silent-modifications
18181 (save-excursion
18182 (remove-text-properties (point-min) (point-max) pall)
18183 (when org-agenda-skip-archived-trees
18184 (goto-char (point-min))
18185 (while (re-search-forward rea nil t)
18186 (if (org-at-heading-p t)
18187 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18188 (goto-char (point-min))
18189 (setq re (format org-heading-keyword-regexp-format
18190 org-comment-string))
18191 (while (re-search-forward re nil t)
18192 (add-text-properties
18193 (match-beginning 0) (org-end-of-subtree t) pc))))
18194 (goto-char pos)))))
18195 (setq org-todo-keywords-for-agenda
18196 (org-uniquify org-todo-keywords-for-agenda))
18197 (setq org-todo-keyword-alist-for-agenda
18198 (org-uniquify org-todo-keyword-alist-for-agenda))))
18201 ;;;; CDLaTeX minor mode
18203 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18204 "Keymap for the minor `org-cdlatex-mode'.")
18206 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18207 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18208 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18209 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18210 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
18212 (defvar org-cdlatex-texmathp-advice-is-done nil
18213 "Flag remembering if we have applied the advice to texmathp already.")
18215 (define-minor-mode org-cdlatex-mode
18216 "Toggle the minor `org-cdlatex-mode'.
18217 This mode supports entering LaTeX environment and math in LaTeX fragments
18218 in Org-mode.
18219 \\{org-cdlatex-mode-map}"
18220 nil " OCDL" nil
18221 (when org-cdlatex-mode
18222 (require 'cdlatex)
18223 (run-hooks 'cdlatex-mode-hook)
18224 (cdlatex-compute-tables))
18225 (unless org-cdlatex-texmathp-advice-is-done
18226 (setq org-cdlatex-texmathp-advice-is-done t)
18227 (defadvice texmathp (around org-math-always-on activate)
18228 "Always return t in org-mode buffers.
18229 This is because we want to insert math symbols without dollars even outside
18230 the LaTeX math segments. If Orgmode thinks that point is actually inside
18231 an embedded LaTeX fragment, let texmathp do its job.
18232 \\[org-cdlatex-mode-map]"
18233 (interactive)
18234 (let (p)
18235 (cond
18236 ((not (derived-mode-p 'org-mode)) ad-do-it)
18237 ((eq this-command 'cdlatex-math-symbol)
18238 (setq ad-return-value t
18239 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18241 (let ((p (org-inside-LaTeX-fragment-p)))
18242 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18243 (setq ad-return-value t
18244 texmathp-why '("Org-mode embedded math" . 0))
18245 (if p ad-do-it)))))))))
18247 (defun turn-on-org-cdlatex ()
18248 "Unconditionally turn on `org-cdlatex-mode'."
18249 (org-cdlatex-mode 1))
18251 (defun org-try-cdlatex-tab ()
18252 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18253 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18254 - inside a LaTeX fragment, or
18255 - after the first word in a line, where an abbreviation expansion could
18256 insert a LaTeX environment."
18257 (when org-cdlatex-mode
18258 (cond
18259 ;; Before any word on the line: No expansion possible.
18260 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18261 ;; Just after first word on the line: Expand it. Make sure it
18262 ;; cannot happen on headlines, though.
18263 ((save-excursion
18264 (skip-chars-backward "a-zA-Z0-9*")
18265 (skip-chars-backward " \t")
18266 (and (bolp) (not (org-at-heading-p))))
18267 (cdlatex-tab) t)
18268 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18270 (defun org-cdlatex-underscore-caret (&optional arg)
18271 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18272 Revert to the normal definition outside of these fragments."
18273 (interactive "P")
18274 (if (org-inside-LaTeX-fragment-p)
18275 (call-interactively 'cdlatex-sub-superscript)
18276 (let (org-cdlatex-mode)
18277 (call-interactively (key-binding (vector last-input-event))))))
18279 (defun org-cdlatex-math-modify (&optional arg)
18280 "Execute `cdlatex-math-modify' in LaTeX fragments.
18281 Revert to the normal definition outside of these fragments."
18282 (interactive "P")
18283 (if (org-inside-LaTeX-fragment-p)
18284 (call-interactively 'cdlatex-math-modify)
18285 (let (org-cdlatex-mode)
18286 (call-interactively (key-binding (vector last-input-event))))))
18290 ;;;; LaTeX fragments
18292 (defvar org-latex-regexps
18293 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
18294 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
18295 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
18296 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18297 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18298 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
18299 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
18300 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
18301 "Regular expressions for matching embedded LaTeX.")
18303 (defun org-inside-LaTeX-fragment-p ()
18304 "Test if point is inside a LaTeX fragment.
18305 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18306 sequence appearing also before point.
18307 Even though the matchers for math are configurable, this function assumes
18308 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18309 delimiters are skipped when they have been removed by customization.
18310 The return value is nil, or a cons cell with the delimiter and the
18311 position of this delimiter.
18313 This function does a reasonably good job, but can locally be fooled by
18314 for example currency specifications. For example it will assume being in
18315 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18316 fragments that are properly closed, but during editing, we have to live
18317 with the uncertainty caused by missing closing delimiters. This function
18318 looks only before point, not after."
18319 (catch 'exit
18320 (let ((pos (point))
18321 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18322 (lim (progn
18323 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18324 (point)))
18325 dd-on str (start 0) m re)
18326 (goto-char pos)
18327 (when dodollar
18328 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18329 re (nth 1 (assoc "$" org-latex-regexps)))
18330 (while (string-match re str start)
18331 (cond
18332 ((= (match-end 0) (length str))
18333 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18334 ((= (match-end 0) (- (length str) 5))
18335 (throw 'exit nil))
18336 (t (setq start (match-end 0))))))
18337 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18338 (goto-char pos)
18339 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18340 (and (match-beginning 2) (throw 'exit nil))
18341 ;; count $$
18342 (while (re-search-backward "\\$\\$" lim t)
18343 (setq dd-on (not dd-on)))
18344 (goto-char pos)
18345 (if dd-on (cons "$$" m))))))
18347 (defun org-inside-latex-macro-p ()
18348 "Is point inside a LaTeX macro or its arguments?"
18349 (save-match-data
18350 (org-in-regexp
18351 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18353 (defvar org-latex-fragment-image-overlays nil
18354 "List of overlays carrying the images of latex fragments.")
18355 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18357 (defun org-remove-latex-fragment-image-overlays ()
18358 "Remove all overlays with LaTeX fragment images in current buffer."
18359 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18360 (setq org-latex-fragment-image-overlays nil))
18362 (defun org-preview-latex-fragment (&optional subtree)
18363 "Preview the LaTeX fragment at point, or all locally or globally.
18364 If the cursor is in a LaTeX fragment, create the image and overlay
18365 it over the source code. If there is no fragment at point, display
18366 all fragments in the current text, from one headline to the next. With
18367 prefix SUBTREE, display all fragments in the current subtree. With a
18368 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18369 the cursor is before the first headline,
18370 display all fragments in the buffer.
18371 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18372 (interactive "P")
18373 (unless buffer-file-name
18374 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18375 (when (display-graphic-p)
18376 (org-remove-latex-fragment-image-overlays)
18377 (save-excursion
18378 (save-restriction
18379 (let (beg end at msg)
18380 (cond
18381 ((or (equal subtree '(16))
18382 (not (save-excursion
18383 (re-search-backward org-outline-regexp-bol nil t))))
18384 (setq beg (point-min) end (point-max)
18385 msg "Creating images for buffer...%s"))
18386 ((equal subtree '(4))
18387 (org-back-to-heading)
18388 (setq beg (point) end (org-end-of-subtree t)
18389 msg "Creating images for subtree...%s"))
18391 (if (setq at (org-inside-LaTeX-fragment-p))
18392 (goto-char (max (point-min) (- (cdr at) 2)))
18393 (org-back-to-heading))
18394 (setq beg (point) end (progn (outline-next-heading) (point))
18395 msg (if at "Creating image...%s"
18396 "Creating images for entry...%s"))))
18397 (message msg "")
18398 (narrow-to-region beg end)
18399 (goto-char beg)
18400 (org-format-latex
18401 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18402 (file-name-nondirectory
18403 buffer-file-name)))
18404 default-directory 'overlays msg at 'forbuffer
18405 org-latex-create-formula-image-program)
18406 (message msg "done. Use `C-c C-c' to remove images."))))))
18408 (defun org-format-latex (prefix &optional dir overlays msg at
18409 forbuffer processing-type)
18410 "Replace LaTeX fragments with links to an image, and produce images.
18411 Some of the options can be changed using the variable
18412 `org-format-latex-options'."
18413 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18414 (let* ((prefixnodir (file-name-nondirectory prefix))
18415 (absprefix (expand-file-name prefix dir))
18416 (todir (file-name-directory absprefix))
18417 (opt org-format-latex-options)
18418 (optnew org-format-latex-options)
18419 (matchers (plist-get opt :matchers))
18420 (re-list org-latex-regexps)
18421 (cnt 0) txt hash link beg end re e checkdir
18422 string
18423 m n block-type block linkfile movefile ov)
18424 ;; Check the different regular expressions
18425 (while (setq e (pop re-list))
18426 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18427 block (if block-type "\n\n" ""))
18428 (when (member m matchers)
18429 (goto-char (point-min))
18430 (while (re-search-forward re nil t)
18431 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18432 (or (not overlays)
18433 (not (eq (get-char-property (match-beginning n)
18434 'org-overlay-type)
18435 'org-latex-overlay))))
18436 (cond
18437 ((eq processing-type 'verbatim))
18438 ((eq processing-type 'mathjax)
18439 ;; Prepare for MathJax processing.
18440 (setq string (match-string n))
18441 (when (member m '("$" "$1"))
18442 (save-excursion
18443 (delete-region (match-beginning n) (match-end n))
18444 (goto-char (match-beginning n))
18445 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18446 ((or (eq processing-type 'dvipng)
18447 (eq processing-type 'imagemagick))
18448 ;; Process to an image.
18449 (setq txt (match-string n)
18450 beg (match-beginning n) end (match-end n)
18451 cnt (1+ cnt))
18452 (let ((face (face-at-point))
18453 (fg (plist-get opt :foreground))
18454 (bg (plist-get opt :background))
18455 ;; Ensure full list is printed.
18456 print-length print-level)
18457 (when forbuffer
18458 ;; Get the colors from the face at point.
18459 (goto-char beg)
18460 (when (eq fg 'auto)
18461 (setq fg (face-attribute face :foreground nil 'default)))
18462 (when (eq bg 'auto)
18463 (setq bg (face-attribute face :background nil 'default)))
18464 (setq optnew (copy-sequence opt))
18465 (plist-put optnew :foreground fg)
18466 (plist-put optnew :background bg))
18467 (setq hash (sha1 (prin1-to-string
18468 (list org-format-latex-header
18469 org-latex-default-packages-alist
18470 org-latex-packages-alist
18471 org-format-latex-options
18472 forbuffer txt fg bg)))
18473 linkfile (format "%s_%s.png" prefix hash)
18474 movefile (format "%s_%s.png" absprefix hash)))
18475 (setq link (concat block "[[file:" linkfile "]]" block))
18476 (if msg (message msg cnt))
18477 (goto-char beg)
18478 (unless checkdir ; Ensure the directory exists.
18479 (setq checkdir t)
18480 (or (file-directory-p todir) (make-directory todir t)))
18481 (unless (file-exists-p movefile)
18482 (org-create-formula-image
18483 txt movefile optnew forbuffer processing-type))
18484 (if overlays
18485 (progn
18486 (mapc (lambda (o)
18487 (if (eq (overlay-get o 'org-overlay-type)
18488 'org-latex-overlay)
18489 (delete-overlay o)))
18490 (overlays-in beg end))
18491 (setq ov (make-overlay beg end))
18492 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18493 (if (featurep 'xemacs)
18494 (progn
18495 (overlay-put ov 'invisible t)
18496 (overlay-put
18497 ov 'end-glyph
18498 (make-glyph (vector 'png :file movefile))))
18499 (overlay-put
18500 ov 'display
18501 (list 'image :type 'png :file movefile :ascent 'center)))
18502 (push ov org-latex-fragment-image-overlays)
18503 (goto-char end))
18504 (delete-region beg end)
18505 (insert (org-add-props link
18506 (list 'org-latex-src
18507 (replace-regexp-in-string
18508 "\"" "" txt)
18509 'org-latex-src-embed-type
18510 (if block-type 'paragraph 'character))))))
18511 ((eq processing-type 'mathml)
18512 ;; Process to MathML
18513 (unless (save-match-data (org-format-latex-mathml-available-p))
18514 (user-error "LaTeX to MathML converter not configured"))
18515 (setq txt (match-string n)
18516 beg (match-beginning n) end (match-end n)
18517 cnt (1+ cnt))
18518 (if msg (message msg cnt))
18519 (goto-char beg)
18520 (delete-region beg end)
18521 (insert (org-format-latex-as-mathml
18522 txt block-type prefix dir)))
18524 (error "Unknown conversion type %s for LaTeX fragments"
18525 processing-type)))))))))
18527 (defun org-create-math-formula (latex-frag &optional mathml-file)
18528 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18529 Use `org-latex-to-mathml-convert-command'. If the conversion is
18530 sucessful, return the portion between \"<math...> </math>\"
18531 elements otherwise return nil. When MATHML-FILE is specified,
18532 write the results in to that file. When invoked as an
18533 interactive command, prompt for LATEX-FRAG, with initial value
18534 set to the current active region and echo the results for user
18535 inspection."
18536 (interactive (list (let ((frag (when (org-region-active-p)
18537 (buffer-substring-no-properties
18538 (region-beginning) (region-end)))))
18539 (read-string "LaTeX Fragment: " frag nil frag))))
18540 (unless latex-frag (error "Invalid LaTeX fragment"))
18541 (let* ((tmp-in-file (file-relative-name
18542 (make-temp-name (expand-file-name "ltxmathml-in"))))
18543 (ignore (write-region latex-frag nil tmp-in-file))
18544 (tmp-out-file (file-relative-name
18545 (make-temp-name (expand-file-name "ltxmathml-out"))))
18546 (cmd (format-spec
18547 org-latex-to-mathml-convert-command
18548 `((?j . ,(shell-quote-argument
18549 (expand-file-name org-latex-to-mathml-jar-file)))
18550 (?I . ,(shell-quote-argument tmp-in-file))
18551 (?o . ,(shell-quote-argument tmp-out-file)))))
18552 mathml shell-command-output)
18553 (when (org-called-interactively-p 'any)
18554 (unless (org-format-latex-mathml-available-p)
18555 (user-error "LaTeX to MathML converter not configured")))
18556 (message "Running %s" cmd)
18557 (setq shell-command-output (shell-command-to-string cmd))
18558 (setq mathml
18559 (when (file-readable-p tmp-out-file)
18560 (with-current-buffer (find-file-noselect tmp-out-file t)
18561 (goto-char (point-min))
18562 (when (re-search-forward
18563 (concat
18564 (regexp-quote
18565 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18566 "\\(.\\|\n\\)*"
18567 (regexp-quote "</math>")) nil t)
18568 (prog1 (match-string 0) (kill-buffer))))))
18569 (cond
18570 (mathml
18571 (setq mathml
18572 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18573 (when mathml-file
18574 (write-region mathml nil mathml-file))
18575 (when (org-called-interactively-p 'any)
18576 (message mathml)))
18577 ((message "LaTeX to MathML conversion failed")
18578 (message shell-command-output)))
18579 (delete-file tmp-in-file)
18580 (when (file-exists-p tmp-out-file)
18581 (delete-file tmp-out-file))
18582 mathml))
18584 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18585 prefix &optional dir)
18586 "Use `org-create-math-formula' but check local cache first."
18587 (let* ((absprefix (expand-file-name prefix dir))
18588 (print-length nil) (print-level nil)
18589 (formula-id (concat
18590 "formula-"
18591 (sha1
18592 (prin1-to-string
18593 (list latex-frag
18594 org-latex-to-mathml-convert-command)))))
18595 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18596 (formula-cache-dir (file-name-directory formula-cache)))
18598 (unless (file-directory-p formula-cache-dir)
18599 (make-directory formula-cache-dir t))
18601 (unless (file-exists-p formula-cache)
18602 (org-create-math-formula latex-frag formula-cache))
18604 (if (file-exists-p formula-cache)
18605 ;; Successful conversion. Return the link to MathML file.
18606 (org-add-props
18607 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18608 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18609 'org-latex-src-embed-type (if latex-frag-type
18610 'paragraph 'character)))
18611 ;; Failed conversion. Return the LaTeX fragment verbatim
18612 latex-frag)))
18614 (defun org-create-formula-image (string tofile options buffer &optional type)
18615 "Create an image from LaTeX source using dvipng or convert.
18616 This function calls either `org-create-formula-image-with-dvipng'
18617 or `org-create-formula-image-with-imagemagick' depending on the
18618 value of `org-latex-create-formula-image-program' or on the value
18619 of the optional TYPE variable.
18621 Note: ultimately these two function should be combined as they
18622 share a good deal of logic."
18623 (org-check-external-command
18624 "latex" "needed to convert LaTeX fragments to images")
18625 (funcall
18626 (case (or type org-latex-create-formula-image-program)
18627 ('dvipng
18628 (org-check-external-command
18629 "dvipng" "needed to convert LaTeX fragments to images")
18630 #'org-create-formula-image-with-dvipng)
18631 ('imagemagick
18632 (org-check-external-command
18633 "convert" "you need to install imagemagick")
18634 #'org-create-formula-image-with-imagemagick)
18635 (t (error
18636 "Invalid value of `org-latex-create-formula-image-program'")))
18637 string tofile options buffer))
18639 (declare-function org-export-get-backend "ox" (name))
18640 (declare-function org-export--get-global-options "ox" (&optional backend))
18641 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18642 (declare-function org-latex-guess-inputenc "ox-latex" (header))
18643 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
18644 (defun org-create-formula--latex-header ()
18645 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18646 (let ((info (org-combine-plists (org-export--get-global-options
18647 (org-export-get-backend 'latex))
18648 (org-export--get-inbuffer-options
18649 (org-export-get-backend 'latex)))))
18650 (org-latex-guess-babel-language
18651 (org-latex-guess-inputenc
18652 (org-splice-latex-header
18653 org-format-latex-header
18654 org-latex-default-packages-alist
18655 org-latex-packages-alist t
18656 (plist-get info :latex-header)))
18657 info)))
18659 ;; This function borrows from Ganesh Swami's latex2png.el
18660 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18661 "This calls dvipng."
18662 (require 'ox-latex)
18663 (let* ((tmpdir (if (featurep 'xemacs)
18664 (temp-directory)
18665 temporary-file-directory))
18666 (texfilebase (make-temp-name
18667 (expand-file-name "orgtex" tmpdir)))
18668 (texfile (concat texfilebase ".tex"))
18669 (dvifile (concat texfilebase ".dvi"))
18670 (pngfile (concat texfilebase ".png"))
18671 (fnh (if (featurep 'xemacs)
18672 (font-height (face-font 'default))
18673 (face-attribute 'default :height nil)))
18674 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18675 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18676 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18677 "Black"))
18678 (bg (or (plist-get options (if buffer :background :html-background))
18679 "Transparent")))
18680 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18681 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18682 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18683 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18684 (let ((latex-header (org-create-formula--latex-header)))
18685 (with-temp-file texfile
18686 (insert latex-header)
18687 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18688 (let ((dir default-directory))
18689 (condition-case nil
18690 (progn
18691 (cd tmpdir)
18692 (call-process "latex" nil nil nil texfile))
18693 (error nil))
18694 (cd dir))
18695 (if (not (file-exists-p dvifile))
18696 (progn (message "Failed to create dvi file from %s" texfile) nil)
18697 (condition-case nil
18698 (if (featurep 'xemacs)
18699 (call-process "dvipng" nil nil nil
18700 "-fg" fg "-bg" bg
18701 "-T" "tight"
18702 "-o" pngfile
18703 dvifile)
18704 (call-process "dvipng" nil nil nil
18705 "-fg" fg "-bg" bg
18706 "-D" dpi
18707 ;;"-x" scale "-y" scale
18708 "-T" "tight"
18709 "-o" pngfile
18710 dvifile))
18711 (error nil))
18712 (if (not (file-exists-p pngfile))
18713 (if org-format-latex-signal-error
18714 (error "Failed to create png file from %s" texfile)
18715 (message "Failed to create png file from %s" texfile)
18716 nil)
18717 ;; Use the requested file name and clean up
18718 (copy-file pngfile tofile 'replace)
18719 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18720 (if (file-exists-p (concat texfilebase e))
18721 (delete-file (concat texfilebase e))))
18722 pngfile))))
18724 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18725 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18726 "This calls convert, which is included into imagemagick."
18727 (require 'ox-latex)
18728 (let* ((tmpdir (if (featurep 'xemacs)
18729 (temp-directory)
18730 temporary-file-directory))
18731 (texfilebase (make-temp-name
18732 (expand-file-name "orgtex" tmpdir)))
18733 (texfile (concat texfilebase ".tex"))
18734 (pdffile (concat texfilebase ".pdf"))
18735 (pngfile (concat texfilebase ".png"))
18736 (fnh (if (featurep 'xemacs)
18737 (font-height (face-font 'default))
18738 (face-attribute 'default :height nil)))
18739 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18740 (dpi (number-to-string (* scale (floor (if buffer fnh 120.)))))
18741 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18742 "black"))
18743 (bg (or (plist-get options (if buffer :background :html-background))
18744 "white")))
18745 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18746 (setq fg (org-latex-color-format fg)))
18747 (if (eq bg 'default) (setq bg (org-latex-color :background))
18748 (setq bg (org-latex-color-format
18749 (if (string= bg "Transparent") "white" bg))))
18750 (let ((latex-header (org-create-formula--latex-header)))
18751 (with-temp-file texfile
18752 (insert latex-header)
18753 (insert "\n\\begin{document}\n"
18754 "\\definecolor{fg}{rgb}{" fg "}\n"
18755 "\\definecolor{bg}{rgb}{" bg "}\n"
18756 "\n\\pagecolor{bg}\n"
18757 "\n{\\color{fg}\n"
18758 string
18759 "\n}\n"
18760 "\n\\end{document}\n")))
18761 (org-latex-compile texfile t)
18762 (if (not (file-exists-p pdffile))
18763 (progn (message "Failed to create pdf file from %s" texfile) nil)
18764 (condition-case nil
18765 (if (featurep 'xemacs)
18766 (call-process "convert" nil nil nil
18767 "-density" "96"
18768 "-trim"
18769 "-antialias"
18770 pdffile
18771 "-quality" "100"
18772 ;; "-sharpen" "0x1.0"
18773 pngfile)
18774 (call-process "convert" nil nil nil
18775 "-density" dpi
18776 "-trim"
18777 "-antialias"
18778 pdffile
18779 "-quality" "100"
18780 ;; "-sharpen" "0x1.0"
18781 pngfile))
18782 (error nil))
18783 (if (not (file-exists-p pngfile))
18784 (if org-format-latex-signal-error
18785 (error "Failed to create png file from %s" texfile)
18786 (message "Failed to create png file from %s" texfile)
18787 nil)
18788 ;; Use the requested file name and clean up
18789 (copy-file pngfile tofile 'replace)
18790 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18791 (if (file-exists-p (concat texfilebase e))
18792 (delete-file (concat texfilebase e))))
18793 pngfile))))
18795 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18796 "Fill a LaTeX header template TPL.
18797 In the template, the following place holders will be recognized:
18799 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18800 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18801 [PACKAGES] \\usepackage statements for PKG
18802 [NO-PACKAGES] do not include PKG
18803 [EXTRA] the string EXTRA
18804 [NO-EXTRA] do not include EXTRA
18806 For backward compatibility, if both the positive and the negative place
18807 holder is missing, the positive one (without the \"NO-\") will be
18808 assumed to be present at the end of the template.
18809 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18810 EXTRA is a string.
18811 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18812 (let (rpl (end ""))
18813 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18814 (setq rpl (if (or (match-end 1) (not def-pkg))
18815 "" (org-latex-packages-to-string def-pkg snippets-p t))
18816 tpl (replace-match rpl t t tpl))
18817 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18819 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18820 (setq rpl (if (or (match-end 1) (not pkg))
18821 "" (org-latex-packages-to-string pkg snippets-p t))
18822 tpl (replace-match rpl t t tpl))
18823 (if pkg (setq end
18824 (concat end "\n"
18825 (org-latex-packages-to-string pkg snippets-p)))))
18827 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18828 (setq rpl (if (or (match-end 1) (not extra))
18829 "" (concat extra "\n"))
18830 tpl (replace-match rpl t t tpl))
18831 (if (and extra (string-match "\\S-" extra))
18832 (setq end (concat end "\n" extra))))
18834 (if (string-match "\\S-" end)
18835 (concat tpl "\n" end)
18836 tpl)))
18838 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18839 "Turn an alist of packages into a string with the \\usepackage macros."
18840 (setq pkg (mapconcat (lambda(p)
18841 (cond
18842 ((stringp p) p)
18843 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18844 (format "%% Package %s omitted" (cadr p)))
18845 ((equal "" (car p))
18846 (format "\\usepackage{%s}" (cadr p)))
18848 (format "\\usepackage[%s]{%s}"
18849 (car p) (cadr p)))))
18851 "\n"))
18852 (if newline (concat pkg "\n") pkg))
18854 (defun org-dvipng-color (attr)
18855 "Return a RGB color specification for dvipng."
18856 (apply 'format "rgb %s %s %s"
18857 (mapcar 'org-normalize-color
18858 (if (featurep 'xemacs)
18859 (color-rgb-components
18860 (face-property 'default
18861 (cond ((eq attr :foreground) 'foreground)
18862 ((eq attr :background) 'background))))
18863 (color-values (face-attribute 'default attr nil))))))
18865 (defun org-dvipng-color-format (color-name)
18866 "Convert COLOR-NAME to a RGB color value for dvipng."
18867 (apply 'format "rgb %s %s %s"
18868 (mapcar 'org-normalize-color
18869 (color-values color-name))))
18871 (defun org-latex-color (attr)
18872 "Return a RGB color for the LaTeX color package."
18873 (apply 'format "%s,%s,%s"
18874 (mapcar 'org-normalize-color
18875 (if (featurep 'xemacs)
18876 (color-rgb-components
18877 (face-property 'default
18878 (cond ((eq attr :foreground) 'foreground)
18879 ((eq attr :background) 'background))))
18880 (color-values (face-attribute 'default attr nil))))))
18882 (defun org-latex-color-format (color-name)
18883 "Convert COLOR-NAME to a RGB color value."
18884 (apply 'format "%s,%s,%s"
18885 (mapcar 'org-normalize-color
18886 (color-values color-name))))
18888 (defun org-normalize-color (value)
18889 "Return string to be used as color value for an RGB component."
18890 (format "%g" (/ value 65535.0)))
18894 ;; Image display
18896 (defvar org-inline-image-overlays nil)
18897 (make-variable-buffer-local 'org-inline-image-overlays)
18899 (defun org-toggle-inline-images (&optional include-linked)
18900 "Toggle the display of inline images.
18901 INCLUDE-LINKED is passed to `org-display-inline-images'."
18902 (interactive "P")
18903 (if org-inline-image-overlays
18904 (progn
18905 (org-remove-inline-images)
18906 (message "Inline image display turned off"))
18907 (org-display-inline-images include-linked)
18908 (if (and (org-called-interactively-p)
18909 org-inline-image-overlays)
18910 (message "%d images displayed inline"
18911 (length org-inline-image-overlays))
18912 (message "No images to display inline"))))
18914 (defun org-redisplay-inline-images ()
18915 "Refresh the display of inline images."
18916 (interactive)
18917 (if (not org-inline-image-overlays)
18918 (org-toggle-inline-images)
18919 (org-toggle-inline-images)
18920 (org-toggle-inline-images)))
18922 (defun org-display-inline-images (&optional include-linked refresh beg end)
18923 "Display inline images.
18924 Normally only links without a description part are inlined, because this
18925 is how it will work for export. When INCLUDE-LINKED is set, also links
18926 with a description part will be inlined. This can be nice for a quick
18927 look at those images, but it does not reflect what exported files will look
18928 like.
18929 When REFRESH is set, refresh existing images between BEG and END.
18930 This will create new image displays only if necessary.
18931 BEG and END default to the buffer boundaries."
18932 (interactive "P")
18933 (when (display-graphic-p)
18934 (unless refresh
18935 (org-remove-inline-images)
18936 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18937 (save-excursion
18938 (save-restriction
18939 (widen)
18940 (setq beg (or beg (point-min)) end (or end (point-max)))
18941 (goto-char beg)
18942 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18943 (substring (org-image-file-name-regexp) 0 -2)
18944 "\\)\\]" (if include-linked "" "\\]")))
18945 (case-fold-search t)
18946 old file ov img type attrwidth width)
18947 (while (re-search-forward re end t)
18948 (setq old (get-char-property-and-overlay (match-beginning 1)
18949 'org-image-overlay)
18950 file (expand-file-name
18951 (concat (or (match-string 3) "") (match-string 4))))
18952 (when (image-type-available-p 'imagemagick)
18953 (setq attrwidth (if (or (listp org-image-actual-width)
18954 (null org-image-actual-width))
18955 (save-excursion
18956 (save-match-data
18957 (when (re-search-backward
18958 "#\\+attr.*:width[ \t]+\\([^ ]+\\)"
18959 (save-excursion
18960 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18961 (string-to-number (match-string 1))))))
18962 width (cond ((eq org-image-actual-width t) nil)
18963 ((null org-image-actual-width) attrwidth)
18964 ((numberp org-image-actual-width)
18965 org-image-actual-width)
18966 ((listp org-image-actual-width)
18967 (or attrwidth (car org-image-actual-width))))
18968 type (if width 'imagemagick)))
18969 (when (file-exists-p file)
18970 (if (and (car-safe old) refresh)
18971 (image-refresh (overlay-get (cdr old) 'display))
18972 (setq img (save-match-data (create-image file type nil :width width)))
18973 (when img
18974 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18975 (overlay-put ov 'display img)
18976 (overlay-put ov 'face 'default)
18977 (overlay-put ov 'org-image-overlay t)
18978 (overlay-put ov 'modification-hooks
18979 (list 'org-display-inline-remove-overlay))
18980 (push ov org-inline-image-overlays))))))))))
18982 (define-obsolete-function-alias
18983 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18985 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18986 "Remove inline-display overlay if a corresponding region is modified."
18987 (let ((inhibit-modification-hooks t))
18988 (when (and ov after)
18989 (delete ov org-inline-image-overlays)
18990 (delete-overlay ov))))
18992 (defun org-remove-inline-images ()
18993 "Remove inline display of images."
18994 (interactive)
18995 (mapc 'delete-overlay org-inline-image-overlays)
18996 (setq org-inline-image-overlays nil))
18998 ;;;; Key bindings
19000 ;; Outline functions from `outline-mode-prefix-map'
19001 ;; that can be remapped in Org:
19002 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19003 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
19004 (define-key org-mode-map [remap outline-forward-same-level]
19005 'org-forward-heading-same-level)
19006 (define-key org-mode-map [remap outline-backward-same-level]
19007 'org-backward-heading-same-level)
19008 (define-key org-mode-map [remap show-branches]
19009 'org-kill-note-or-show-branches)
19010 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19011 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19012 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19014 ;; Outline functions from `outline-mode-prefix-map' that can not
19015 ;; be remapped in Org:
19017 ;; - the column "key binding" shows whether the Outline function is still
19018 ;; available in Org mode on the same key that it has been bound to in
19019 ;; Outline mode:
19020 ;; - "overridden": key used for a different functionality in Org mode
19021 ;; - else: key still bound to the same Outline function in Org mode
19023 ;; | Outline function | key binding | Org replacement |
19024 ;; |------------------------------------+-------------+-----------------------|
19025 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
19026 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
19027 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19028 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19029 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19030 ;; | `show-entry' | overridden | no replacement |
19031 ;; | `show-children' | `C-c C-i' | visibility cycling |
19032 ;; | `show-branches' | `C-c C-k' | still same function |
19033 ;; | `show-subtree' | overridden | visibility cycling |
19034 ;; | `show-all' | overridden | no replacement |
19035 ;; | `hide-subtree' | overridden | visibility cycling |
19036 ;; | `hide-body' | overridden | no replacement |
19037 ;; | `hide-entry' | overridden | visibility cycling |
19038 ;; | `hide-leaves' | overridden | no replacement |
19039 ;; | `hide-sublevels' | overridden | no replacement |
19040 ;; | `hide-other' | overridden | no replacement |
19042 ;; Make `C-c C-x' a prefix key
19043 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19045 ;; TAB key with modifiers
19046 (org-defkey org-mode-map "\C-i" 'org-cycle)
19047 (org-defkey org-mode-map [(tab)] 'org-cycle)
19048 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19049 (org-defkey org-mode-map "\M-\t" 'pcomplete)
19050 ;; The following line is necessary under Suse GNU/Linux
19051 (unless (featurep 'xemacs)
19052 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
19053 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19054 (define-key org-mode-map [backtab] 'org-shifttab)
19056 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19057 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19058 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19060 ;; Cursor keys with modifiers
19061 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19062 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19063 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19064 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19066 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19067 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19068 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19069 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19071 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19072 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19073 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19074 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19076 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19077 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19078 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19079 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19081 ;; Babel keys
19082 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19083 (mapc (lambda (pair)
19084 (define-key org-babel-map (car pair) (cdr pair)))
19085 org-babel-key-bindings)
19087 ;;; Extra keys for tty access.
19088 ;; We only set them when really needed because otherwise the
19089 ;; menus don't show the simple keys
19091 (when (or org-use-extra-keys
19092 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19093 (not window-system))
19094 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19095 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19096 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19097 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19098 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19099 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19100 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19101 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19102 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19103 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19104 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19105 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19106 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19107 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19108 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19109 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19110 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19111 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19112 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19113 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19114 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19115 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19116 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
19117 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19118 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19119 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19120 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19121 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19123 ;; All the other keys
19125 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
19126 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19127 (if (boundp 'narrow-map)
19128 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19129 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19130 (if (boundp 'narrow-map)
19131 (org-defkey narrow-map "b" 'org-narrow-to-block)
19132 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19133 (if (boundp 'narrow-map)
19134 (org-defkey narrow-map "e" 'org-narrow-to-element)
19135 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19136 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19137 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19138 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19139 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19140 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19141 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19142 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19143 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19144 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19145 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19146 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
19147 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19148 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19149 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19150 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19151 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19152 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19153 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19154 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19155 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19156 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19157 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19158 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19159 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19160 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19161 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19162 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19163 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19164 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19165 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19166 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19167 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19168 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19169 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19170 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19171 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19172 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19173 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19174 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19175 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19176 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19177 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19178 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19179 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19180 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19181 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19182 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19183 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19184 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19185 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19186 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19187 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19188 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19189 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19190 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19191 (org-defkey org-mode-map "\C-c^" 'org-sort)
19192 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19193 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19194 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19195 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19196 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19197 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19198 (org-defkey org-mode-map "\C-m" 'org-return)
19199 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19200 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19201 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19202 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19203 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19204 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19205 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19206 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19207 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19208 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19209 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19210 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19211 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19212 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19213 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
19214 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19215 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19216 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19217 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19218 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19219 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19220 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19221 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19223 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19224 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19225 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19227 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19228 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19229 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19230 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19231 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19232 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19233 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19234 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19235 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19236 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19237 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
19238 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19239 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19240 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19241 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19242 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19243 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19244 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19245 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19246 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19247 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19248 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19249 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19251 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19252 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19253 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19254 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19255 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19257 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19259 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19261 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19262 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19264 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19267 (when (featurep 'xemacs)
19268 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19271 (defconst org-speed-commands-default
19273 ("Outline Navigation")
19274 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19275 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19276 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19277 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19278 ("F" . org-next-block)
19279 ("B" . org-previous-block)
19280 ("u" . (org-speed-move-safe 'outline-up-heading))
19281 ("j" . org-goto)
19282 ("g" . (org-refile t))
19283 ("Outline Visibility")
19284 ("c" . org-cycle)
19285 ("C" . org-shifttab)
19286 (" " . org-display-outline-path)
19287 ("s" . org-narrow-to-subtree)
19288 ("=" . org-columns)
19289 ("Outline Structure Editing")
19290 ("U" . org-shiftmetaup)
19291 ("D" . org-shiftmetadown)
19292 ("r" . org-metaright)
19293 ("l" . org-metaleft)
19294 ("R" . org-shiftmetaright)
19295 ("L" . org-shiftmetaleft)
19296 ("i" . (progn (forward-char 1) (call-interactively
19297 'org-insert-heading-respect-content)))
19298 ("^" . org-sort)
19299 ("w" . org-refile)
19300 ("a" . org-archive-subtree-default-with-confirmation)
19301 ("@" . org-mark-subtree)
19302 ("#" . org-toggle-comment)
19303 ("Clock Commands")
19304 ("I" . org-clock-in)
19305 ("O" . org-clock-out)
19306 ("Meta Data Editing")
19307 ("t" . org-todo)
19308 ("," . (org-priority))
19309 ("0" . (org-priority ?\ ))
19310 ("1" . (org-priority ?A))
19311 ("2" . (org-priority ?B))
19312 ("3" . (org-priority ?C))
19313 (":" . org-set-tags-command)
19314 ("e" . org-set-effort)
19315 ("E" . org-inc-effort)
19316 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19317 (org-entry-put (point) "APPT_WARNTIME" m)))
19318 ("Agenda Views etc")
19319 ("v" . org-agenda)
19320 ("/" . org-sparse-tree)
19321 ("Misc")
19322 ("o" . org-open-at-point)
19323 ("?" . org-speed-command-help)
19324 ("<" . (org-agenda-set-restriction-lock 'subtree))
19325 (">" . (org-agenda-remove-restriction-lock))
19327 "The default speed commands.")
19329 (defun org-print-speed-command (e)
19330 (if (> (length (car e)) 1)
19331 (progn
19332 (princ "\n")
19333 (princ (car e))
19334 (princ "\n")
19335 (princ (make-string (length (car e)) ?-))
19336 (princ "\n"))
19337 (princ (car e))
19338 (princ " ")
19339 (if (symbolp (cdr e))
19340 (princ (symbol-name (cdr e)))
19341 (prin1 (cdr e)))
19342 (princ "\n")))
19344 (defun org-speed-command-help ()
19345 "Show the available speed commands."
19346 (interactive)
19347 (if (not org-use-speed-commands)
19348 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19349 (with-output-to-temp-buffer "*Help*"
19350 (princ "User-defined Speed commands\n===========================\n")
19351 (mapc 'org-print-speed-command org-speed-commands-user)
19352 (princ "\n")
19353 (princ "Built-in Speed commands\n=======================\n")
19354 (mapc 'org-print-speed-command org-speed-commands-default))
19355 (with-current-buffer "*Help*"
19356 (setq truncate-lines t))))
19358 (defun org-speed-move-safe (cmd)
19359 "Execute CMD, but make sure that the cursor always ends up in a headline.
19360 If not, return to the original position and throw an error."
19361 (interactive)
19362 (let ((pos (point)))
19363 (call-interactively cmd)
19364 (unless (and (bolp) (org-at-heading-p))
19365 (goto-char pos)
19366 (error "Boundary reached while executing %s" cmd))))
19368 (defvar org-self-insert-command-undo-counter 0)
19370 (defvar org-table-auto-blank-field) ; defined in org-table.el
19371 (defvar org-speed-command nil)
19373 (define-obsolete-function-alias
19374 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19376 (defun org-speed-command-activate (keys)
19377 "Hook for activating single-letter speed commands.
19378 `org-speed-commands-default' specifies a minimal command set.
19379 Use `org-speed-commands-user' for further customization."
19380 (when (or (and (bolp) (looking-at org-outline-regexp))
19381 (and (functionp org-use-speed-commands)
19382 (funcall org-use-speed-commands)))
19383 (cdr (assoc keys (append org-speed-commands-user
19384 org-speed-commands-default)))))
19386 (define-obsolete-function-alias
19387 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19389 (defun org-babel-speed-command-activate (keys)
19390 "Hook for activating single-letter code block commands."
19391 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19392 (cdr (assoc keys org-babel-key-bindings))))
19394 (defcustom org-speed-command-hook
19395 '(org-speed-command-default-hook org-babel-speed-command-hook)
19396 "Hook for activating speed commands at strategic locations.
19397 Hook functions are called in sequence until a valid handler is
19398 found.
19400 Each hook takes a single argument, a user-pressed command key
19401 which is also a `self-insert-command' from the global map.
19403 Within the hook, examine the cursor position and the command key
19404 and return nil or a valid handler as appropriate. Handler could
19405 be one of an interactive command, a function, or a form.
19407 Set `org-use-speed-commands' to non-nil value to enable this
19408 hook. The default setting is `org-speed-command-activate'."
19409 :group 'org-structure
19410 :version "24.1"
19411 :type 'hook)
19413 (defun org-self-insert-command (N)
19414 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19415 If the cursor is in a table looking at whitespace, the whitespace is
19416 overwritten, and the table is not marked as requiring realignment."
19417 (interactive "p")
19418 (org-check-before-invisible-edit 'insert)
19419 (cond
19420 ((and org-use-speed-commands
19421 (setq org-speed-command
19422 (run-hook-with-args-until-success
19423 'org-speed-command-hook (this-command-keys))))
19424 (cond
19425 ((commandp org-speed-command)
19426 (setq this-command org-speed-command)
19427 (call-interactively org-speed-command))
19428 ((functionp org-speed-command)
19429 (funcall org-speed-command))
19430 ((and org-speed-command (listp org-speed-command))
19431 (eval org-speed-command))
19432 (t (let (org-use-speed-commands)
19433 (call-interactively 'org-self-insert-command)))))
19434 ((and
19435 (org-table-p)
19436 (progn
19437 ;; check if we blank the field, and if that triggers align
19438 (and (featurep 'org-table) org-table-auto-blank-field
19439 (member last-command
19440 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19441 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19442 ;; got extra space, this field does not determine column width
19443 (let (org-table-may-need-update) (org-table-blank-field))
19444 ;; no extra space, this field may determine column width
19445 (org-table-blank-field)))
19447 (eq N 1)
19448 (looking-at "[^|\n]* |"))
19449 (let (org-table-may-need-update)
19450 (goto-char (1- (match-end 0)))
19451 (backward-delete-char 1)
19452 (goto-char (match-beginning 0))
19453 (self-insert-command N)))
19455 (setq org-table-may-need-update t)
19456 (self-insert-command N)
19457 (org-fix-tags-on-the-fly)
19458 (if org-self-insert-cluster-for-undo
19459 (if (not (eq last-command 'org-self-insert-command))
19460 (setq org-self-insert-command-undo-counter 1)
19461 (if (>= org-self-insert-command-undo-counter 20)
19462 (setq org-self-insert-command-undo-counter 1)
19463 (and (> org-self-insert-command-undo-counter 0)
19464 buffer-undo-list (listp buffer-undo-list)
19465 (not (cadr buffer-undo-list)) ; remove nil entry
19466 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19467 (setq org-self-insert-command-undo-counter
19468 (1+ org-self-insert-command-undo-counter))))))))
19470 (defun org-check-before-invisible-edit (kind)
19471 "Check is editing if kind KIND would be dangerous with invisible text around.
19472 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19473 ;; First, try to get out of here as quickly as possible, to reduce overhead
19474 (if (and org-catch-invisible-edits
19475 (or (not (boundp 'visible-mode)) (not visible-mode))
19476 (or (get-char-property (point) 'invisible)
19477 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19478 ;; OK, we need to take a closer look
19479 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19480 (invisible-before-point (if (bobp) nil (get-char-property
19481 (1- (point)) 'invisible)))
19482 (border-and-ok-direction
19484 ;; Check if we are acting predictably before invisible text
19485 (and invisible-at-point (not invisible-before-point)
19486 (memq kind '(insert delete-backward)))
19487 ;; Check if we are acting predictably after invisible text
19488 ;; This works not well, and I have turned it off. It seems
19489 ;; better to always show and stop after invisible text.
19490 ;; (and (not invisible-at-point) invisible-before-point
19491 ;; (memq kind '(insert delete)))
19493 (when (or (memq invisible-at-point '(outline org-hide-block t))
19494 (memq invisible-before-point '(outline org-hide-block t)))
19495 (if (eq org-catch-invisible-edits 'error)
19496 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19497 (if (and org-custom-properties-overlays
19498 (y-or-n-p "Display invisible properties in this buffer? "))
19499 (org-toggle-custom-properties-visibility)
19500 ;; Make the area visible
19501 (save-excursion
19502 (if invisible-before-point
19503 (goto-char (previous-single-char-property-change
19504 (point) 'invisible)))
19505 (show-subtree))
19506 (cond
19507 ((eq org-catch-invisible-edits 'show)
19508 ;; That's it, we do the edit after showing
19509 (message
19510 "Unfolding invisible region around point before editing")
19511 (sit-for 1))
19512 ((and (eq org-catch-invisible-edits 'smart)
19513 border-and-ok-direction)
19514 (message "Unfolding invisible region around point before editing"))
19516 ;; Don't do the edit, make the user repeat it in full visibility
19517 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19519 (defun org-fix-tags-on-the-fly ()
19520 (when (and (equal (char-after (point-at-bol)) ?*)
19521 (org-at-heading-p))
19522 (org-align-tags-here org-tags-column)))
19524 (defun org-delete-backward-char (N)
19525 "Like `delete-backward-char', insert whitespace at field end in tables.
19526 When deleting backwards, in tables this function will insert whitespace in
19527 front of the next \"|\" separator, to keep the table aligned. The table will
19528 still be marked for re-alignment if the field did fill the entire column,
19529 because, in this case the deletion might narrow the column."
19530 (interactive "p")
19531 (save-match-data
19532 (org-check-before-invisible-edit 'delete-backward)
19533 (if (and (org-table-p)
19534 (eq N 1)
19535 (string-match "|" (buffer-substring (point-at-bol) (point)))
19536 (looking-at ".*?|"))
19537 (let ((pos (point))
19538 (noalign (looking-at "[^|\n\r]* |"))
19539 (c org-table-may-need-update))
19540 (backward-delete-char N)
19541 (if (not overwrite-mode)
19542 (progn
19543 (skip-chars-forward "^|")
19544 (insert " ")
19545 (goto-char (1- pos))))
19546 ;; noalign: if there were two spaces at the end, this field
19547 ;; does not determine the width of the column.
19548 (if noalign (setq org-table-may-need-update c)))
19549 (backward-delete-char N)
19550 (org-fix-tags-on-the-fly))))
19552 (defun org-delete-char (N)
19553 "Like `delete-char', but insert whitespace at field end in tables.
19554 When deleting characters, in tables this function will insert whitespace in
19555 front of the next \"|\" separator, to keep the table aligned. The table will
19556 still be marked for re-alignment if the field did fill the entire column,
19557 because, in this case the deletion might narrow the column."
19558 (interactive "p")
19559 (save-match-data
19560 (org-check-before-invisible-edit 'delete)
19561 (if (and (org-table-p)
19562 (not (bolp))
19563 (not (= (char-after) ?|))
19564 (eq N 1))
19565 (if (looking-at ".*?|")
19566 (let ((pos (point))
19567 (noalign (looking-at "[^|\n\r]* |"))
19568 (c org-table-may-need-update))
19569 (replace-match
19570 (concat (substring (match-string 0) 1 -1) " |") nil t)
19571 (goto-char pos)
19572 ;; noalign: if there were two spaces at the end, this field
19573 ;; does not determine the width of the column.
19574 (if noalign (setq org-table-may-need-update c)))
19575 (delete-char N))
19576 (delete-char N)
19577 (org-fix-tags-on-the-fly))))
19579 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19580 (put 'org-self-insert-command 'delete-selection
19581 (lambda ()
19582 (not (run-hook-with-args-until-success
19583 'self-insert-uses-region-functions))))
19584 (put 'orgtbl-self-insert-command 'delete-selection
19585 (lambda ()
19586 (not (run-hook-with-args-until-success
19587 'self-insert-uses-region-functions))))
19588 (put 'org-delete-char 'delete-selection 'supersede)
19589 (put 'org-delete-backward-char 'delete-selection 'supersede)
19590 (put 'org-yank 'delete-selection 'yank)
19592 ;; Make `flyspell-mode' delay after some commands
19593 (put 'org-self-insert-command 'flyspell-delayed t)
19594 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19595 (put 'org-delete-char 'flyspell-delayed t)
19596 (put 'org-delete-backward-char 'flyspell-delayed t)
19598 ;; Make pabbrev-mode expand after org-mode commands
19599 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19600 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19602 (defun org-remap (map &rest commands)
19603 "In MAP, remap the functions given in COMMANDS.
19604 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19605 (let (new old)
19606 (while commands
19607 (setq old (pop commands) new (pop commands))
19608 (if (fboundp 'command-remapping)
19609 (org-defkey map (vector 'remap old) new)
19610 (substitute-key-definition old new map global-map)))))
19612 (defun org-transpose-words ()
19613 "Transpose words for Org.
19614 This uses the `org-mode-transpose-word-syntax-table' syntax
19615 table, which interprets characters in `org-emphasis-alist' as
19616 word constituents."
19617 (interactive)
19618 (with-syntax-table org-mode-transpose-word-syntax-table
19619 (call-interactively 'transpose-words)))
19620 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19622 (when (eq org-enable-table-editor 'optimized)
19623 ;; If the user wants maximum table support, we need to hijack
19624 ;; some standard editing functions
19625 (org-remap org-mode-map
19626 'self-insert-command 'org-self-insert-command
19627 'delete-char 'org-delete-char
19628 'delete-backward-char 'org-delete-backward-char)
19629 (org-defkey org-mode-map "|" 'org-force-self-insert))
19631 (defvar org-ctrl-c-ctrl-c-hook nil
19632 "Hook for functions attaching themselves to `C-c C-c'.
19634 This can be used to add additional functionality to the C-c C-c
19635 key which executes context-dependent commands. This hook is run
19636 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19637 run after the last test.
19639 Each function will be called with no arguments. The function
19640 must check if the context is appropriate for it to act. If yes,
19641 it should do its thing and then return a non-nil value. If the
19642 context is wrong, just do nothing and return nil.")
19644 (defvar org-ctrl-c-ctrl-c-final-hook nil
19645 "Hook for functions attaching themselves to `C-c C-c'.
19647 This can be used to add additional functionality to the C-c C-c
19648 key which executes context-dependent commands. This hook is run
19649 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19650 before the first test.
19652 Each function will be called with no arguments. The function
19653 must check if the context is appropriate for it to act. If yes,
19654 it should do its thing and then return a non-nil value. If the
19655 context is wrong, just do nothing and return nil.")
19657 (defvar org-tab-first-hook nil
19658 "Hook for functions to attach themselves to TAB.
19659 See `org-ctrl-c-ctrl-c-hook' for more information.
19660 This hook runs as the first action when TAB is pressed, even before
19661 `org-cycle' messes around with the `outline-regexp' to cater for
19662 inline tasks and plain list item folding.
19663 If any function in this hook returns t, any other actions that
19664 would have been caused by TAB (such as table field motion or visibility
19665 cycling) will not occur.")
19667 (defvar org-tab-after-check-for-table-hook nil
19668 "Hook for functions to attach themselves to TAB.
19669 See `org-ctrl-c-ctrl-c-hook' for more information.
19670 This hook runs after it has been established that the cursor is not in a
19671 table, but before checking if the cursor is in a headline or if global cycling
19672 should be done.
19673 If any function in this hook returns t, not other actions like visibility
19674 cycling will be done.")
19676 (defvar org-tab-after-check-for-cycling-hook nil
19677 "Hook for functions to attach themselves to TAB.
19678 See `org-ctrl-c-ctrl-c-hook' for more information.
19679 This hook runs after it has been established that not table field motion and
19680 not visibility should be done because of current context. This is probably
19681 the place where a package like yasnippets can hook in.")
19683 (defvar org-tab-before-tab-emulation-hook nil
19684 "Hook for functions to attach themselves to TAB.
19685 See `org-ctrl-c-ctrl-c-hook' for more information.
19686 This hook runs after every other options for TAB have been exhausted, but
19687 before indentation and \t insertion takes place.")
19689 (defvar org-metaleft-hook nil
19690 "Hook for functions attaching themselves to `M-left'.
19691 See `org-ctrl-c-ctrl-c-hook' for more information.")
19692 (defvar org-metaright-hook nil
19693 "Hook for functions attaching themselves to `M-right'.
19694 See `org-ctrl-c-ctrl-c-hook' for more information.")
19695 (defvar org-metaup-hook nil
19696 "Hook for functions attaching themselves to `M-up'.
19697 See `org-ctrl-c-ctrl-c-hook' for more information.")
19698 (defvar org-metadown-hook nil
19699 "Hook for functions attaching themselves to `M-down'.
19700 See `org-ctrl-c-ctrl-c-hook' for more information.")
19701 (defvar org-shiftmetaleft-hook nil
19702 "Hook for functions attaching themselves to `M-S-left'.
19703 See `org-ctrl-c-ctrl-c-hook' for more information.")
19704 (defvar org-shiftmetaright-hook nil
19705 "Hook for functions attaching themselves to `M-S-right'.
19706 See `org-ctrl-c-ctrl-c-hook' for more information.")
19707 (defvar org-shiftmetaup-hook nil
19708 "Hook for functions attaching themselves to `M-S-up'.
19709 See `org-ctrl-c-ctrl-c-hook' for more information.")
19710 (defvar org-shiftmetadown-hook nil
19711 "Hook for functions attaching themselves to `M-S-down'.
19712 See `org-ctrl-c-ctrl-c-hook' for more information.")
19713 (defvar org-metareturn-hook nil
19714 "Hook for functions attaching themselves to `M-RET'.
19715 See `org-ctrl-c-ctrl-c-hook' for more information.")
19716 (defvar org-shiftup-hook nil
19717 "Hook for functions attaching themselves to `S-up'.
19718 See `org-ctrl-c-ctrl-c-hook' for more information.")
19719 (defvar org-shiftup-final-hook nil
19720 "Hook for functions attaching themselves to `S-up'.
19721 This one runs after all other options except shift-select have been excluded.
19722 See `org-ctrl-c-ctrl-c-hook' for more information.")
19723 (defvar org-shiftdown-hook nil
19724 "Hook for functions attaching themselves to `S-down'.
19725 See `org-ctrl-c-ctrl-c-hook' for more information.")
19726 (defvar org-shiftdown-final-hook nil
19727 "Hook for functions attaching themselves to `S-down'.
19728 This one runs after all other options except shift-select have been excluded.
19729 See `org-ctrl-c-ctrl-c-hook' for more information.")
19730 (defvar org-shiftleft-hook nil
19731 "Hook for functions attaching themselves to `S-left'.
19732 See `org-ctrl-c-ctrl-c-hook' for more information.")
19733 (defvar org-shiftleft-final-hook nil
19734 "Hook for functions attaching themselves to `S-left'.
19735 This one runs after all other options except shift-select have been excluded.
19736 See `org-ctrl-c-ctrl-c-hook' for more information.")
19737 (defvar org-shiftright-hook nil
19738 "Hook for functions attaching themselves to `S-right'.
19739 See `org-ctrl-c-ctrl-c-hook' for more information.")
19740 (defvar org-shiftright-final-hook nil
19741 "Hook for functions attaching themselves to `S-right'.
19742 This one runs after all other options except shift-select have been excluded.
19743 See `org-ctrl-c-ctrl-c-hook' for more information.")
19745 (defun org-modifier-cursor-error ()
19746 "Throw an error, a modified cursor command was applied in wrong context."
19747 (user-error "This command is active in special context like tables, headlines or items"))
19749 (defun org-shiftselect-error ()
19750 "Throw an error because Shift-Cursor command was applied in wrong context."
19751 (if (and (boundp 'shift-select-mode) shift-select-mode)
19752 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19753 (user-error "This command works only in special context like headlines or timestamps")))
19755 (defun org-call-for-shift-select (cmd)
19756 (let ((this-command-keys-shift-translated t))
19757 (call-interactively cmd)))
19759 (defun org-shifttab (&optional arg)
19760 "Global visibility cycling or move to previous table field.
19761 Call `org-table-previous-field' within a table.
19762 When ARG is nil, cycle globally through visibility states.
19763 When ARG is a numeric prefix, show contents of this level."
19764 (interactive "P")
19765 (cond
19766 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19767 ((integerp arg)
19768 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19769 (message "Content view to level: %d" arg)
19770 (org-content (prefix-numeric-value arg2))
19771 (org-cycle-show-empty-lines t)
19772 (setq org-cycle-global-status 'overview)))
19773 (t (call-interactively 'org-global-cycle))))
19775 (defun org-shiftmetaleft ()
19776 "Promote subtree or delete table column.
19777 Calls `org-promote-subtree', `org-outdent-item-tree', or
19778 `org-table-delete-column', depending on context. See the
19779 individual commands for more information."
19780 (interactive)
19781 (cond
19782 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19783 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19784 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19785 ((if (not (org-region-active-p)) (org-at-item-p)
19786 (save-excursion (goto-char (region-beginning))
19787 (org-at-item-p)))
19788 (call-interactively 'org-outdent-item-tree))
19789 (t (org-modifier-cursor-error))))
19791 (defun org-shiftmetaright ()
19792 "Demote subtree or insert table column.
19793 Calls `org-demote-subtree', `org-indent-item-tree', or
19794 `org-table-insert-column', depending on context. See the
19795 individual commands for more information."
19796 (interactive)
19797 (cond
19798 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19799 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19800 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19801 ((if (not (org-region-active-p)) (org-at-item-p)
19802 (save-excursion (goto-char (region-beginning))
19803 (org-at-item-p)))
19804 (call-interactively 'org-indent-item-tree))
19805 (t (org-modifier-cursor-error))))
19807 (defun org-shiftmetaup (&optional arg)
19808 "Move subtree up or kill table row.
19809 Calls `org-move-subtree-up' or `org-table-kill-row' or
19810 `org-move-item-up' or `org-timestamp-up', depending on context.
19811 See the individual commands for more information."
19812 (interactive "P")
19813 (cond
19814 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19815 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19816 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19817 ((org-at-item-p) (call-interactively 'org-move-item-up))
19818 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19819 (call-interactively 'org-timestamp-up)))
19820 (t (call-interactively 'org-drag-line-backward))))
19822 (defun org-shiftmetadown (&optional arg)
19823 "Move subtree down or insert table row.
19824 Calls `org-move-subtree-down' or `org-table-insert-row' or
19825 `org-move-item-down' or `org-timestamp-up', depending on context.
19826 See the individual commands for more information."
19827 (interactive "P")
19828 (cond
19829 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19830 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19831 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19832 ((org-at-item-p) (call-interactively 'org-move-item-down))
19833 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19834 (call-interactively 'org-timestamp-down)))
19835 (t (call-interactively 'org-drag-line-forward))))
19837 (defsubst org-hidden-tree-error ()
19838 (user-error
19839 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19841 (defun org-metaleft (&optional arg)
19842 "Promote heading or move table column to left.
19843 Calls `org-do-promote' or `org-table-move-column', depending on context.
19844 With no specific context, calls the Emacs default `backward-word'.
19845 See the individual commands for more information."
19846 (interactive "P")
19847 (cond
19848 ((run-hook-with-args-until-success 'org-metaleft-hook))
19849 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19850 ((org-with-limited-levels
19851 (or (org-at-heading-p)
19852 (and (org-region-active-p)
19853 (save-excursion
19854 (goto-char (region-beginning))
19855 (org-at-heading-p)))))
19856 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19857 (call-interactively 'org-do-promote))
19858 ;; At an inline task.
19859 ((org-at-heading-p)
19860 (call-interactively 'org-inlinetask-promote))
19861 ((or (org-at-item-p)
19862 (and (org-region-active-p)
19863 (save-excursion
19864 (goto-char (region-beginning))
19865 (org-at-item-p))))
19866 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19867 (call-interactively 'org-outdent-item))
19868 (t (call-interactively 'backward-word))))
19870 (defun org-metaright (&optional arg)
19871 "Demote a subtree, a list item or move table column to right.
19872 In front of a drawer or a block keyword, indent it correctly.
19873 With no specific context, calls the Emacs default `forward-word'.
19874 See the individual commands for more information."
19875 (interactive "P")
19876 (cond
19877 ((run-hook-with-args-until-success 'org-metaright-hook))
19878 ((org-at-table-p) (call-interactively 'org-table-move-column))
19879 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19880 ((org-at-block-p) (call-interactively 'org-indent-block))
19881 ((org-with-limited-levels
19882 (or (org-at-heading-p)
19883 (and (org-region-active-p)
19884 (save-excursion
19885 (goto-char (region-beginning))
19886 (org-at-heading-p)))))
19887 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19888 (call-interactively 'org-do-demote))
19889 ;; At an inline task.
19890 ((org-at-heading-p)
19891 (call-interactively 'org-inlinetask-demote))
19892 ((or (org-at-item-p)
19893 (and (org-region-active-p)
19894 (save-excursion
19895 (goto-char (region-beginning))
19896 (org-at-item-p))))
19897 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19898 (call-interactively 'org-indent-item))
19899 (t (call-interactively 'forward-word))))
19901 (defun org-check-for-hidden (what)
19902 "Check if there are hidden headlines/items in the current visual line.
19903 WHAT can be either `headlines' or `items'. If the current line is
19904 an outline or item heading and it has a folded subtree below it,
19905 this function returns t, nil otherwise."
19906 (let ((re (cond
19907 ((eq what 'headlines) org-outline-regexp-bol)
19908 ((eq what 'items) (org-item-beginning-re))
19909 (t (error "This should not happen"))))
19910 beg end)
19911 (save-excursion
19912 (catch 'exit
19913 (unless (org-region-active-p)
19914 (setq beg (point-at-bol))
19915 (beginning-of-line 2)
19916 (while (and (not (eobp)) ;; this is like `next-line'
19917 (get-char-property (1- (point)) 'invisible))
19918 (beginning-of-line 2))
19919 (setq end (point))
19920 (goto-char beg)
19921 (goto-char (point-at-eol))
19922 (setq end (max end (point)))
19923 (while (re-search-forward re end t)
19924 (if (get-char-property (match-beginning 0) 'invisible)
19925 (throw 'exit t))))
19926 nil))))
19928 (defun org-metaup (&optional arg)
19929 "Move subtree up or move table row up.
19930 Calls `org-move-subtree-up' or `org-table-move-row' or
19931 `org-move-item-up', depending on context. See the individual commands
19932 for more information."
19933 (interactive "P")
19934 (cond
19935 ((run-hook-with-args-until-success 'org-metaup-hook))
19936 ((org-region-active-p)
19937 (let* ((a (min (region-beginning) (region-end)))
19938 (b (1- (max (region-beginning) (region-end))))
19939 (c (save-excursion (goto-char a)
19940 (move-beginning-of-line 0)))
19941 (d (save-excursion (goto-char a)
19942 (move-end-of-line 0) (point))))
19943 (transpose-regions a b c d)
19944 (goto-char c)))
19945 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19946 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19947 ((org-at-item-p) (call-interactively 'org-move-item-up))
19948 (t (org-drag-element-backward))))
19950 (defun org-metadown (&optional arg)
19951 "Move subtree down or move table row down.
19952 Calls `org-move-subtree-down' or `org-table-move-row' or
19953 `org-move-item-down', depending on context. See the individual
19954 commands for more information."
19955 (interactive "P")
19956 (cond
19957 ((run-hook-with-args-until-success 'org-metadown-hook))
19958 ((org-region-active-p)
19959 (let* ((a (min (region-beginning) (region-end)))
19960 (b (max (region-beginning) (region-end)))
19961 (c (save-excursion (goto-char b)
19962 (move-beginning-of-line 1)))
19963 (d (save-excursion (goto-char b)
19964 (move-end-of-line 1) (1+ (point)))))
19965 (transpose-regions a b c d)
19966 (goto-char d)))
19967 ((org-at-table-p) (call-interactively 'org-table-move-row))
19968 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19969 ((org-at-item-p) (call-interactively 'org-move-item-down))
19970 (t (org-drag-element-forward))))
19972 (defun org-shiftup (&optional arg)
19973 "Increase item in timestamp or increase priority of current headline.
19974 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19975 depending on context. See the individual commands for more information."
19976 (interactive "P")
19977 (cond
19978 ((run-hook-with-args-until-success 'org-shiftup-hook))
19979 ((and org-support-shift-select (org-region-active-p))
19980 (org-call-for-shift-select 'previous-line))
19981 ((org-at-timestamp-p t)
19982 (call-interactively (if org-edit-timestamp-down-means-later
19983 'org-timestamp-down 'org-timestamp-up)))
19984 ((and (not (eq org-support-shift-select 'always))
19985 org-enable-priority-commands
19986 (org-at-heading-p))
19987 (call-interactively 'org-priority-up))
19988 ((and (not org-support-shift-select) (org-at-item-p))
19989 (call-interactively 'org-previous-item))
19990 ((org-clocktable-try-shift 'up arg))
19991 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19992 (org-support-shift-select
19993 (org-call-for-shift-select 'previous-line))
19994 (t (org-shiftselect-error))))
19996 (defun org-shiftdown (&optional arg)
19997 "Decrease item in timestamp or decrease priority of current headline.
19998 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19999 depending on context. See the individual commands for more information."
20000 (interactive "P")
20001 (cond
20002 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20003 ((and org-support-shift-select (org-region-active-p))
20004 (org-call-for-shift-select 'next-line))
20005 ((org-at-timestamp-p t)
20006 (call-interactively (if org-edit-timestamp-down-means-later
20007 'org-timestamp-up 'org-timestamp-down)))
20008 ((and (not (eq org-support-shift-select 'always))
20009 org-enable-priority-commands
20010 (org-at-heading-p))
20011 (call-interactively 'org-priority-down))
20012 ((and (not org-support-shift-select) (org-at-item-p))
20013 (call-interactively 'org-next-item))
20014 ((org-clocktable-try-shift 'down arg))
20015 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20016 (org-support-shift-select
20017 (org-call-for-shift-select 'next-line))
20018 (t (org-shiftselect-error))))
20020 (defun org-shiftright (&optional arg)
20021 "Cycle the thing at point or in the current line, depending on context.
20022 Depending on context, this does one of the following:
20024 - switch a timestamp at point one day into the future
20025 - on a headline, switch to the next TODO keyword.
20026 - on an item, switch entire list to the next bullet type
20027 - on a property line, switch to the next allowed value
20028 - on a clocktable definition line, move time block into the future"
20029 (interactive "P")
20030 (cond
20031 ((run-hook-with-args-until-success 'org-shiftright-hook))
20032 ((and org-support-shift-select (org-region-active-p))
20033 (org-call-for-shift-select 'forward-char))
20034 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20035 ((and (not (eq org-support-shift-select 'always))
20036 (org-at-heading-p))
20037 (let ((org-inhibit-logging
20038 (not org-treat-S-cursor-todo-selection-as-state-change))
20039 (org-inhibit-blocking
20040 (not org-treat-S-cursor-todo-selection-as-state-change)))
20041 (org-call-with-arg 'org-todo 'right)))
20042 ((or (and org-support-shift-select
20043 (not (eq org-support-shift-select 'always))
20044 (org-at-item-bullet-p))
20045 (and (not org-support-shift-select) (org-at-item-p)))
20046 (org-call-with-arg 'org-cycle-list-bullet nil))
20047 ((and (not (eq org-support-shift-select 'always))
20048 (org-at-property-p))
20049 (call-interactively 'org-property-next-allowed-value))
20050 ((org-clocktable-try-shift 'right arg))
20051 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20052 (org-support-shift-select
20053 (org-call-for-shift-select 'forward-char))
20054 (t (org-shiftselect-error))))
20056 (defun org-shiftleft (&optional arg)
20057 "Cycle the thing at point or in the current line, depending on context.
20058 Depending on context, this does one of the following:
20060 - switch a timestamp at point one day into the past
20061 - on a headline, switch to the previous TODO keyword.
20062 - on an item, switch entire list to the previous bullet type
20063 - on a property line, switch to the previous allowed value
20064 - on a clocktable definition line, move time block into the past"
20065 (interactive "P")
20066 (cond
20067 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20068 ((and org-support-shift-select (org-region-active-p))
20069 (org-call-for-shift-select 'backward-char))
20070 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20071 ((and (not (eq org-support-shift-select 'always))
20072 (org-at-heading-p))
20073 (let ((org-inhibit-logging
20074 (not org-treat-S-cursor-todo-selection-as-state-change))
20075 (org-inhibit-blocking
20076 (not org-treat-S-cursor-todo-selection-as-state-change)))
20077 (org-call-with-arg 'org-todo 'left)))
20078 ((or (and org-support-shift-select
20079 (not (eq org-support-shift-select 'always))
20080 (org-at-item-bullet-p))
20081 (and (not org-support-shift-select) (org-at-item-p)))
20082 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20083 ((and (not (eq org-support-shift-select 'always))
20084 (org-at-property-p))
20085 (call-interactively 'org-property-previous-allowed-value))
20086 ((org-clocktable-try-shift 'left arg))
20087 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20088 (org-support-shift-select
20089 (org-call-for-shift-select 'backward-char))
20090 (t (org-shiftselect-error))))
20092 (defun org-shiftcontrolright ()
20093 "Switch to next TODO set."
20094 (interactive)
20095 (cond
20096 ((and org-support-shift-select (org-region-active-p))
20097 (org-call-for-shift-select 'forward-word))
20098 ((and (not (eq org-support-shift-select 'always))
20099 (org-at-heading-p))
20100 (org-call-with-arg 'org-todo 'nextset))
20101 (org-support-shift-select
20102 (org-call-for-shift-select 'forward-word))
20103 (t (org-shiftselect-error))))
20105 (defun org-shiftcontrolleft ()
20106 "Switch to previous TODO set."
20107 (interactive)
20108 (cond
20109 ((and org-support-shift-select (org-region-active-p))
20110 (org-call-for-shift-select 'backward-word))
20111 ((and (not (eq org-support-shift-select 'always))
20112 (org-at-heading-p))
20113 (org-call-with-arg 'org-todo 'previousset))
20114 (org-support-shift-select
20115 (org-call-for-shift-select 'backward-word))
20116 (t (org-shiftselect-error))))
20118 (defun org-shiftcontrolup (&optional n)
20119 "Change timestamps synchronously up in CLOCK log lines.
20120 Optional argument N tells to change by that many units."
20121 (interactive "P")
20122 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20123 (let (org-support-shift-select)
20124 (org-clock-timestamps-up n))
20125 (user-error "Not at a clock log")))
20127 (defun org-shiftcontroldown (&optional n)
20128 "Change timestamps synchronously down in CLOCK log lines.
20129 Optional argument N tells to change by that many units."
20130 (interactive "P")
20131 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20132 (let (org-support-shift-select)
20133 (org-clock-timestamps-down n))
20134 (user-error "Not at a clock log")))
20136 (defun org-ctrl-c-ret ()
20137 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20138 (interactive)
20139 (cond
20140 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20141 (t (call-interactively 'org-insert-heading))))
20143 (defun org-find-visible ()
20144 (let ((s (point)))
20145 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20146 (get-char-property s 'invisible)))
20148 (defun org-find-invisible ()
20149 (let ((s (point)))
20150 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20151 (not (get-char-property s 'invisible))))
20154 (defun org-copy-visible (beg end)
20155 "Copy the visible parts of the region."
20156 (interactive "r")
20157 (let (snippets s)
20158 (save-excursion
20159 (save-restriction
20160 (narrow-to-region beg end)
20161 (setq s (goto-char (point-min)))
20162 (while (not (= (point) (point-max)))
20163 (goto-char (org-find-invisible))
20164 (push (buffer-substring s (point)) snippets)
20165 (setq s (goto-char (org-find-visible))))))
20166 (kill-new (apply 'concat (nreverse snippets)))))
20168 (defun org-copy-special ()
20169 "Copy region in table or copy current subtree.
20170 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20171 See the individual commands for more information."
20172 (interactive)
20173 (call-interactively
20174 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20176 (defun org-cut-special ()
20177 "Cut region in table or cut current subtree.
20178 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20179 See the individual commands for more information."
20180 (interactive)
20181 (call-interactively
20182 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20184 (defun org-paste-special (arg)
20185 "Paste rectangular region into table, or past subtree relative to level.
20186 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20187 See the individual commands for more information."
20188 (interactive "P")
20189 (if (org-at-table-p)
20190 (org-table-paste-rectangle)
20191 (org-paste-subtree arg)))
20193 (defsubst org-in-fixed-width-region-p ()
20194 "Is point in a fixed-width region?"
20195 (save-match-data
20196 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20198 (defun org-edit-special (&optional arg)
20199 "Call a special editor for the element at point.
20200 When at a table, call the formula editor with `org-table-edit-formulas'.
20201 When in a source code block, call `org-edit-src-code'.
20202 When in a fixed-width region, call `org-edit-fixed-width-region'.
20203 When at an #+INCLUDE keyword, visit the included file.
20204 On a link, call `ffap' to visit the link at point.
20205 Otherwise, return a user error."
20206 (interactive "P")
20207 (let ((element (org-element-at-point)))
20208 (assert (not buffer-read-only) nil
20209 "Buffer is read-only: %s" (buffer-name))
20210 (case (org-element-type element)
20211 (src-block
20212 (if (not arg) (org-edit-src-code)
20213 (let* ((info (org-babel-get-src-block-info))
20214 (lang (nth 0 info))
20215 (params (nth 2 info))
20216 (session (cdr (assq :session params))))
20217 (if (not session) (org-edit-src-code)
20218 ;; At a src-block with a session and function called with
20219 ;; an ARG: switch to the buffer related to the inferior
20220 ;; process.
20221 (switch-to-buffer
20222 (funcall (intern (concat "org-babel-prep-session:" lang))
20223 session params))))))
20224 (keyword
20225 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20226 (find-file
20227 (org-remove-double-quotes
20228 (car (org-split-string (org-element-property :value element)))))
20229 (user-error "No special environment to edit here")))
20230 (table
20231 (if (eq (org-element-property :type element) 'table.el)
20232 (org-edit-src-code)
20233 (call-interactively 'org-table-edit-formulas)))
20234 ;; Only Org tables contain `table-row' type elements.
20235 (table-row (call-interactively 'org-table-edit-formulas))
20236 ((example-block export-block) (org-edit-src-code))
20237 (fixed-width (org-edit-fixed-width-region))
20238 (otherwise
20239 ;; No notable element at point. Though, we may be at a link,
20240 ;; which is an object. Thus, scan deeper.
20241 (if (eq (org-element-type (org-element-context element)) 'link)
20242 (call-interactively 'ffap)
20243 (user-error "No special environment to edit here"))))))
20245 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20246 (defun org-ctrl-c-ctrl-c (&optional arg)
20247 "Set tags in headline, or update according to changed information at point.
20249 This command does many different things, depending on context:
20251 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20252 this is what we do.
20254 - If the cursor is on a statistics cookie, update it.
20256 - If the cursor is in a headline, prompt for tags and insert them
20257 into the current line, aligned to `org-tags-column'. When called
20258 with prefix arg, realign all tags in the current buffer.
20260 - If the cursor is in one of the special #+KEYWORD lines, this
20261 triggers scanning the buffer for these lines and updating the
20262 information.
20264 - If the cursor is inside a table, realign the table. This command
20265 works even if the automatic table editor has been turned off.
20267 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20268 the entire table.
20270 - If the cursor is at a footnote reference or definition, jump to
20271 the corresponding definition or references, respectively.
20273 - If the cursor is a the beginning of a dynamic block, update it.
20275 - If the current buffer is a capture buffer, close note and file it.
20277 - If the cursor is on a <<<target>>>, update radio targets and
20278 corresponding links in this buffer.
20280 - If the cursor is on a numbered item in a plain list, renumber the
20281 ordered list.
20283 - If the cursor is on a checkbox, toggle it.
20285 - If the cursor is on a code block, evaluate it. The variable
20286 `org-confirm-babel-evaluate' can be used to control prompting
20287 before code block evaluation, by default every code block
20288 evaluation requires confirmation. Code block evaluation can be
20289 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20290 (interactive "P")
20291 (cond
20292 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20293 org-occur-highlights
20294 org-latex-fragment-image-overlays)
20295 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20296 (org-remove-occur-highlights)
20297 (org-remove-latex-fragment-image-overlays)
20298 (message "Temporary highlights/overlays removed from current buffer"))
20299 ((and (local-variable-p 'org-finish-function (current-buffer))
20300 (fboundp org-finish-function))
20301 (funcall org-finish-function))
20302 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20304 (let* ((context (org-element-context)) (type (org-element-type context)))
20305 ;; Test if point is within a blank line.
20306 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20307 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20308 (user-error "C-c C-c can do nothing useful at this location"))
20309 (case type
20310 ;; When at a link, act according to the parent instead.
20311 (link (setq context (org-element-property :parent context))
20312 (setq type (org-element-type context)))
20313 ;; Unsupported object types: refer to the first supported
20314 ;; element or object containing it.
20315 ((bold code entity export-snippet inline-babel-call inline-src-block
20316 italic latex-fragment line-break macro strike-through subscript
20317 superscript underline verbatim)
20318 (while (and (setq context (org-element-property :parent context))
20319 (not (memq (setq type (org-element-type context))
20320 '(radio-target paragraph verse-block
20321 table-cell)))))))
20322 ;; For convenience: at the first line of a paragraph on the
20323 ;; same line as an item, apply function on that item instead.
20324 (when (eq type 'paragraph)
20325 (let ((parent (org-element-property :parent context)))
20326 (when (and (eq (org-element-type parent) 'item)
20327 (= (point-at-bol) (org-element-property :begin parent)))
20328 (setq context parent type 'item))))
20329 ;; Act according to type of element or object at point.
20330 (case type
20331 (clock (org-clock-update-time-maybe))
20332 (dynamic-block
20333 (save-excursion
20334 (goto-char (org-element-property :post-affiliated context))
20335 (org-update-dblock)))
20336 (footnote-definition
20337 (goto-char (org-element-property :post-affiliated context))
20338 (call-interactively 'org-footnote-action))
20339 (footnote-reference (call-interactively 'org-footnote-action))
20340 ((headline inlinetask)
20341 (save-excursion (goto-char (org-element-property :begin context))
20342 (call-interactively 'org-set-tags)))
20343 (item
20344 ;; At an item: a double C-u set checkbox to "[-]"
20345 ;; unconditionally, whereas a single one will toggle its
20346 ;; presence. Without an universal argument, if the item
20347 ;; has a checkbox, toggle it. Otherwise repair the list.
20348 (let* ((box (org-element-property :checkbox context))
20349 (struct (org-element-property :structure context))
20350 (old-struct (copy-tree struct))
20351 (parents (org-list-parents-alist struct))
20352 (prevs (org-list-prevs-alist struct))
20353 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20354 (org-list-set-checkbox
20355 (org-element-property :begin context) struct
20356 (cond ((equal arg '(16)) "[-]")
20357 ((and (not box) (equal arg '(4))) "[ ]")
20358 ((or (not box) (equal arg '(4))) nil)
20359 ((eq box 'on) "[ ]")
20360 (t "[X]")))
20361 ;; Mimic `org-list-write-struct' but with grabbing
20362 ;; a return value from `org-list-struct-fix-box'.
20363 (org-list-struct-fix-ind struct parents 2)
20364 (org-list-struct-fix-item-end struct)
20365 (org-list-struct-fix-bul struct prevs)
20366 (org-list-struct-fix-ind struct parents)
20367 (let ((block-item
20368 (org-list-struct-fix-box struct parents prevs orderedp)))
20369 (if (and box (equal struct old-struct))
20370 (if (equal arg '(16))
20371 (message "Checkboxes already reset")
20372 (user-error "Cannot toggle this checkbox: %s"
20373 (if (eq box 'on)
20374 "all subitems checked"
20375 "unchecked subitems")))
20376 (org-list-struct-apply-struct struct old-struct)
20377 (org-update-checkbox-count-maybe))
20378 (when block-item
20379 (message "Checkboxes were removed due to empty box at line %d"
20380 (org-current-line block-item))))))
20381 (keyword
20382 (let ((org-inhibit-startup-visibility-stuff t)
20383 (org-startup-align-all-tables nil))
20384 (when (boundp 'org-table-coordinate-overlays)
20385 (mapc 'delete-overlay org-table-coordinate-overlays)
20386 (setq org-table-coordinate-overlays nil))
20387 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20388 (message "Local setup has been refreshed"))
20389 (plain-list
20390 ;; At a plain list, with a double C-u argument, set
20391 ;; checkboxes of each item to "[-]", whereas a single one
20392 ;; will toggle their presence according to the state of the
20393 ;; first item in the list. Without an argument, repair the
20394 ;; list.
20395 (let* ((begin (org-element-property :contents-begin context))
20396 (beginm (move-marker (make-marker) begin))
20397 (struct (org-element-property :structure context))
20398 (old-struct (copy-tree struct))
20399 (first-box (save-excursion
20400 (goto-char begin)
20401 (looking-at org-list-full-item-re)
20402 (match-string-no-properties 3)))
20403 (new-box (cond ((equal arg '(16)) "[-]")
20404 ((equal arg '(4)) (unless first-box "[ ]"))
20405 ((equal first-box "[X]") "[ ]")
20406 (t "[X]"))))
20407 (cond
20408 (arg
20409 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20410 (org-list-get-all-items
20411 begin struct (org-list-prevs-alist struct))))
20412 ((and first-box (eq (point) begin))
20413 ;; For convenience, when point is at bol on the first
20414 ;; item of the list and no argument is provided, simply
20415 ;; toggle checkbox of that item, if any.
20416 (org-list-set-checkbox begin struct new-box)))
20417 (org-list-write-struct
20418 struct (org-list-parents-alist struct) old-struct)
20419 (org-update-checkbox-count-maybe)
20420 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20421 ((property-drawer node-property)
20422 (call-interactively 'org-property-action))
20423 ((radio-target target)
20424 (call-interactively 'org-update-radio-target-regexp))
20425 (statistics-cookie
20426 (call-interactively 'org-update-statistics-cookies))
20427 ((table table-cell table-row)
20428 ;; At a table, recalculate every field and align it. Also
20429 ;; send the table if necessary. If the table has
20430 ;; a `table.el' type, just give up. At a table row or
20431 ;; cell, maybe recalculate line but always align table.
20432 (if (eq (org-element-property :type context) 'table.el)
20433 (message "Use C-c ' to edit table.el tables")
20434 (let ((org-enable-table-editor t))
20435 (if (or (eq type 'table)
20436 ;; Check if point is at a TBLFM line.
20437 (and (eq type 'table-row)
20438 (= (point) (org-element-property :end context))))
20439 (save-excursion
20440 (if (org-at-TBLFM-p)
20441 (progn (require 'org-table)
20442 (org-table-calc-current-TBLFM))
20443 (goto-char (org-element-property :contents-begin context))
20444 (org-call-with-arg 'org-table-recalculate (or arg t))
20445 (orgtbl-send-table 'maybe)))
20446 (org-table-maybe-eval-formula)
20447 (cond (arg (call-interactively 'org-table-recalculate))
20448 ((org-table-maybe-recalculate-line))
20449 (t (org-table-align)))))))
20450 (timestamp (org-timestamp-change 0 'day))
20451 (otherwise
20452 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20453 (user-error
20454 "C-c C-c can do nothing useful at this location")))))))))
20456 (defun org-mode-restart ()
20457 (interactive)
20458 (let ((indent-status (org-bound-and-true-p org-indent-mode)))
20459 (funcall major-mode)
20460 (hack-local-variables)
20461 (when (and indent-status (not (org-bound-and-true-p org-indent-mode)))
20462 (org-indent-mode -1)))
20463 (message "%s restarted" major-mode))
20465 (defun org-kill-note-or-show-branches ()
20466 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20467 (interactive)
20468 (if (not org-finish-function)
20469 (progn
20470 (hide-subtree)
20471 (call-interactively 'show-branches))
20472 (let ((org-note-abort t))
20473 (funcall org-finish-function))))
20475 (defun org-open-line (n)
20476 "Insert a new row in tables, call `open-line' elsewhere.
20477 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
20478 (interactive "*p")
20479 (cond
20480 ((not org-special-ctrl-o)
20481 (open-line n))
20482 ((org-at-table-p)
20483 (org-table-insert-row))
20485 (open-line n))))
20487 (defun org-return (&optional indent)
20488 "Goto next table row or insert a newline.
20489 Calls `org-table-next-row' or `newline', depending on context.
20490 See the individual commands for more information."
20491 (interactive)
20492 (let (org-ts-what)
20493 (cond
20494 ((or (bobp) (org-in-src-block-p))
20495 (if indent (newline-and-indent) (newline)))
20496 ((org-at-table-p)
20497 (org-table-justify-field-maybe)
20498 (call-interactively 'org-table-next-row))
20499 ;; when `newline-and-indent' is called within a list, make sure
20500 ;; text moved stays inside the item.
20501 ((and (org-in-item-p) indent)
20502 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20503 (progn
20504 (save-match-data (newline))
20505 (org-indent-line-to (length (match-string 0))))
20506 (let ((ind (org-get-indentation)))
20507 (newline)
20508 (if (org-looking-back org-list-end-re)
20509 (org-indent-line)
20510 (org-indent-line-to ind)))))
20511 ((and org-return-follows-link
20512 (org-at-timestamp-p t)
20513 (not (eq org-ts-what 'after)))
20514 (org-follow-timestamp-link))
20515 ((and org-return-follows-link
20516 (let ((tprop (get-text-property (point) 'face)))
20517 (or (eq tprop 'org-link)
20518 (and (listp tprop) (memq 'org-link tprop)))))
20519 (call-interactively 'org-open-at-point))
20520 ((and (org-at-heading-p)
20521 (looking-at
20522 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20523 (org-show-entry)
20524 (end-of-line 1)
20525 (newline))
20526 (t (if indent (newline-and-indent) (newline))))))
20528 (defun org-return-indent ()
20529 "Goto next table row or insert a newline and indent.
20530 Calls `org-table-next-row' or `newline-and-indent', depending on
20531 context. See the individual commands for more information."
20532 (interactive)
20533 (org-return t))
20535 (defun org-ctrl-c-star ()
20536 "Compute table, or change heading status of lines.
20537 Calls `org-table-recalculate' or `org-toggle-heading',
20538 depending on context."
20539 (interactive)
20540 (cond
20541 ((org-at-table-p)
20542 (call-interactively 'org-table-recalculate))
20544 ;; Convert all lines in region to list items
20545 (call-interactively 'org-toggle-heading))))
20547 (defun org-ctrl-c-minus ()
20548 "Insert separator line in table or modify bullet status of line.
20549 Also turns a plain line or a region of lines into list items.
20550 Calls `org-table-insert-hline', `org-toggle-item', or
20551 `org-cycle-list-bullet', depending on context."
20552 (interactive)
20553 (cond
20554 ((org-at-table-p)
20555 (call-interactively 'org-table-insert-hline))
20556 ((org-region-active-p)
20557 (call-interactively 'org-toggle-item))
20558 ((org-in-item-p)
20559 (call-interactively 'org-cycle-list-bullet))
20561 (call-interactively 'org-toggle-item))))
20563 (defun org-toggle-item (arg)
20564 "Convert headings or normal lines to items, items to normal lines.
20565 If there is no active region, only the current line is considered.
20567 If the first non blank line in the region is a headline, convert
20568 all headlines to items, shifting text accordingly.
20570 If it is an item, convert all items to normal lines.
20572 If it is normal text, change region into a list of items.
20573 With a prefix argument ARG, change the region in a single item."
20574 (interactive "P")
20575 (let ((shift-text
20576 (function
20577 ;; Shift text in current section to IND, from point to END.
20578 ;; The function leaves point to END line.
20579 (lambda (ind end)
20580 (let ((min-i 1000) (end (copy-marker end)))
20581 ;; First determine the minimum indentation (MIN-I) of
20582 ;; the text.
20583 (save-excursion
20584 (catch 'exit
20585 (while (< (point) end)
20586 (let ((i (org-get-indentation)))
20587 (cond
20588 ;; Skip blank lines and inline tasks.
20589 ((looking-at "^[ \t]*$"))
20590 ((looking-at org-outline-regexp-bol))
20591 ;; We can't find less than 0 indentation.
20592 ((zerop i) (throw 'exit (setq min-i 0)))
20593 ((< i min-i) (setq min-i i))))
20594 (forward-line))))
20595 ;; Then indent each line so that a line indented to
20596 ;; MIN-I becomes indented to IND. Ignore blank lines
20597 ;; and inline tasks in the process.
20598 (let ((delta (- ind min-i)))
20599 (while (< (point) end)
20600 (unless (or (looking-at "^[ \t]*$")
20601 (looking-at org-outline-regexp-bol))
20602 (org-indent-line-to (+ (org-get-indentation) delta)))
20603 (forward-line)))))))
20604 (skip-blanks
20605 (function
20606 ;; Return beginning of first non-blank line, starting from
20607 ;; line at POS.
20608 (lambda (pos)
20609 (save-excursion
20610 (goto-char pos)
20611 (skip-chars-forward " \r\t\n")
20612 (point-at-bol)))))
20613 beg end)
20614 ;; Determine boundaries of changes.
20615 (if (org-region-active-p)
20616 (setq beg (funcall skip-blanks (region-beginning))
20617 end (copy-marker (region-end)))
20618 (setq beg (funcall skip-blanks (point-at-bol))
20619 end (copy-marker (point-at-eol))))
20620 ;; Depending on the starting line, choose an action on the text
20621 ;; between BEG and END.
20622 (org-with-limited-levels
20623 (save-excursion
20624 (goto-char beg)
20625 (cond
20626 ;; Case 1. Start at an item: de-itemize. Note that it only
20627 ;; happens when a region is active: `org-ctrl-c-minus'
20628 ;; would call `org-cycle-list-bullet' otherwise.
20629 ((org-at-item-p)
20630 (while (< (point) end)
20631 (when (org-at-item-p)
20632 (skip-chars-forward " \t")
20633 (delete-region (point) (match-end 0)))
20634 (forward-line)))
20635 ;; Case 2. Start at an heading: convert to items.
20636 ((org-at-heading-p)
20637 (let* ((bul (org-list-bullet-string "-"))
20638 (bul-len (length bul))
20639 ;; Indentation of the first heading. It should be
20640 ;; relative to the indentation of its parent, if any.
20641 (start-ind (save-excursion
20642 (cond
20643 ((not org-adapt-indentation) 0)
20644 ((not (outline-previous-heading)) 0)
20645 (t (length (match-string 0))))))
20646 ;; Level of first heading. Further headings will be
20647 ;; compared to it to determine hierarchy in the list.
20648 (ref-level (org-reduced-level (org-outline-level))))
20649 (while (< (point) end)
20650 (let* ((level (org-reduced-level (org-outline-level)))
20651 (delta (max 0 (- level ref-level))))
20652 ;; If current headline is less indented than the first
20653 ;; one, set it as reference, in order to preserve
20654 ;; subtrees.
20655 (when (< level ref-level) (setq ref-level level))
20656 (replace-match bul t t)
20657 (org-indent-line-to (+ start-ind (* delta bul-len)))
20658 ;; Ensure all text down to END (or SECTION-END) belongs
20659 ;; to the newly created item.
20660 (let ((section-end (save-excursion
20661 (or (outline-next-heading) (point)))))
20662 (forward-line)
20663 (funcall shift-text
20664 (+ start-ind (* (1+ delta) bul-len))
20665 (min end section-end)))))))
20666 ;; Case 3. Normal line with ARG: make the first line of region
20667 ;; an item, and shift indentation of others lines to
20668 ;; set them as item's body.
20669 (arg (let* ((bul (org-list-bullet-string "-"))
20670 (bul-len (length bul))
20671 (ref-ind (org-get-indentation)))
20672 (skip-chars-forward " \t")
20673 (insert bul)
20674 (forward-line)
20675 (while (< (point) end)
20676 ;; Ensure that lines less indented than first one
20677 ;; still get included in item body.
20678 (funcall shift-text
20679 (+ ref-ind bul-len)
20680 (min end (save-excursion (or (outline-next-heading)
20681 (point)))))
20682 (forward-line))))
20683 ;; Case 4. Normal line without ARG: turn each non-item line
20684 ;; into an item.
20686 (while (< (point) end)
20687 (unless (or (org-at-heading-p) (org-at-item-p))
20688 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20689 (replace-match
20690 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20691 (forward-line))))))))
20693 (defun org-toggle-heading (&optional nstars)
20694 "Convert headings to normal text, or items or text to headings.
20695 If there is no active region, only convert the current line.
20697 With a \\[universal-argument] prefix, convert the whole list at
20698 point into heading.
20700 In a region:
20702 - If the first non blank line is a headline, remove the stars
20703 from all headlines in the region.
20705 - If it is a normal line, turn each and every normal line (i.e.,
20706 not an heading or an item) in the region into headings. If you
20707 want to convert only the first line of this region, use one
20708 universal prefix argument.
20710 - If it is a plain list item, turn all plain list items into headings.
20712 When converting a line into a heading, the number of stars is chosen
20713 such that the lines become children of the current entry. However,
20714 when a numeric prefix argument is given, its value determines the
20715 number of stars to add."
20716 (interactive "P")
20717 (let ((skip-blanks
20718 (function
20719 ;; Return beginning of first non-blank line, starting from
20720 ;; line at POS.
20721 (lambda (pos)
20722 (save-excursion
20723 (goto-char pos)
20724 (while (org-at-comment-p) (forward-line))
20725 (skip-chars-forward " \r\t\n")
20726 (point-at-bol)))))
20727 beg end toggled)
20728 ;; Determine boundaries of changes. If a universal prefix has
20729 ;; been given, put the list in a region. If region ends at a bol,
20730 ;; do not consider the last line to be in the region.
20732 (when (and current-prefix-arg (org-at-item-p))
20733 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20734 (org-mark-element))
20736 (if (org-region-active-p)
20737 (setq beg (funcall skip-blanks (region-beginning))
20738 end (copy-marker (save-excursion
20739 (goto-char (region-end))
20740 (if (bolp) (point) (point-at-eol)))))
20741 (setq beg (funcall skip-blanks (point-at-bol))
20742 end (copy-marker (point-at-eol))))
20743 ;; Ensure inline tasks don't count as headings.
20744 (org-with-limited-levels
20745 (save-excursion
20746 (goto-char beg)
20747 (cond
20748 ;; Case 1. Started at an heading: de-star headings.
20749 ((org-at-heading-p)
20750 (while (< (point) end)
20751 (when (org-at-heading-p t)
20752 (looking-at org-outline-regexp) (replace-match "")
20753 (setq toggled t))
20754 (forward-line)))
20755 ;; Case 2. Started at an item: change items into headlines.
20756 ;; One star will be added by `org-list-to-subtree'.
20757 ((org-at-item-p)
20758 (let* ((stars (make-string
20759 ;; subtract the star that will be added again by
20760 ;; `org-list-to-subtree'
20761 (if (numberp nstars) (1- nstars)
20762 (or (org-current-level) 0))
20763 ?*))
20764 (add-stars
20765 (cond (nstars "") ; stars from prefix only
20766 ((equal stars "") "") ; before first heading
20767 (org-odd-levels-only "*") ; inside heading, odd
20768 (t "")))) ; inside heading, oddeven
20769 (while (< (point) end)
20770 (when (org-at-item-p)
20771 ;; Pay attention to cases when region ends before list.
20772 (let* ((struct (org-list-struct))
20773 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20774 (save-restriction
20775 (narrow-to-region (point) list-end)
20776 (insert
20777 (org-list-to-subtree
20778 (org-list-parse-list t)
20779 '(:istart (concat stars add-stars (funcall get-stars depth))
20780 :icount (concat stars add-stars (funcall get-stars depth)))))))
20781 (setq toggled t))
20782 (forward-line))))
20783 ;; Case 3. Started at normal text: make every line an heading,
20784 ;; skipping headlines and items.
20785 (t (let* ((stars
20786 (make-string
20787 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20788 (add-stars
20789 (cond (nstars "") ; stars from prefix only
20790 ((equal stars "") "*") ; before first heading
20791 (org-odd-levels-only "**") ; inside heading, odd
20792 (t "*"))) ; inside heading, oddeven
20793 (rpl (concat stars add-stars " "))
20794 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20795 (while (< (point) (if (equal nstars '(4)) lend end))
20796 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20797 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20798 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20799 (forward-line)))))))
20800 (unless toggled (message "Cannot toggle heading from here"))))
20802 (defun org-meta-return (&optional arg)
20803 "Insert a new heading or wrap a region in a table.
20804 Calls `org-insert-heading' or `org-table-wrap-region', depending
20805 on context. See the individual commands for more information."
20806 (interactive "P")
20807 (org-check-before-invisible-edit 'insert)
20808 (or (run-hook-with-args-until-success 'org-metareturn-hook)
20809 (let* ((element (org-element-at-point))
20810 (type (org-element-type element)))
20811 (when (eq type 'table-row)
20812 (setq element (org-element-property :parent element))
20813 (setq type 'table))
20814 (if (and (eq type 'table)
20815 (eq (org-element-property :type element) 'org)
20816 (>= (point) (org-element-property :contents-begin element))
20817 (< (point) (org-element-property :contents-end element)))
20818 (call-interactively 'org-table-wrap-region)
20819 (call-interactively 'org-insert-heading)))))
20821 ;;; Menu entries
20823 (defsubst org-in-subtree-not-table-p ()
20824 "Are we in a subtree and not in a table?"
20825 (and (not (org-before-first-heading-p))
20826 (not (org-at-table-p))))
20828 ;; Define the Org-mode menus
20829 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20830 '("Tbl"
20831 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20832 ["Next Field" org-cycle (org-at-table-p)]
20833 ["Previous Field" org-shifttab (org-at-table-p)]
20834 ["Next Row" org-return (org-at-table-p)]
20835 "--"
20836 ["Blank Field" org-table-blank-field (org-at-table-p)]
20837 ["Edit Field" org-table-edit-field (org-at-table-p)]
20838 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20839 "--"
20840 ("Column"
20841 ["Move Column Left" org-metaleft (org-at-table-p)]
20842 ["Move Column Right" org-metaright (org-at-table-p)]
20843 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20844 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20845 ("Row"
20846 ["Move Row Up" org-metaup (org-at-table-p)]
20847 ["Move Row Down" org-metadown (org-at-table-p)]
20848 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20849 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20850 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20851 "--"
20852 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20853 ("Rectangle"
20854 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20855 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20856 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20857 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20858 "--"
20859 ("Calculate"
20860 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20861 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20862 ["Edit Formulas" org-edit-special (org-at-table-p)]
20863 "--"
20864 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20865 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20866 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20867 "--"
20868 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20869 "--"
20870 ["Sum Column/Rectangle" org-table-sum
20871 (or (org-at-table-p) (org-region-active-p))]
20872 ["Which Column?" org-table-current-column (org-at-table-p)])
20873 ["Debug Formulas"
20874 org-table-toggle-formula-debugger
20875 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20876 ["Show Col/Row Numbers"
20877 org-table-toggle-coordinate-overlays
20878 :style toggle
20879 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20880 "--"
20881 ["Create" org-table-create (and (not (org-at-table-p))
20882 org-enable-table-editor)]
20883 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20884 ["Import from File" org-table-import (not (org-at-table-p))]
20885 ["Export to File" org-table-export (org-at-table-p)]
20886 "--"
20887 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20889 (easy-menu-define org-org-menu org-mode-map "Org menu"
20890 '("Org"
20891 ("Show/Hide"
20892 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20893 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20894 ["Sparse Tree..." org-sparse-tree t]
20895 ["Reveal Context" org-reveal t]
20896 ["Show All" show-all t]
20897 "--"
20898 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20899 "--"
20900 ["New Heading" org-insert-heading t]
20901 ("Navigate Headings"
20902 ["Up" outline-up-heading t]
20903 ["Next" outline-next-visible-heading t]
20904 ["Previous" outline-previous-visible-heading t]
20905 ["Next Same Level" outline-forward-same-level t]
20906 ["Previous Same Level" outline-backward-same-level t]
20907 "--"
20908 ["Jump" org-goto t])
20909 ("Edit Structure"
20910 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20911 "--"
20912 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20913 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20914 "--"
20915 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20916 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20917 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20918 "--"
20919 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20920 "--"
20921 ["Copy visible text" org-copy-visible t]
20922 "--"
20923 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20924 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20925 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20926 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20927 "--"
20928 ["Sort Region/Children" org-sort t]
20929 "--"
20930 ["Convert to odd levels" org-convert-to-odd-levels t]
20931 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20932 ("Editing"
20933 ["Emphasis..." org-emphasize t]
20934 ["Edit Source Example" org-edit-special t]
20935 "--"
20936 ["Footnote new/jump" org-footnote-action t]
20937 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20938 ("Archive"
20939 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20940 "--"
20941 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20942 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20943 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20945 "--"
20946 ("Hyperlinks"
20947 ["Store Link (Global)" org-store-link t]
20948 ["Find existing link to here" org-occur-link-in-agenda-files t]
20949 ["Insert Link" org-insert-link t]
20950 ["Follow Link" org-open-at-point t]
20951 "--"
20952 ["Next link" org-next-link t]
20953 ["Previous link" org-previous-link t]
20954 "--"
20955 ["Descriptive Links"
20956 org-toggle-link-display
20957 :style radio
20958 :selected org-descriptive-links
20960 ["Literal Links"
20961 org-toggle-link-display
20962 :style radio
20963 :selected (not org-descriptive-links)])
20964 "--"
20965 ("TODO Lists"
20966 ["TODO/DONE/-" org-todo t]
20967 ("Select keyword"
20968 ["Next keyword" org-shiftright (org-at-heading-p)]
20969 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20970 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20971 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20972 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20973 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20974 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20975 "--"
20976 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20977 :selected org-enforce-todo-dependencies :style toggle :active t]
20978 "Settings for tree at point"
20979 ["Do Children sequentially" org-toggle-ordered-property :style radio
20980 :selected (org-entry-get nil "ORDERED")
20981 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20982 ["Do Children parallel" org-toggle-ordered-property :style radio
20983 :selected (not (org-entry-get nil "ORDERED"))
20984 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20985 "--"
20986 ["Set Priority" org-priority t]
20987 ["Priority Up" org-shiftup t]
20988 ["Priority Down" org-shiftdown t]
20989 "--"
20990 ["Get news from all feeds" org-feed-update-all t]
20991 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20992 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20993 ("TAGS and Properties"
20994 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20995 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20996 "--"
20997 ["Set property" org-set-property (not (org-before-first-heading-p))]
20998 ["Column view of properties" org-columns t]
20999 ["Insert Column View DBlock" org-insert-columns-dblock t])
21000 ("Dates and Scheduling"
21001 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21002 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21003 ("Change Date"
21004 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21005 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21006 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21007 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21008 ["Compute Time Range" org-evaluate-time-range t]
21009 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21010 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21011 "--"
21012 ["Custom time format" org-toggle-time-stamp-overlays
21013 :style radio :selected org-display-custom-times]
21014 "--"
21015 ["Goto Calendar" org-goto-calendar t]
21016 ["Date from Calendar" org-date-from-calendar t]
21017 "--"
21018 ["Start/Restart Timer" org-timer-start t]
21019 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21020 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21021 ["Insert Timer String" org-timer t]
21022 ["Insert Timer Item" org-timer-item t])
21023 ("Logging work"
21024 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21025 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21026 ["Clock out" org-clock-out t]
21027 ["Clock cancel" org-clock-cancel t]
21028 "--"
21029 ["Mark as default task" org-clock-mark-default-task t]
21030 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21031 ["Goto running clock" org-clock-goto t]
21032 "--"
21033 ["Display times" org-clock-display t]
21034 ["Create clock table" org-clock-report t]
21035 "--"
21036 ["Record DONE time"
21037 (progn (setq org-log-done (not org-log-done))
21038 (message "Switching to %s will %s record a timestamp"
21039 (car org-done-keywords)
21040 (if org-log-done "automatically" "not")))
21041 :style toggle :selected org-log-done])
21042 "--"
21043 ["Agenda Command..." org-agenda t]
21044 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21045 ("File List for Agenda")
21046 ("Special views current file"
21047 ["TODO Tree" org-show-todo-tree t]
21048 ["Check Deadlines" org-check-deadlines t]
21049 ["Timeline" org-timeline t]
21050 ["Tags/Property tree" org-match-sparse-tree t])
21051 "--"
21052 ["Export/Publish..." org-export-dispatch t]
21053 ("LaTeX"
21054 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21055 :selected org-cdlatex-mode]
21056 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21057 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21058 ["Modify math symbol" org-cdlatex-math-modify
21059 (org-inside-LaTeX-fragment-p)]
21060 ["Insert citation" org-reftex-citation t]
21061 "--"
21062 ["Template for BEAMER" (org-beamer-insert-options-template) t])
21063 "--"
21064 ("MobileOrg"
21065 ["Push Files and Views" org-mobile-push t]
21066 ["Get Captured and Flagged" org-mobile-pull t]
21067 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21068 "--"
21069 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21070 "--"
21071 ("Documentation"
21072 ["Show Version" org-version t]
21073 ["Info Documentation" org-info t])
21074 ("Customize"
21075 ["Browse Org Group" org-customize t]
21076 "--"
21077 ["Expand This Menu" org-create-customize-menu
21078 (fboundp 'customize-menu-create)])
21079 ["Send bug report" org-submit-bug-report t]
21080 "--"
21081 ("Refresh/Reload"
21082 ["Refresh setup current buffer" org-mode-restart t]
21083 ["Reload Org (after update)" org-reload t]
21084 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21087 (defun org-info (&optional node)
21088 "Read documentation for Org-mode in the info system.
21089 With optional NODE, go directly to that node."
21090 (interactive)
21091 (info (format "(org)%s" (or node ""))))
21093 ;;;###autoload
21094 (defun org-submit-bug-report ()
21095 "Submit a bug report on Org-mode via mail.
21097 Don't hesitate to report any problems or inaccurate documentation.
21099 If you don't have setup sending mail from (X)Emacs, please copy the
21100 output buffer into your mail program, as it gives us important
21101 information about your Org-mode version and configuration."
21102 (interactive)
21103 (require 'reporter)
21104 (org-load-modules-maybe)
21105 (org-require-autoloaded-modules)
21106 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21107 (reporter-submit-bug-report
21108 "emacs-orgmode@gnu.org"
21109 (org-version nil 'full)
21110 (let (list)
21111 (save-window-excursion
21112 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21113 (delete-other-windows)
21114 (erase-buffer)
21115 (insert "You are about to submit a bug report to the Org-mode mailing list.
21117 We would like to add your full Org-mode and Outline configuration to the
21118 bug report. This greatly simplifies the work of the maintainer and
21119 other experts on the mailing list.
21121 HOWEVER, some variables you have customized may contain private
21122 information. The names of customers, colleagues, or friends, might
21123 appear in the form of file names, tags, todo states, or search strings.
21124 If you answer yes to the prompt, you might want to check and remove
21125 such private information before sending the email.")
21126 (add-text-properties (point-min) (point-max) '(face org-warning))
21127 (when (yes-or-no-p "Include your Org-mode configuration ")
21128 (mapatoms
21129 (lambda (v)
21130 (and (boundp v)
21131 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21132 (or (and (symbol-value v)
21133 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21134 (and
21135 (get v 'custom-type) (get v 'standard-value)
21136 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21137 (push v list)))))
21138 (kill-buffer (get-buffer "*Warn about privacy*"))
21139 list))
21140 nil nil
21141 "Remember to cover the basics, that is, what you expected to happen and
21142 what in fact did happen. You don't know how to make a good report? See
21144 http://orgmode.org/manual/Feedback.html#Feedback
21146 Your bug report will be posted to the Org-mode mailing list.
21147 ------------------------------------------------------------------------")
21148 (save-excursion
21149 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21150 (replace-match "\\1Bug: \\3 [\\2]")))))
21153 (defun org-install-agenda-files-menu ()
21154 (let ((bl (buffer-list)))
21155 (save-excursion
21156 (while bl
21157 (set-buffer (pop bl))
21158 (if (derived-mode-p 'org-mode) (setq bl nil)))
21159 (when (derived-mode-p 'org-mode)
21160 (easy-menu-change
21161 '("Org") "File List for Agenda"
21162 (append
21163 (list
21164 ["Edit File List" (org-edit-agenda-file-list) t]
21165 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21166 ["Remove Current File from List" org-remove-file t]
21167 ["Cycle through agenda files" org-cycle-agenda-files t]
21168 ["Occur in all agenda files" org-occur-in-agenda-files t]
21169 "--")
21170 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21172 ;;;; Documentation
21174 (defun org-require-autoloaded-modules ()
21175 (interactive)
21176 (mapc 'require
21177 '(org-agenda org-archive org-attach org-clock org-colview org-id
21178 org-table org-timer)))
21180 ;;;###autoload
21181 (defun org-reload (&optional uncompiled)
21182 "Reload all org lisp files.
21183 With prefix arg UNCOMPILED, load the uncompiled versions."
21184 (interactive "P")
21185 (require 'loadhist)
21186 (let* ((org-dir (org-find-library-dir "org"))
21187 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21188 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21189 (remove-re (mapconcat 'identity
21190 (mapcar (lambda (f) (concat "^" f "$"))
21191 (list (if (featurep 'xemacs)
21192 "org-colview"
21193 "org-colview-xemacs")
21194 "org" "org-loaddefs" "org-version"))
21195 "\\|"))
21196 (feats (delete-dups
21197 (mapcar 'file-name-sans-extension
21198 (mapcar 'file-name-nondirectory
21199 (delq nil
21200 (mapcar 'feature-file
21201 features))))))
21202 (lfeat (append
21203 (sort
21204 (setq feats
21205 (delq nil (mapcar
21206 (lambda (f)
21207 (if (and (string-match feature-re f)
21208 (not (string-match remove-re f)))
21209 f nil))
21210 feats)))
21211 'string-lessp)
21212 (list "org-version" "org")))
21213 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21214 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21215 load-uncore load-misses)
21216 (setq load-misses
21217 (delq 't
21218 (mapcar (lambda (f)
21219 (or (org-load-noerror-mustsuffix (concat org-dir f))
21220 (and (string= org-dir contrib-dir)
21221 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21222 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21223 (add-to-list 'load-uncore f 'append)
21226 lfeat)))
21227 (if load-uncore
21228 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21229 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21230 (if load-misses
21231 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21232 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21233 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21235 ;;;###autoload
21236 (defun org-customize ()
21237 "Call the customize function with org as argument."
21238 (interactive)
21239 (org-load-modules-maybe)
21240 (org-require-autoloaded-modules)
21241 (customize-browse 'org))
21243 (defun org-create-customize-menu ()
21244 "Create a full customization menu for Org-mode, insert it into the menu."
21245 (interactive)
21246 (org-load-modules-maybe)
21247 (org-require-autoloaded-modules)
21248 (if (fboundp 'customize-menu-create)
21249 (progn
21250 (easy-menu-change
21251 '("Org") "Customize"
21252 `(["Browse Org group" org-customize t]
21253 "--"
21254 ,(customize-menu-create 'org)
21255 ["Set" Custom-set t]
21256 ["Save" Custom-save t]
21257 ["Reset to Current" Custom-reset-current t]
21258 ["Reset to Saved" Custom-reset-saved t]
21259 ["Reset to Standard Settings" Custom-reset-standard t]))
21260 (message "\"Org\"-menu now contains full customization menu"))
21261 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21263 ;;;; Miscellaneous stuff
21265 ;;; Generally useful functions
21267 (defun org-get-at-bol (property)
21268 "Get text property PROPERTY at beginning of line."
21269 (get-text-property (point-at-bol) property))
21271 (defun org-find-text-property-in-string (prop s)
21272 "Return the first non-nil value of property PROP in string S."
21273 (or (get-text-property 0 prop s)
21274 (get-text-property (or (next-single-property-change 0 prop s) 0)
21275 prop s)))
21277 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21278 "Display the given MESSAGE as a warning."
21279 (if (fboundp 'display-warning)
21280 (display-warning 'org message
21281 (if (featurep 'xemacs) 'warning :warning))
21282 (let ((buf (get-buffer-create "*Org warnings*")))
21283 (with-current-buffer buf
21284 (goto-char (point-max))
21285 (insert "Warning (Org): " message)
21286 (unless (bolp)
21287 (newline)))
21288 (display-buffer buf)
21289 (sit-for 0))))
21291 (defun org-eval (form)
21292 "Eval FORM and return result."
21293 (condition-case error
21294 (eval form)
21295 (error (format "%%![Error: %s]" error))))
21297 (defun org-in-clocktable-p ()
21298 "Check if the cursor is in a clocktable."
21299 (let ((pos (point)) start)
21300 (save-excursion
21301 (end-of-line 1)
21302 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21303 (setq start (match-beginning 0))
21304 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21305 (>= (match-end 0) pos)
21306 start))))
21308 (defun org-in-commented-line ()
21309 "Is point in a line starting with `#'?"
21310 (equal (char-after (point-at-bol)) ?#))
21312 (defun org-in-indented-comment-line ()
21313 "Is point in a line starting with `#' after some white space?"
21314 (save-excursion
21315 (save-match-data
21316 (goto-char (point-at-bol))
21317 (looking-at "[ \t]*#"))))
21319 (defun org-in-verbatim-emphasis ()
21320 (save-match-data
21321 (and (org-in-regexp org-emph-re 2)
21322 (>= (point) (match-beginning 3))
21323 (<= (point) (match-end 4))
21324 (member (match-string 3) '("=" "~")))))
21326 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21327 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21328 (if (and marker (marker-buffer marker)
21329 (buffer-live-p (marker-buffer marker)))
21330 (progn
21331 (org-pop-to-buffer-same-window (marker-buffer marker))
21332 (if (or (> marker (point-max)) (< marker (point-min)))
21333 (widen))
21334 (goto-char marker)
21335 (org-show-context 'org-goto))
21336 (if bookmark
21337 (bookmark-jump bookmark)
21338 (error "Cannot find location"))))
21340 (defun org-quote-csv-field (s)
21341 "Quote field for inclusion in CSV material."
21342 (if (string-match "[\",]" s)
21343 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21346 (defun org-force-self-insert (N)
21347 "Needed to enforce self-insert under remapping."
21348 (interactive "p")
21349 (self-insert-command N))
21351 (defun org-string-width (s)
21352 "Compute width of string, ignoring invisible characters.
21353 This ignores character with invisibility property `org-link', and also
21354 characters with property `org-cwidth', because these will become invisible
21355 upon the next fontification round."
21356 (let (b l)
21357 (when (or (eq t buffer-invisibility-spec)
21358 (assq 'org-link buffer-invisibility-spec))
21359 (while (setq b (text-property-any 0 (length s)
21360 'invisible 'org-link s))
21361 (setq s (concat (substring s 0 b)
21362 (substring s (or (next-single-property-change
21363 b 'invisible s) (length s)))))))
21364 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21365 (setq s (concat (substring s 0 b)
21366 (substring s (or (next-single-property-change
21367 b 'org-cwidth s) (length s))))))
21368 (setq l (string-width s) b -1)
21369 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21370 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21373 (defun org-shorten-string (s maxlength)
21374 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21375 If the string is shorter or has length MAXLENGTH, just return the
21376 original string. If it is longer, the functions finds a space in the
21377 string, breaks this string off at that locations and adds three dots
21378 as ellipsis. Including the ellipsis, the string will not be longer
21379 than MAXLENGTH. If finding a good breaking point in the string does
21380 not work, the string is just chopped off in the middle of a word
21381 if necessary."
21382 (if (<= (length s) maxlength)
21384 (let* ((n (max (- maxlength 4) 1))
21385 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21386 (if (string-match re s)
21387 (concat (match-string 1 s) "...")
21388 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21390 (defun org-get-indentation (&optional line)
21391 "Get the indentation of the current line, interpreting tabs.
21392 When LINE is given, assume it represents a line and compute its indentation."
21393 (if line
21394 (if (string-match "^ *" (org-remove-tabs line))
21395 (match-end 0))
21396 (save-excursion
21397 (beginning-of-line 1)
21398 (skip-chars-forward " \t")
21399 (current-column))))
21401 (defun org-get-string-indentation (s)
21402 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21403 (let ((n -1) (i 0) (w tab-width) c)
21404 (catch 'exit
21405 (while (< (setq n (1+ n)) (length s))
21406 (setq c (aref s n))
21407 (cond ((= c ?\ ) (setq i (1+ i)))
21408 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21409 (t (throw 'exit t)))))
21412 (defun org-remove-tabs (s &optional width)
21413 "Replace tabulators in S with spaces.
21414 Assumes that s is a single line, starting in column 0."
21415 (setq width (or width tab-width))
21416 (while (string-match "\t" s)
21417 (setq s (replace-match
21418 (make-string
21419 (- (* width (/ (+ (match-beginning 0) width) width))
21420 (match-beginning 0)) ?\ )
21421 t t s)))
21424 (defun org-fix-indentation (line ind)
21425 "Fix indentation in LINE.
21426 IND is a cons cell with target and minimum indentation.
21427 If the current indentation in LINE is smaller than the minimum,
21428 leave it alone. If it is larger than ind, set it to the target."
21429 (let* ((l (org-remove-tabs line))
21430 (i (org-get-indentation l))
21431 (i1 (car ind)) (i2 (cdr ind)))
21432 (if (>= i i2) (setq l (substring line i2)))
21433 (if (> i1 0)
21434 (concat (make-string i1 ?\ ) l)
21435 l)))
21437 (defun org-remove-indentation (code &optional n)
21438 "Remove the maximum common indentation from the lines in CODE.
21439 N may optionally be the number of spaces to remove."
21440 (with-temp-buffer
21441 (insert code)
21442 (org-do-remove-indentation n)
21443 (buffer-string)))
21445 (defun org-do-remove-indentation (&optional n)
21446 "Remove the maximum common indentation from the buffer."
21447 (untabify (point-min) (point-max))
21448 (let ((min 10000) re)
21449 (if n
21450 (setq min n)
21451 (goto-char (point-min))
21452 (while (re-search-forward "^ *[^ \n]" nil t)
21453 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21454 (unless (or (= min 0) (= min 10000))
21455 (setq re (format "^ \\{%d\\}" min))
21456 (goto-char (point-min))
21457 (while (re-search-forward re nil t)
21458 (replace-match "")
21459 (end-of-line 1))
21460 min)))
21462 (defun org-fill-template (template alist)
21463 "Find each %key of ALIST in TEMPLATE and replace it."
21464 (let ((case-fold-search nil)
21465 entry key value)
21466 (setq alist (sort (copy-sequence alist)
21467 (lambda (a b) (< (length (car a)) (length (car b))))))
21468 (while (setq entry (pop alist))
21469 (setq template
21470 (replace-regexp-in-string
21471 (concat "%" (regexp-quote (car entry)))
21472 (or (cdr entry) "") template t t)))
21473 template))
21475 (defun org-base-buffer (buffer)
21476 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21477 (if (not buffer)
21478 buffer
21479 (or (buffer-base-buffer buffer)
21480 buffer)))
21482 (defun org-trim (s)
21483 "Remove whitespace at beginning and end of string."
21484 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
21485 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
21488 (defun org-wrap (string &optional width lines)
21489 "Wrap string to either a number of lines, or a width in characters.
21490 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21491 that costs. If there is a word longer than WIDTH, the text is actually
21492 wrapped to the length of that word.
21493 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21494 many lines, whatever width that takes.
21495 The return value is a list of lines, without newlines at the end."
21496 (let* ((words (org-split-string string "[ \t\n]+"))
21497 (maxword (apply 'max (mapcar 'org-string-width words)))
21498 w ll)
21499 (cond (width
21500 (org-do-wrap words (max maxword width)))
21501 (lines
21502 (setq w maxword)
21503 (setq ll (org-do-wrap words maxword))
21504 (if (<= (length ll) lines)
21506 (setq ll words)
21507 (while (> (length ll) lines)
21508 (setq w (1+ w))
21509 (setq ll (org-do-wrap words w)))
21510 ll))
21511 (t (error "Cannot wrap this")))))
21513 (defun org-do-wrap (words width)
21514 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21515 (let (lines line)
21516 (while words
21517 (setq line (pop words))
21518 (while (and words (< (+ (length line) (length (car words))) width))
21519 (setq line (concat line " " (pop words))))
21520 (setq lines (push line lines)))
21521 (nreverse lines)))
21523 (defun org-split-string (string &optional separators)
21524 "Splits STRING into substrings at SEPARATORS.
21525 No empty strings are returned if there are matches at the beginning
21526 and end of string."
21527 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21528 (start 0)
21529 notfirst
21530 (list nil))
21531 (while (and (string-match rexp string
21532 (if (and notfirst
21533 (= start (match-beginning 0))
21534 (< start (length string)))
21535 (1+ start) start))
21536 (< (match-beginning 0) (length string)))
21537 (setq notfirst t)
21538 (or (eq (match-beginning 0) 0)
21539 (and (eq (match-beginning 0) (match-end 0))
21540 (eq (match-beginning 0) start))
21541 (setq list
21542 (cons (substring string start (match-beginning 0))
21543 list)))
21544 (setq start (match-end 0)))
21545 (or (eq start (length string))
21546 (setq list
21547 (cons (substring string start)
21548 list)))
21549 (nreverse list)))
21551 (defun org-quote-vert (s)
21552 "Replace \"|\" with \"\\vert\"."
21553 (while (string-match "|" s)
21554 (setq s (replace-match "\\vert" t t s)))
21557 (defun org-uuidgen-p (s)
21558 "Is S an ID created by UUIDGEN?"
21559 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21561 (defun org-in-src-block-p (&optional inside)
21562 "Whether point is in a code source block.
21563 When INSIDE is non-nil, don't consider we are within a src block
21564 when point is at #+BEGIN_SRC or #+END_SRC."
21565 (let ((case-fold-search t) ov)
21566 (or (and (setq ov (overlays-at (point)))
21567 (memq 'org-block-background
21568 (overlay-properties (car ov))))
21569 (and (not inside)
21570 (save-match-data
21571 (save-excursion
21572 (beginning-of-line)
21573 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21575 (defun org-context ()
21576 "Return a list of contexts of the current cursor position.
21577 If several contexts apply, all are returned.
21578 Each context entry is a list with a symbol naming the context, and
21579 two positions indicating start and end of the context. Possible
21580 contexts are:
21582 :headline anywhere in a headline
21583 :headline-stars on the leading stars in a headline
21584 :todo-keyword on a TODO keyword (including DONE) in a headline
21585 :tags on the TAGS in a headline
21586 :priority on the priority cookie in a headline
21587 :item on the first line of a plain list item
21588 :item-bullet on the bullet/number of a plain list item
21589 :checkbox on the checkbox in a plain list item
21590 :table in an org-mode table
21591 :table-special on a special filed in a table
21592 :table-table in a table.el table
21593 :clocktable in a clocktable
21594 :src-block in a source block
21595 :link on a hyperlink
21596 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21597 :target on a <<target>>
21598 :radio-target on a <<<radio-target>>>
21599 :latex-fragment on a LaTeX fragment
21600 :latex-preview on a LaTeX fragment with overlaid preview image
21602 This function expects the position to be visible because it uses font-lock
21603 faces as a help to recognize the following contexts: :table-special, :link,
21604 and :keyword."
21605 (let* ((f (get-text-property (point) 'face))
21606 (faces (if (listp f) f (list f)))
21607 (case-fold-search t)
21608 (p (point)) clist o)
21609 ;; First the large context
21610 (cond
21611 ((org-at-heading-p t)
21612 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21613 (when (progn
21614 (beginning-of-line 1)
21615 (looking-at org-todo-line-tags-regexp))
21616 (push (org-point-in-group p 1 :headline-stars) clist)
21617 (push (org-point-in-group p 2 :todo-keyword) clist)
21618 (push (org-point-in-group p 4 :tags) clist))
21619 (goto-char p)
21620 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21621 (if (looking-at "\\[#[A-Z0-9]\\]")
21622 (push (org-point-in-group p 0 :priority) clist)))
21624 ((org-at-item-p)
21625 (push (org-point-in-group p 2 :item-bullet) clist)
21626 (push (list :item (point-at-bol)
21627 (save-excursion (org-end-of-item) (point)))
21628 clist)
21629 (and (org-at-item-checkbox-p)
21630 (push (org-point-in-group p 0 :checkbox) clist)))
21632 ((org-at-table-p)
21633 (push (list :table (org-table-begin) (org-table-end)) clist)
21634 (if (memq 'org-formula faces)
21635 (push (list :table-special
21636 (previous-single-property-change p 'face)
21637 (next-single-property-change p 'face)) clist)))
21638 ((org-at-table-p 'any)
21639 (push (list :table-table) clist)))
21640 (goto-char p)
21642 (let ((case-fold-search t))
21643 ;; New the "medium" contexts: clocktables, source blocks
21644 (cond ((org-in-clocktable-p)
21645 (push (list :clocktable
21646 (and (or (looking-at "#\\+BEGIN: clocktable")
21647 (search-backward "#+BEGIN: clocktable" nil t))
21648 (match-beginning 0))
21649 (and (re-search-forward "#\\+END:?" nil t)
21650 (match-end 0))) clist))
21651 ((org-in-src-block-p)
21652 (push (list :src-block
21653 (and (or (looking-at "#\\+BEGIN_SRC")
21654 (search-backward "#+BEGIN_SRC" nil t))
21655 (match-beginning 0))
21656 (and (search-forward "#+END_SRC" nil t)
21657 (match-beginning 0))) clist))))
21658 (goto-char p)
21660 ;; Now the small context
21661 (cond
21662 ((org-at-timestamp-p)
21663 (push (org-point-in-group p 0 :timestamp) clist))
21664 ((memq 'org-link faces)
21665 (push (list :link
21666 (previous-single-property-change p 'face)
21667 (next-single-property-change p 'face)) clist))
21668 ((memq 'org-special-keyword faces)
21669 (push (list :keyword
21670 (previous-single-property-change p 'face)
21671 (next-single-property-change p 'face)) clist))
21672 ((org-at-target-p)
21673 (push (org-point-in-group p 0 :target) clist)
21674 (goto-char (1- (match-beginning 0)))
21675 (if (looking-at org-radio-target-regexp)
21676 (push (org-point-in-group p 0 :radio-target) clist))
21677 (goto-char p))
21678 ((setq o (car (delq nil
21679 (mapcar
21680 (lambda (x)
21681 (if (memq x org-latex-fragment-image-overlays) x))
21682 (overlays-at (point))))))
21683 (push (list :latex-fragment
21684 (overlay-start o) (overlay-end o)) clist)
21685 (push (list :latex-preview
21686 (overlay-start o) (overlay-end o)) clist))
21687 ((org-inside-LaTeX-fragment-p)
21688 ;; FIXME: positions wrong.
21689 (push (list :latex-fragment (point) (point)) clist)))
21691 (setq clist (nreverse (delq nil clist)))
21692 clist))
21694 ;; FIXME: Compare with at-regexp-p Do we need both?
21695 (defun org-in-regexp (re &optional nlines visually)
21696 "Check if point is inside a match of regexp.
21697 Normally only the current line is checked, but you can include NLINES extra
21698 lines both before and after point into the search.
21699 If VISUALLY is set, require that the cursor is not after the match but
21700 really on, so that the block visually is on the match."
21701 (catch 'exit
21702 (let ((pos (point))
21703 (eol (point-at-eol (+ 1 (or nlines 0))))
21704 (inc (if visually 1 0)))
21705 (save-excursion
21706 (beginning-of-line (- 1 (or nlines 0)))
21707 (while (re-search-forward re eol t)
21708 (if (and (<= (match-beginning 0) pos)
21709 (>= (+ inc (match-end 0)) pos))
21710 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21712 (defun org-at-regexp-p (regexp)
21713 "Is point inside a match of REGEXP in the current line?"
21714 (catch 'exit
21715 (save-excursion
21716 (let ((pos (point)) (end (point-at-eol)))
21717 (beginning-of-line 1)
21718 (while (re-search-forward regexp end t)
21719 (if (and (<= (match-beginning 0) pos)
21720 (>= (match-end 0) pos))
21721 (throw 'exit t)))
21722 nil))))
21724 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21725 "Non-nil when point is between matches of START-RE and END-RE.
21727 Also return a non-nil value when point is on one of the matches.
21729 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21730 buffer positions. Default values are the positions of headlines
21731 surrounding the point.
21733 The functions returns a cons cell whose car (resp. cdr) is the
21734 position before START-RE (resp. after END-RE)."
21735 (save-match-data
21736 (let ((pos (point))
21737 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21738 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21739 beg end)
21740 (save-excursion
21741 ;; Point is on a block when on START-RE or if START-RE can be
21742 ;; found before it...
21743 (and (or (org-at-regexp-p start-re)
21744 (re-search-backward start-re limit-up t))
21745 (setq beg (match-beginning 0))
21746 ;; ... and END-RE after it...
21747 (goto-char (match-end 0))
21748 (re-search-forward end-re limit-down t)
21749 (> (setq end (match-end 0)) pos)
21750 ;; ... without another START-RE in-between.
21751 (goto-char (match-beginning 0))
21752 (not (re-search-backward start-re (1+ beg) t))
21753 ;; Return value.
21754 (cons beg end))))))
21756 (defun org-in-block-p (names)
21757 "Non-nil when point belongs to a block whose name belongs to NAMES.
21759 NAMES is a list of strings containing names of blocks.
21761 Return first block name matched, or nil. Beware that in case of
21762 nested blocks, the returned name may not belong to the closest
21763 block from point."
21764 (save-match-data
21765 (catch 'exit
21766 (let ((case-fold-search t)
21767 (lim-up (save-excursion (outline-previous-heading)))
21768 (lim-down (save-excursion (outline-next-heading))))
21769 (mapc (lambda (name)
21770 (let ((n (regexp-quote name)))
21771 (when (org-between-regexps-p
21772 (concat "^[ \t]*#\\+begin_" n)
21773 (concat "^[ \t]*#\\+end_" n)
21774 lim-up lim-down)
21775 (throw 'exit n))))
21776 names))
21777 nil)))
21779 (defun org-in-drawer-p ()
21780 "Is point within a drawer?"
21781 (save-match-data
21782 (let ((case-fold-search t)
21783 (lim-up (save-excursion (outline-previous-heading)))
21784 (lim-down (save-excursion (outline-next-heading))))
21785 (org-between-regexps-p
21786 (concat "^[ \t]*:" (regexp-opt org-drawers) ":")
21787 "^[ \t]*:end:.*$"
21788 lim-up lim-down))))
21790 (defun org-occur-in-agenda-files (regexp &optional nlines)
21791 "Call `multi-occur' with buffers for all agenda files."
21792 (interactive "sOrg-files matching: \np")
21793 (let* ((files (org-agenda-files))
21794 (tnames (mapcar 'file-truename files))
21795 (extra org-agenda-text-search-extra-files)
21797 (when (eq (car extra) 'agenda-archives)
21798 (setq extra (cdr extra))
21799 (setq files (org-add-archive-files files)))
21800 (while (setq f (pop extra))
21801 (unless (member (file-truename f) tnames)
21802 (add-to-list 'files f 'append)
21803 (add-to-list 'tnames (file-truename f) 'append)))
21804 (multi-occur
21805 (mapcar (lambda (x)
21806 (with-current-buffer
21807 (or (get-file-buffer x) (find-file-noselect x))
21808 (widen)
21809 (current-buffer)))
21810 files)
21811 regexp)))
21813 (if (boundp 'occur-mode-find-occurrence-hook)
21814 ;; Emacs 23
21815 (add-hook 'occur-mode-find-occurrence-hook
21816 (lambda ()
21817 (when (derived-mode-p 'org-mode)
21818 (org-reveal))))
21819 ;; Emacs 22
21820 (defadvice occur-mode-goto-occurrence
21821 (after org-occur-reveal activate)
21822 (and (derived-mode-p 'org-mode) (org-reveal)))
21823 (defadvice occur-mode-goto-occurrence-other-window
21824 (after org-occur-reveal activate)
21825 (and (derived-mode-p 'org-mode) (org-reveal)))
21826 (defadvice occur-mode-display-occurrence
21827 (after org-occur-reveal activate)
21828 (when (derived-mode-p 'org-mode)
21829 (let ((pos (occur-mode-find-occurrence)))
21830 (with-current-buffer (marker-buffer pos)
21831 (save-excursion
21832 (goto-char pos)
21833 (org-reveal)))))))
21835 (defun org-occur-link-in-agenda-files ()
21836 "Create a link and search for it in the agendas.
21837 The link is not stored in `org-stored-links', it is just created
21838 for the search purpose."
21839 (interactive)
21840 (let ((link (condition-case nil
21841 (org-store-link nil)
21842 (error "Unable to create a link to here"))))
21843 (org-occur-in-agenda-files (regexp-quote link))))
21845 (defun org-reverse-string (string)
21846 "Return the reverse of STRING."
21847 (apply 'string (reverse (string-to-list string))))
21849 ;; defsubst org-uniquify must be defined before first use
21851 (defun org-uniquify-alist (alist)
21852 "Merge elements of ALIST with the same key.
21854 For example, in this alist:
21856 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
21857 => '((a 1 3) (b 2))
21859 merge (a 1) and (a 3) into (a 1 3).
21861 The function returns the new ALIST."
21862 (let (rtn)
21863 (mapc
21864 (lambda (e)
21865 (let (n)
21866 (if (not (assoc (car e) rtn))
21867 (push e rtn)
21868 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
21869 (setq rtn (assq-delete-all (car e) rtn))
21870 (push n rtn))))
21871 alist)
21872 rtn))
21874 (defun org-delete-all (elts list)
21875 "Remove all elements in ELTS from LIST."
21876 (while elts
21877 (setq list (delete (pop elts) list)))
21878 list)
21880 (defun org-count (cl-item cl-seq)
21881 "Count the number of occurrences of ITEM in SEQ.
21882 Taken from `count' in cl-seq.el with all keyword arguments removed."
21883 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21884 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21885 (while (< cl-start cl-end)
21886 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21887 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21888 (setq cl-start (1+ cl-start)))
21889 cl-count))
21891 (defun org-remove-if (predicate seq)
21892 "Remove everything from SEQ that fulfills PREDICATE."
21893 (let (res e)
21894 (while seq
21895 (setq e (pop seq))
21896 (if (not (funcall predicate e)) (push e res)))
21897 (nreverse res)))
21899 (defun org-remove-if-not (predicate seq)
21900 "Remove everything from SEQ that does not fulfill PREDICATE."
21901 (let (res e)
21902 (while seq
21903 (setq e (pop seq))
21904 (if (funcall predicate e) (push e res)))
21905 (nreverse res)))
21907 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21908 "Reduce two-argument FUNCTION across SEQ.
21909 Taken from `reduce' in cl-seq.el with all keyword arguments but
21910 \":initial-value\" removed."
21911 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21912 (cadr (memq :initial-value cl-keys)))
21913 (cl-seq (pop cl-seq))
21914 (t (funcall cl-func)))))
21915 (while cl-seq
21916 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21917 cl-accum))
21919 (defun org-every (pred seq)
21920 "Return true if PREDICATE is true of every element of SEQ.
21921 Adapted from `every' in cl.el."
21922 (catch 'org-every
21923 (mapc (lambda (e) (unless (funcall pred e) (throw 'org-every nil))) seq)
21926 (defun org-some (pred seq)
21927 "Return true if PREDICATE is true of any element of SEQ.
21928 Adapted from `some' in cl.el."
21929 (catch 'org-some
21930 (mapc (lambda (e) (when (funcall pred e) (throw 'org-some t))) seq)
21931 nil))
21933 (defun org-back-over-empty-lines ()
21934 "Move backwards over whitespace, to the beginning of the first empty line.
21935 Returns the number of empty lines passed."
21936 (let ((pos (point)))
21937 (if (cdr (assoc 'heading org-blank-before-new-entry))
21938 (skip-chars-backward " \t\n\r")
21939 (unless (eobp)
21940 (forward-line -1)))
21941 (beginning-of-line 2)
21942 (goto-char (min (point) pos))
21943 (count-lines (point) pos)))
21945 (defun org-skip-whitespace ()
21946 (skip-chars-forward " \t\n\r"))
21948 (defun org-point-in-group (point group &optional context)
21949 "Check if POINT is in match-group GROUP.
21950 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21951 match. If the match group does not exist or point is not inside it,
21952 return nil."
21953 (and (match-beginning group)
21954 (>= point (match-beginning group))
21955 (<= point (match-end group))
21956 (if context
21957 (list context (match-beginning group) (match-end group))
21958 t)))
21960 (defun org-switch-to-buffer-other-window (&rest args)
21961 "Switch to buffer in a second window on the current frame.
21962 In particular, do not allow pop-up frames.
21963 Returns the newly created buffer."
21964 (org-no-popups
21965 (apply 'switch-to-buffer-other-window args)))
21967 (defun org-combine-plists (&rest plists)
21968 "Create a single property list from all plists in PLISTS.
21969 The process starts by copying the first list, and then setting properties
21970 from the other lists. Settings in the last list are the most significant
21971 ones and overrule settings in the other lists."
21972 (let ((rtn (copy-sequence (pop plists)))
21973 p v ls)
21974 (while plists
21975 (setq ls (pop plists))
21976 (while ls
21977 (setq p (pop ls) v (pop ls))
21978 (setq rtn (plist-put rtn p v))))
21979 rtn))
21981 (defun org-replace-escapes (string table)
21982 "Replace %-escapes in STRING with values in TABLE.
21983 TABLE is an association list with keys like \"%a\" and string values.
21984 The sequences in STRING may contain normal field width and padding information,
21985 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21986 so values can contain further %-escapes if they are define later in TABLE."
21987 (let ((tbl (copy-alist table))
21988 (case-fold-search nil)
21989 (pchg 0)
21990 e re rpl)
21991 (while (setq e (pop tbl))
21992 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21993 (when (and (cdr e) (string-match re (cdr e)))
21994 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21995 (safe "SREF"))
21996 (add-text-properties 0 3 (list 'sref sref) safe)
21997 (setcdr e (replace-match safe t t (cdr e)))))
21998 (while (string-match re string)
21999 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22000 (cdr e)))
22001 (setq string (replace-match rpl t t string))))
22002 (while (setq pchg (next-property-change pchg string))
22003 (let ((sref (get-text-property pchg 'sref string)))
22004 (when (and sref (string-match "SREF" string pchg))
22005 (setq string (replace-match sref t t string)))))
22006 string))
22008 (defun org-sublist (list start end)
22009 "Return a section of LIST, from START to END.
22010 Counting starts at 1."
22011 (let (rtn (c start))
22012 (setq list (nthcdr (1- start) list))
22013 (while (and list (<= c end))
22014 (push (pop list) rtn)
22015 (setq c (1+ c)))
22016 (nreverse rtn)))
22018 (defun org-find-base-buffer-visiting (file)
22019 "Like `find-buffer-visiting' but always return the base buffer and
22020 not an indirect buffer."
22021 (let ((buf (or (get-file-buffer file)
22022 (find-buffer-visiting file))))
22023 (if buf
22024 (or (buffer-base-buffer buf) buf)
22025 nil)))
22027 (defun org-image-file-name-regexp (&optional extensions)
22028 "Return regexp matching the file names of images.
22029 If EXTENSIONS is given, only match these."
22030 (if (and (not extensions) (fboundp 'image-file-name-regexp))
22031 (image-file-name-regexp)
22032 (let ((image-file-name-extensions
22033 (or extensions
22034 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
22035 "xbm" "xpm" "pbm" "pgm" "ppm"))))
22036 (concat "\\."
22037 (regexp-opt (nconc (mapcar 'upcase
22038 image-file-name-extensions)
22039 image-file-name-extensions)
22041 "\\'"))))
22043 (defun org-file-image-p (file &optional extensions)
22044 "Return non-nil if FILE is an image."
22045 (save-match-data
22046 (string-match (org-image-file-name-regexp extensions) file)))
22048 (defun org-get-cursor-date (&optional with-time)
22049 "Return the date at cursor in as a time.
22050 This works in the calendar and in the agenda, anywhere else it just
22051 returns the current time.
22052 If WITH-TIME is non-nil, returns the time of the event at point (in
22053 the agenda) or the current time of the day."
22054 (let (date day defd tp tm hod mod)
22055 (when with-time
22056 (setq tp (get-text-property (point) 'time))
22057 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22058 (setq hod (string-to-number (match-string 1 tp))
22059 mod (string-to-number (match-string 2 tp))))
22060 (or tp (setq hod (nth 2 (decode-time (current-time)))
22061 mod (nth 1 (decode-time (current-time))))))
22062 (cond
22063 ((eq major-mode 'calendar-mode)
22064 (setq date (calendar-cursor-to-date)
22065 defd (encode-time 0 (or mod 0) (or hod 0)
22066 (nth 1 date) (nth 0 date) (nth 2 date))))
22067 ((eq major-mode 'org-agenda-mode)
22068 (setq day (get-text-property (point) 'day))
22069 (if day
22070 (setq date (calendar-gregorian-from-absolute day)
22071 defd (encode-time 0 (or mod 0) (or hod 0)
22072 (nth 1 date) (nth 0 date) (nth 2 date))))))
22073 (or defd (current-time))))
22075 (defun org-mark-subtree (&optional up)
22076 "Mark the current subtree.
22077 This puts point at the start of the current subtree, and mark at
22078 the end. If a numeric prefix UP is given, move up into the
22079 hierarchy of headlines by UP levels before marking the subtree."
22080 (interactive "P")
22081 (org-with-limited-levels
22082 (cond ((org-at-heading-p) (beginning-of-line))
22083 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22084 (t (outline-previous-visible-heading 1))))
22085 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
22086 (if (org-called-interactively-p 'any)
22087 (call-interactively 'org-mark-element)
22088 (org-mark-element)))
22091 ;;; Indentation
22093 (defun org-indent-line ()
22094 "Indent line depending on context."
22095 (interactive)
22096 (let* ((pos (point))
22097 (itemp (org-at-item-p))
22098 (case-fold-search t)
22099 (org-drawer-regexp (or org-drawer-regexp "\000"))
22100 (inline-task-p (and (featurep 'org-inlinetask)
22101 (org-inlinetask-in-task-p)))
22102 (inline-re (and inline-task-p
22103 (org-inlinetask-outline-regexp)))
22104 column)
22105 (if (and orgstruct-is-++ (eq pos (point)))
22106 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
22107 (indent-according-to-mode))
22108 (beginning-of-line 1)
22109 (cond
22110 ;; Headings
22111 ((looking-at org-outline-regexp) (setq column 0))
22112 ;; Footnote definition
22113 ((looking-at org-footnote-definition-re) (setq column 0))
22114 ;; Literal examples
22115 ((looking-at "[ \t]*:\\( \\|$\\)")
22116 (setq column (org-get-indentation))) ; do nothing
22117 ;; Lists
22118 ((ignore-errors (goto-char (org-in-item-p)))
22119 (setq column (if itemp
22120 (org-get-indentation)
22121 (org-list-item-body-column (point))))
22122 (goto-char pos))
22123 ;; Drawers
22124 ((and (looking-at "[ \t]*:END:")
22125 (save-excursion (re-search-backward org-drawer-regexp nil t)))
22126 (save-excursion
22127 (goto-char (1- (match-beginning 1)))
22128 (setq column (current-column))))
22129 ;; Special blocks
22130 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
22131 (save-excursion
22132 (re-search-backward
22133 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
22134 (setq column (org-get-indentation (match-string 0))))
22135 ((and (not (looking-at "[ \t]*#\\+begin_"))
22136 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
22137 (save-excursion
22138 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
22139 (setq column
22140 (cond ((equal (downcase (match-string 1)) "src")
22141 ;; src blocks: let `org-edit-src-exit' handle them
22142 (org-get-indentation))
22143 ((equal (downcase (match-string 1)) "example")
22144 (max (org-get-indentation)
22145 (org-get-indentation (match-string 0))))
22147 (org-get-indentation (match-string 0))))))
22148 ;; This line has nothing special, look at the previous relevant
22149 ;; line to compute indentation
22151 (beginning-of-line 0)
22152 (while (and (not (bobp))
22153 (not (looking-at org-table-line-regexp))
22154 (not (looking-at org-drawer-regexp))
22155 ;; When point started in an inline task, do not move
22156 ;; above task starting line.
22157 (not (and inline-task-p (looking-at inline-re)))
22158 ;; Skip drawers, blocks, empty lines, verbatim,
22159 ;; comments, tables, footnotes definitions, lists,
22160 ;; inline tasks.
22161 (or (and (looking-at "[ \t]*:END:")
22162 (re-search-backward org-drawer-regexp nil t))
22163 (and (looking-at "[ \t]*#\\+end_")
22164 (re-search-backward "[ \t]*#\\+begin_"nil t))
22165 (looking-at "[ \t]*[\n:#|]")
22166 (looking-at org-footnote-definition-re)
22167 (and (not inline-task-p)
22168 (featurep 'org-inlinetask)
22169 (org-inlinetask-in-task-p)
22170 (or (org-inlinetask-goto-beginning) t))))
22171 (beginning-of-line 0))
22172 (cond
22173 ;; There was a list item above.
22174 ((ignore-errors (goto-char (org-in-item-p)))
22175 (goto-char (org-list-get-top-point (org-list-struct)))
22176 (setq column (org-get-indentation)))
22177 ;; There was an heading above.
22178 ((looking-at "\\*+[ \t]+")
22179 (if (not org-adapt-indentation)
22180 (setq column 0)
22181 (goto-char (match-end 0))
22182 (setq column (current-column))))
22183 ;; A drawer had started and is unfinished
22184 ((looking-at org-drawer-regexp)
22185 (goto-char (1- (match-beginning 1)))
22186 (setq column (current-column)))
22187 ;; Else, nothing noticeable found: get indentation and go on.
22188 (t (setq column (org-get-indentation))))))
22189 ;; Now apply indentation and move cursor accordingly
22190 (goto-char pos)
22191 (if (<= (current-column) (current-indentation))
22192 (org-indent-line-to column)
22193 (save-excursion (org-indent-line-to column)))
22194 ;; Special polishing for properties, see `org-property-format'
22195 (setq column (current-column))
22196 (beginning-of-line 1)
22197 (if (looking-at org-property-re)
22198 (replace-match (concat (match-string 4)
22199 (format org-property-format
22200 (match-string 1) (match-string 3)))
22201 t t))
22202 (org-move-to-column column))))
22204 (defun org-indent-drawer ()
22205 "Indent the drawer at point."
22206 (interactive)
22207 (let ((p (point))
22208 (e (and (save-excursion (re-search-forward ":END:" nil t))
22209 (match-end 0)))
22210 (folded
22211 (save-excursion
22212 (end-of-line)
22213 (when (overlays-at (point))
22214 (member 'invisible (overlay-properties
22215 (car (overlays-at (point)))))))))
22216 (when folded (org-cycle))
22217 (indent-for-tab-command)
22218 (while (and (move-beginning-of-line 2) (< (point) e))
22219 (indent-for-tab-command))
22220 (goto-char p)
22221 (when folded (org-cycle)))
22222 (message "Drawer at point indented"))
22224 (defun org-indent-block ()
22225 "Indent the block at point."
22226 (interactive)
22227 (let ((p (point))
22228 (case-fold-search t)
22229 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
22230 (match-end 0)))
22231 (folded
22232 (save-excursion
22233 (end-of-line)
22234 (when (overlays-at (point))
22235 (member 'invisible (overlay-properties
22236 (car (overlays-at (point)))))))))
22237 (when folded (org-cycle))
22238 (indent-for-tab-command)
22239 (while (and (move-beginning-of-line 2) (< (point) e))
22240 (indent-for-tab-command))
22241 (goto-char p)
22242 (when folded (org-cycle)))
22243 (message "Block at point indented"))
22245 (defun org-indent-region (start end)
22246 "Indent region."
22247 (interactive "r")
22248 (save-excursion
22249 (let ((line-end (org-current-line end)))
22250 (goto-char start)
22251 (while (< (org-current-line) line-end)
22252 (cond ((org-in-src-block-p t) (org-src-native-tab-command-maybe))
22253 (t (call-interactively 'org-indent-line)))
22254 (move-beginning-of-line 2)))))
22257 ;;; Filling
22259 ;; We use our own fill-paragraph and auto-fill functions.
22261 ;; `org-fill-paragraph' relies on adaptive filling and context
22262 ;; checking. Appropriate `fill-prefix' is computed with
22263 ;; `org-adaptive-fill-function'.
22265 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22266 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22267 ;; `org-adaptive-fill-function' value. Internally,
22268 ;; `org-comment-line-break-function' breaks the line.
22270 ;; `org-setup-filling' installs filling and auto-filling related
22271 ;; variables during `org-mode' initialization.
22273 (defvar org-element-paragraph-separate) ; org-element.el
22274 (defun org-setup-filling ()
22275 (require 'org-element)
22276 ;; Prevent auto-fill from inserting unwanted new items.
22277 (when (boundp 'fill-nobreak-predicate)
22278 (org-set-local
22279 'fill-nobreak-predicate
22280 (org-uniquify
22281 (append fill-nobreak-predicate
22282 '(org-fill-line-break-nobreak-p
22283 org-fill-paragraph-with-timestamp-nobreak-p)))))
22284 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22285 (org-set-local 'paragraph-start paragraph-ending)
22286 (org-set-local 'paragraph-separate paragraph-ending))
22287 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22288 (org-set-local 'auto-fill-inhibit-regexp nil)
22289 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22290 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22291 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22293 (defun org-fill-line-break-nobreak-p ()
22294 "Non-nil when a new line at point would create an Org line break."
22295 (save-excursion
22296 (skip-chars-backward "[ \t]")
22297 (skip-chars-backward "\\\\")
22298 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22300 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22301 "Non-nil when a new line at point would split a timestamp."
22302 (and (org-at-timestamp-p t)
22303 (not (looking-at org-ts-regexp-both))))
22305 (declare-function message-in-body-p "message" ())
22306 (defvar orgtbl-line-start-regexp) ; From org-table.el
22307 (defun org-adaptive-fill-function ()
22308 "Compute a fill prefix for the current line.
22309 Return fill prefix, as a string, or nil if current line isn't
22310 meant to be filled. For convenience, if `adaptive-fill-regexp'
22311 matches in paragraphs or comments, use it."
22312 (catch 'exit
22313 (when (derived-mode-p 'message-mode)
22314 (save-excursion
22315 (beginning-of-line)
22316 (cond ((or (not (message-in-body-p))
22317 (looking-at orgtbl-line-start-regexp))
22318 (throw 'exit nil))
22319 ((looking-at message-cite-prefix-regexp)
22320 (throw 'exit (match-string-no-properties 0)))
22321 ((looking-at org-outline-regexp)
22322 (throw 'exit (make-string (length (match-string 0)) ? ))))))
22323 (org-with-wide-buffer
22324 (let* ((p (line-beginning-position))
22325 (element (save-excursion
22326 (beginning-of-line)
22327 (or (ignore-errors (org-element-at-point))
22328 (user-error "An element cannot be parsed line %d"
22329 (line-number-at-pos (point))))))
22330 (type (org-element-type element))
22331 (post-affiliated (org-element-property :post-affiliated element)))
22332 (unless (and post-affiliated (< p post-affiliated))
22333 (case type
22334 (comment
22335 (save-excursion
22336 (beginning-of-line)
22337 (looking-at "[ \t]*")
22338 (concat (match-string 0) "# ")))
22339 (footnote-definition "")
22340 ((item plain-list)
22341 (make-string (org-list-item-body-column
22342 (or post-affiliated
22343 (org-element-property :begin element)))
22344 ? ))
22345 (paragraph
22346 ;; Fill prefix is usually the same as the current line,
22347 ;; unless the paragraph is at the beginning of an item.
22348 (let ((parent (org-element-property :parent element)))
22349 (save-excursion
22350 (beginning-of-line)
22351 (cond ((eq (org-element-type parent) 'item)
22352 (make-string (org-list-item-body-column
22353 (org-element-property :begin parent))
22354 ? ))
22355 ((and adaptive-fill-regexp
22356 ;; Locally disable
22357 ;; `adaptive-fill-function' to let
22358 ;; `fill-context-prefix' handle
22359 ;; `adaptive-fill-regexp' variable.
22360 (let (adaptive-fill-function)
22361 (fill-context-prefix
22362 post-affiliated
22363 (org-element-property :end element)))))
22364 ((looking-at "[ \t]+") (match-string 0))
22365 (t "")))))
22366 (comment-block
22367 ;; Only fill contents if P is within block boundaries.
22368 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22369 (forward-line)
22370 (point)))
22371 (cend (save-excursion
22372 (goto-char (org-element-property :end element))
22373 (skip-chars-backward " \r\t\n")
22374 (line-beginning-position))))
22375 (when (and (>= p cbeg) (< p cend))
22376 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22377 (match-string 0)
22378 ""))))))))))
22380 (declare-function message-goto-body "message" ())
22381 (defvar message-cite-prefix-regexp) ; From message.el
22382 (defun org-fill-paragraph (&optional justify)
22383 "Fill element at point, when applicable.
22385 This function only applies to comment blocks, comments, example
22386 blocks and paragraphs. Also, as a special case, re-align table
22387 when point is at one.
22389 If JUSTIFY is non-nil (interactively, with prefix argument),
22390 justify as well. If `sentence-end-double-space' is non-nil, then
22391 period followed by one space does not end a sentence, so don't
22392 break a line there. The variable `fill-column' controls the
22393 width for filling.
22395 For convenience, when point is at a plain list, an item or
22396 a footnote definition, try to fill the first paragraph within."
22397 (interactive)
22398 (if (and (derived-mode-p 'message-mode)
22399 (or (not (message-in-body-p))
22400 (save-excursion (move-beginning-of-line 1)
22401 (looking-at message-cite-prefix-regexp))))
22402 ;; First ensure filling is correct in message-mode.
22403 (let ((fill-paragraph-function
22404 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22405 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22406 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22407 (paragraph-separate
22408 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22409 (fill-paragraph nil))
22410 (with-syntax-table org-mode-transpose-word-syntax-table
22411 ;; Move to end of line in order to get the first paragraph
22412 ;; within a plain list or a footnote definition.
22413 (let ((element (save-excursion
22414 (end-of-line)
22415 (or (ignore-errors (org-element-at-point))
22416 (user-error "An element cannot be parsed line %d"
22417 (line-number-at-pos (point)))))))
22418 ;; First check if point is in a blank line at the beginning of
22419 ;; the buffer. In that case, ignore filling.
22420 (case (org-element-type element)
22421 ;; Use major mode filling function is src blocks.
22422 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22423 ;; Align Org tables, leave table.el tables as-is.
22424 (table-row (org-table-align) t)
22425 (table
22426 (when (eq (org-element-property :type element) 'org)
22427 (save-excursion
22428 (goto-char (org-element-property :post-affiliated element))
22429 (org-table-align)))
22431 (paragraph
22432 ;; Paragraphs may contain `line-break' type objects.
22433 (let ((beg (max (point-min)
22434 (org-element-property :contents-begin element)))
22435 (end (min (point-max)
22436 (org-element-property :contents-end element))))
22437 ;; Do nothing if point is at an affiliated keyword.
22438 (if (< (line-end-position) beg) t
22439 (when (derived-mode-p 'message-mode)
22440 ;; In `message-mode', do not fill following citation
22441 ;; in current paragraph nor text before message body.
22442 (let ((body-start (save-excursion (message-goto-body))))
22443 (when body-start (setq beg (max body-start beg))))
22444 (when (save-excursion
22445 (re-search-forward
22446 (concat "^" message-cite-prefix-regexp) end t))
22447 (setq end (match-beginning 0))))
22448 ;; Fill paragraph, taking line breaks into account.
22449 ;; For that, slice the paragraph using line breaks as
22450 ;; separators, and fill the parts in reverse order to
22451 ;; avoid messing with markers.
22452 (save-excursion
22453 (goto-char end)
22454 (mapc
22455 (lambda (pos)
22456 (fill-region-as-paragraph pos (point) justify)
22457 (goto-char pos))
22458 ;; Find the list of ending positions for line breaks
22459 ;; in the current paragraph. Add paragraph
22460 ;; beginning to include first slice.
22461 (nreverse
22462 (cons beg
22463 (org-element-map
22464 (org-element--parse-objects
22465 beg end nil (org-element-restriction 'paragraph))
22466 'line-break
22467 (lambda (lb) (org-element-property :end lb)))))))
22468 t)))
22469 ;; Contents of `comment-block' type elements should be
22470 ;; filled as plain text, but only if point is within block
22471 ;; markers.
22472 (comment-block
22473 (let* ((case-fold-search t)
22474 (beg (save-excursion
22475 (goto-char (org-element-property :begin element))
22476 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22477 (forward-line)
22478 (point)))
22479 (end (save-excursion
22480 (goto-char (org-element-property :end element))
22481 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22482 (line-beginning-position))))
22483 (if (or (< (point) beg) (> (point) end)) t
22484 (fill-region-as-paragraph
22485 (save-excursion (end-of-line)
22486 (re-search-backward "^[ \t]*$" beg 'move)
22487 (line-beginning-position))
22488 (save-excursion (beginning-of-line)
22489 (re-search-forward "^[ \t]*$" end 'move)
22490 (line-beginning-position))
22491 justify))))
22492 ;; Fill comments.
22493 (comment
22494 (let ((begin (org-element-property :post-affiliated element))
22495 (end (org-element-property :end element)))
22496 (when (and (>= (point) begin) (<= (point) end))
22497 (let ((begin (save-excursion
22498 (end-of-line)
22499 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22500 (progn (forward-line) (point))
22501 begin)))
22502 (end (save-excursion
22503 (end-of-line)
22504 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22505 (1- (line-beginning-position))
22506 (skip-chars-backward " \r\t\n")
22507 (line-end-position)))))
22508 ;; Do not fill comments when at a blank line.
22509 (when (> end begin)
22510 (let ((fill-prefix
22511 (save-excursion
22512 (beginning-of-line)
22513 (looking-at "[ \t]*#")
22514 (let ((comment-prefix (match-string 0)))
22515 (goto-char (match-end 0))
22516 (if (looking-at adaptive-fill-regexp)
22517 (concat comment-prefix (match-string 0))
22518 (concat comment-prefix " "))))))
22519 (save-excursion
22520 (fill-region-as-paragraph begin end justify))))))
22522 ;; Ignore every other element.
22523 (otherwise t))))))
22525 (defun org-auto-fill-function ()
22526 "Auto-fill function."
22527 ;; Check if auto-filling is meaningful.
22528 (let ((fc (current-fill-column)))
22529 (when (and fc (> (current-column) fc))
22530 (let* ((fill-prefix (org-adaptive-fill-function))
22531 ;; Enforce empty fill prefix, if required. Otherwise, it
22532 ;; will be computed again.
22533 (adaptive-fill-mode (not (equal fill-prefix ""))))
22534 (when fill-prefix (do-auto-fill))))))
22536 (defun org-comment-line-break-function (&optional soft)
22537 "Break line at point and indent, continuing comment if within one.
22538 The inserted newline is marked hard if variable
22539 `use-hard-newlines' is true, unless optional argument SOFT is
22540 non-nil."
22541 (if soft (insert-and-inherit ?\n) (newline 1))
22542 (save-excursion (forward-char -1) (delete-horizontal-space))
22543 (delete-horizontal-space)
22544 (indent-to-left-margin)
22545 (insert-before-markers-and-inherit fill-prefix))
22548 ;;; Comments
22550 ;; Org comments syntax is quite complex. It requires the entire line
22551 ;; to be just a comment. Also, even with the right syntax at the
22552 ;; beginning of line, some some elements (i.e. verse-block or
22553 ;; example-block) don't accept comments. Usual Emacs comment commands
22554 ;; cannot cope with those requirements. Therefore, Org replaces them.
22556 ;; Org still relies on `comment-dwim', but cannot trust
22557 ;; `comment-only-p'. So, `comment-region-function' and
22558 ;; `uncomment-region-function' both point
22559 ;; to`org-comment-or-uncomment-region'. Eventually,
22560 ;; `org-insert-comment' takes care of insertion of comments at the
22561 ;; beginning of line.
22563 ;; `org-setup-comments-handling' install comments related variables
22564 ;; during `org-mode' initialization.
22566 (defun org-setup-comments-handling ()
22567 (interactive)
22568 (org-set-local 'comment-use-syntax nil)
22569 (org-set-local 'comment-start "# ")
22570 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22571 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22572 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22573 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22575 (defun org-insert-comment ()
22576 "Insert an empty comment above current line.
22577 If the line is empty, insert comment at its beginning."
22578 (beginning-of-line)
22579 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
22580 (org-indent-line)
22581 (insert "# "))
22583 (defvar comment-empty-lines) ; From newcomment.el.
22584 (defun org-comment-or-uncomment-region (beg end &rest ignore)
22585 "Comment or uncomment each non-blank line in the region.
22586 Uncomment each non-blank line between BEG and END if it only
22587 contains commented lines. Otherwise, comment them."
22588 (save-restriction
22589 ;; Restrict region
22590 (narrow-to-region (save-excursion (goto-char beg)
22591 (skip-chars-forward " \r\t\n" end)
22592 (line-beginning-position))
22593 (save-excursion (goto-char end)
22594 (skip-chars-backward " \r\t\n" beg)
22595 (line-end-position)))
22596 (let ((uncommentp
22597 ;; UNCOMMENTP is non-nil when every non blank line between
22598 ;; BEG and END is a comment.
22599 (save-excursion
22600 (goto-char (point-min))
22601 (while (and (not (eobp))
22602 (let ((element (org-element-at-point)))
22603 (and (eq (org-element-type element) 'comment)
22604 (goto-char (min (point-max)
22605 (org-element-property
22606 :end element)))))))
22607 (eobp))))
22608 (if uncommentp
22609 ;; Only blank lines and comments in region: uncomment it.
22610 (save-excursion
22611 (goto-char (point-min))
22612 (while (not (eobp))
22613 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22614 (replace-match "" nil nil nil 1))
22615 (forward-line)))
22616 ;; Comment each line in region.
22617 (let ((min-indent (point-max)))
22618 ;; First find the minimum indentation across all lines.
22619 (save-excursion
22620 (goto-char (point-min))
22621 (while (and (not (eobp)) (not (zerop min-indent)))
22622 (unless (looking-at "[ \t]*$")
22623 (setq min-indent (min min-indent (current-indentation))))
22624 (forward-line)))
22625 ;; Then loop over all lines.
22626 (save-excursion
22627 (goto-char (point-min))
22628 (while (not (eobp))
22629 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22630 ;; Don't get fooled by invisible text (e.g. link path)
22631 ;; when moving to column MIN-INDENT.
22632 (let ((buffer-invisibility-spec nil))
22633 (org-move-to-column min-indent t))
22634 (insert comment-start))
22635 (forward-line))))))))
22638 ;;; Planning
22640 ;; This section contains tools to operate on timestamp objects, as
22641 ;; returned by, e.g. `org-element-context'.
22643 (defun org-timestamp-has-time-p (timestamp)
22644 "Non-nil when TIMESTAMP has a time specified."
22645 (org-element-property :hour-start timestamp))
22647 (defun org-timestamp-format (timestamp format &optional end utc)
22648 "Format a TIMESTAMP element into a string.
22650 FORMAT is a format specifier to be passed to
22651 `format-time-string'.
22653 When optional argument END is non-nil, use end of date-range or
22654 time-range, if possible.
22656 When optional argument UTC is non-nil, time will be expressed as
22657 Universal Time."
22658 (format-time-string
22659 format
22660 (apply 'encode-time
22661 (cons 0
22662 (mapcar
22663 (lambda (prop) (or (org-element-property prop timestamp) 0))
22664 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22665 '(:minute-start :hour-start :day-start :month-start
22666 :year-start)))))
22667 utc))
22669 (defun org-timestamp-split-range (timestamp &optional end)
22670 "Extract a timestamp object from a date or time range.
22672 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22673 the end of the range. Otherwise, extract its start.
22675 Return a new timestamp object sharing the same parent as
22676 TIMESTAMP."
22677 (let ((type (org-element-property :type timestamp)))
22678 (if (memq type '(active inactive diary)) timestamp
22679 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22680 ;; Set new type.
22681 (org-element-put-property
22682 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22683 ;; Copy start properties over end properties if END is
22684 ;; non-nil. Otherwise, copy end properties over `start' ones.
22685 (let ((p-alist '((:minute-start . :minute-end)
22686 (:hour-start . :hour-end)
22687 (:day-start . :day-end)
22688 (:month-start . :month-end)
22689 (:year-start . :year-end))))
22690 (dolist (p-cell p-alist)
22691 (org-element-put-property
22692 split-ts
22693 (funcall (if end 'car 'cdr) p-cell)
22694 (org-element-property
22695 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22696 ;; Eventually refresh `:raw-value'.
22697 (org-element-put-property split-ts :raw-value nil)
22698 (org-element-put-property
22699 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22701 (defun org-timestamp-translate (timestamp &optional boundary)
22702 "Apply `org-translate-time' on a TIMESTAMP object.
22703 When optional argument BOUNDARY is non-nil, it is either the
22704 symbol `start' or `end'. In this case, only translate the
22705 starting or ending part of TIMESTAMP if it is a date or time
22706 range. Otherwise, translate both parts."
22707 (if (and (not boundary)
22708 (memq (org-element-property :type timestamp)
22709 '(active-range inactive-range)))
22710 (concat
22711 (org-translate-time
22712 (org-element-property :raw-value
22713 (org-timestamp-split-range timestamp)))
22714 "--"
22715 (org-translate-time
22716 (org-element-property :raw-value
22717 (org-timestamp-split-range timestamp t))))
22718 (org-translate-time
22719 (org-element-property
22720 :raw-value
22721 (if (not boundary) timestamp
22722 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22726 ;;; Other stuff.
22728 (defun org-toggle-fixed-width-section (arg)
22729 "Toggle the fixed-width export.
22730 If there is no active region, the QUOTE keyword at the current headline is
22731 inserted or removed. When present, it causes the text between this headline
22732 and the next to be exported as fixed-width text, and unmodified.
22733 If there is an active region, this command adds or removes a colon as the
22734 first character of this line. If the first character of a line is a colon,
22735 this line is also exported in fixed-width font."
22736 (interactive "P")
22737 (let* ((cc 0)
22738 (regionp (org-region-active-p))
22739 (beg (if regionp (region-beginning) (point)))
22740 (end (if regionp (region-end)))
22741 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22742 (case-fold-search nil)
22743 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22744 off)
22745 (if regionp
22746 (save-excursion
22747 (goto-char beg)
22748 (setq cc (current-column))
22749 (beginning-of-line 1)
22750 (setq off (looking-at re))
22751 (while (> nlines 0)
22752 (setq nlines (1- nlines))
22753 (beginning-of-line 1)
22754 (cond
22755 (arg
22756 (org-move-to-column cc t)
22757 (insert ": \n")
22758 (forward-line -1))
22759 ((and off (looking-at re))
22760 (replace-match "" t t nil 1))
22761 ((not off) (org-move-to-column cc t) (insert ": ")))
22762 (forward-line 1)))
22763 (save-excursion
22764 (org-back-to-heading)
22765 (cond
22766 ((looking-at (format org-heading-keyword-regexp-format
22767 org-quote-string))
22768 (goto-char (match-end 1))
22769 (looking-at (concat " +" org-quote-string))
22770 (replace-match "" t t)
22771 (when (eolp) (insert " ")))
22772 ((looking-at org-outline-regexp)
22773 (goto-char (match-end 0))
22774 (insert org-quote-string " ")))))))
22776 (defun org-reftex-citation ()
22777 "Use reftex-citation to insert a citation into the buffer.
22778 This looks for a line like
22780 #+BIBLIOGRAPHY: foo plain option:-d
22782 and derives from it that foo.bib is the bibliography file relevant
22783 for this document. It then installs the necessary environment for RefTeX
22784 to work in this buffer and calls `reftex-citation' to insert a citation
22785 into the buffer.
22787 Export of such citations to both LaTeX and HTML is handled by the contributed
22788 package ox-bibtex by Taru Karttunen."
22789 (interactive)
22790 (let ((reftex-docstruct-symbol 'rds)
22791 (reftex-cite-format "\\cite{%l}")
22792 rds bib)
22793 (save-excursion
22794 (save-restriction
22795 (widen)
22796 (let ((case-fold-search t)
22797 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22798 (if (not (save-excursion
22799 (or (re-search-forward re nil t)
22800 (re-search-backward re nil t))))
22801 (error "No bibliography defined in file")
22802 (setq bib (concat (match-string 1) ".bib")
22803 rds (list (list 'bib bib)))))))
22804 (call-interactively 'reftex-citation)))
22806 ;;;; Functions extending outline functionality
22808 (defun org-beginning-of-line (&optional arg)
22809 "Go to the beginning of the current line. If that is invisible, continue
22810 to a visible line beginning. This makes the function of C-a more intuitive.
22811 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22812 first attempt, and only move to after the tags when the cursor is already
22813 beyond the end of the headline."
22814 (interactive "P")
22815 (let ((pos (point))
22816 (special (if (consp org-special-ctrl-a/e)
22817 (car org-special-ctrl-a/e)
22818 org-special-ctrl-a/e))
22819 deactivate-mark refpos)
22820 (if (org-bound-and-true-p visual-line-mode)
22821 (beginning-of-visual-line 1)
22822 (beginning-of-line 1))
22823 (if (and arg (fboundp 'move-beginning-of-line))
22824 (call-interactively 'move-beginning-of-line)
22825 (if (bobp)
22827 (backward-char 1)
22828 (if (org-truely-invisible-p)
22829 (while (and (not (bobp)) (org-truely-invisible-p))
22830 (backward-char 1)
22831 (beginning-of-line 1))
22832 (forward-char 1))))
22833 (when special
22834 (cond
22835 ((and (looking-at org-complex-heading-regexp)
22836 (= (char-after (match-end 1)) ?\ ))
22837 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22838 (point-at-eol)))
22839 (goto-char
22840 (if (eq special t)
22841 (cond ((> pos refpos) refpos)
22842 ((= pos (point)) refpos)
22843 (t (point)))
22844 (cond ((> pos (point)) (point))
22845 ((not (eq last-command this-command)) (point))
22846 (t refpos)))))
22847 ((org-at-item-p)
22848 ;; Being at an item and not looking at an the item means point
22849 ;; was previously moved to beginning of a visual line, which
22850 ;; doesn't contain the item. Therefore, do nothing special,
22851 ;; just stay here.
22852 (when (looking-at org-list-full-item-re)
22853 ;; Set special position at first white space character after
22854 ;; bullet, and check-box, if any.
22855 (let ((after-bullet
22856 (let ((box (match-end 3)))
22857 (if (not box) (match-end 1)
22858 (let ((after (char-after box)))
22859 (if (and after (= after ? )) (1+ box) box))))))
22860 ;; Special case: Move point to special position when
22861 ;; currently after it or at beginning of line.
22862 (if (eq special t)
22863 (when (or (> pos after-bullet) (= (point) pos))
22864 (goto-char after-bullet))
22865 ;; Reversed case: Move point to special position when
22866 ;; point was already at beginning of line and command is
22867 ;; repeated.
22868 (when (and (= (point) pos) (eq last-command this-command))
22869 (goto-char after-bullet))))))))
22870 (org-no-warnings
22871 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22872 (setq disable-point-adjustment
22873 (or (not (invisible-p (point)))
22874 (not (invisible-p (max (point-min) (1- (point))))))))
22876 (defun org-end-of-line (&optional arg)
22877 "Go to the end of the line.
22878 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22879 tags on the first attempt, and only move to after the tags when
22880 the cursor is already beyond the end of the headline."
22881 (interactive "P")
22882 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22883 org-special-ctrl-a/e))
22884 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22885 'end-of-visual-line)
22886 ((fboundp 'move-end-of-line) 'move-end-of-line)
22887 (t 'end-of-line)))
22888 deactivate-mark)
22889 (if (or (not special) arg) (call-interactively move-fun)
22890 (let* ((element (save-excursion (beginning-of-line)
22891 (org-element-at-point)))
22892 (type (org-element-type element)))
22893 (cond
22894 ((memq type '(headline inlinetask))
22895 (let ((pos (point)))
22896 (beginning-of-line 1)
22897 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22898 (if (eq special t)
22899 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22900 (goto-char (match-beginning 1))
22901 (goto-char (match-end 0)))
22902 (if (or (< pos (match-end 0))
22903 (not (eq this-command last-command)))
22904 (goto-char (match-end 0))
22905 (goto-char (match-beginning 1))))
22906 (call-interactively move-fun))))
22907 ((org-element-property :hiddenp element)
22908 ;; If element is hidden, `move-end-of-line' would put point
22909 ;; after it. Use `end-of-line' to stay on current line.
22910 (call-interactively 'end-of-line))
22911 (t (call-interactively move-fun)))))
22912 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22913 (setq disable-point-adjustment
22914 (or (not (invisible-p (point)))
22915 (not (invisible-p (max (point-min) (1- (point))))))))
22917 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22918 (define-key org-mode-map "\C-e" 'org-end-of-line)
22920 (defun org-backward-sentence (&optional arg)
22921 "Go to beginning of sentence, or beginning of table field.
22922 This will call `backward-sentence' or `org-table-beginning-of-field',
22923 depending on context."
22924 (interactive "P")
22925 (cond
22926 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22927 (t (call-interactively 'backward-sentence))))
22929 (defun org-forward-sentence (&optional arg)
22930 "Go to end of sentence, or end of table field.
22931 This will call `forward-sentence' or `org-table-end-of-field',
22932 depending on context."
22933 (interactive "P")
22934 (cond
22935 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22936 (t (call-interactively 'forward-sentence))))
22938 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22939 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22941 (defun org-kill-line (&optional arg)
22942 "Kill line, to tags or end of line."
22943 (interactive "P")
22944 (cond
22945 ((or (not org-special-ctrl-k)
22946 (bolp)
22947 (not (org-at-heading-p)))
22948 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22949 org-ctrl-k-protect-subtree)
22950 (if (or (eq org-ctrl-k-protect-subtree 'error)
22951 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22952 (user-error "C-k aborted as it would kill a hidden subtree")))
22953 (call-interactively
22954 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22955 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22956 (kill-region (point) (match-beginning 1))
22957 (org-set-tags nil t))
22958 (t (kill-region (point) (point-at-eol)))))
22960 (define-key org-mode-map "\C-k" 'org-kill-line)
22962 (defun org-yank (&optional arg)
22963 "Yank. If the kill is a subtree, treat it specially.
22964 This command will look at the current kill and check if is a single
22965 subtree, or a series of subtrees[1]. If it passes the test, and if the
22966 cursor is at the beginning of a line or after the stars of a currently
22967 empty headline, then the yank is handled specially. How exactly depends
22968 on the value of the following variables, both set by default.
22970 org-yank-folded-subtrees
22971 When set, the subtree(s) will be folded after insertion, but only
22972 if doing so would now swallow text after the yanked text.
22974 org-yank-adjusted-subtrees
22975 When set, the subtree will be promoted or demoted in order to
22976 fit into the local outline tree structure, which means that the level
22977 will be adjusted so that it becomes the smaller one of the two
22978 *visible* surrounding headings.
22980 Any prefix to this command will cause `yank' to be called directly with
22981 no special treatment. In particular, a simple \\[universal-argument] prefix \
22982 will just
22983 plainly yank the text as it is.
22985 \[1] The test checks if the first non-white line is a heading
22986 and if there are no other headings with fewer stars."
22987 (interactive "P")
22988 (org-yank-generic 'yank arg))
22990 (defun org-yank-generic (command arg)
22991 "Perform some yank-like command.
22993 This function implements the behavior described in the `org-yank'
22994 documentation. However, it has been generalized to work for any
22995 interactive command with similar behavior."
22997 ;; pretend to be command COMMAND
22998 (setq this-command command)
23000 (if arg
23001 (call-interactively command)
23003 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23004 (and (org-kill-is-subtree-p)
23005 (or (bolp)
23006 (and (looking-at "[ \t]*$")
23007 (string-match
23008 "\\`\\*+\\'"
23009 (buffer-substring (point-at-bol) (point)))))))
23010 swallowp)
23011 (cond
23012 ((and subtreep org-yank-folded-subtrees)
23013 (let ((beg (point))
23014 end)
23015 (if (and subtreep org-yank-adjusted-subtrees)
23016 (org-paste-subtree nil nil 'for-yank)
23017 (call-interactively command))
23019 (setq end (point))
23020 (goto-char beg)
23021 (when (and (bolp) subtreep
23022 (not (setq swallowp
23023 (org-yank-folding-would-swallow-text beg end))))
23024 (org-with-limited-levels
23025 (or (looking-at org-outline-regexp)
23026 (re-search-forward org-outline-regexp-bol end t))
23027 (while (and (< (point) end) (looking-at org-outline-regexp))
23028 (hide-subtree)
23029 (org-cycle-show-empty-lines 'folded)
23030 (condition-case nil
23031 (outline-forward-same-level 1)
23032 (error (goto-char end))))))
23033 (when swallowp
23034 (message
23035 "Inserted text not folded because that would swallow text"))
23037 (goto-char end)
23038 (skip-chars-forward " \t\n\r")
23039 (beginning-of-line 1)
23040 (push-mark beg 'nomsg)))
23041 ((and subtreep org-yank-adjusted-subtrees)
23042 (let ((beg (point-at-bol)))
23043 (org-paste-subtree nil nil 'for-yank)
23044 (push-mark beg 'nomsg)))
23046 (call-interactively command))))))
23048 (defun org-yank-folding-would-swallow-text (beg end)
23049 "Would hide-subtree at BEG swallow any text after END?"
23050 (let (level)
23051 (org-with-limited-levels
23052 (save-excursion
23053 (goto-char beg)
23054 (when (or (looking-at org-outline-regexp)
23055 (re-search-forward org-outline-regexp-bol end t))
23056 (setq level (org-outline-level)))
23057 (goto-char end)
23058 (skip-chars-forward " \t\r\n\v\f")
23059 (if (or (eobp)
23060 (and (bolp) (looking-at org-outline-regexp)
23061 (<= (org-outline-level) level)))
23062 nil ; Nothing would be swallowed
23063 t))))) ; something would swallow
23065 (define-key org-mode-map "\C-y" 'org-yank)
23067 (defun org-truely-invisible-p ()
23068 "Check if point is at a character currently not visible.
23069 This version does not only check the character property, but also
23070 `visible-mode'."
23071 ;; Early versions of noutline don't have `outline-invisible-p'.
23072 (if (org-bound-and-true-p visible-mode)
23074 (outline-invisible-p)))
23076 (defun org-invisible-p2 ()
23077 "Check if point is at a character currently not visible."
23078 (save-excursion
23079 (if (and (eolp) (not (bobp))) (backward-char 1))
23080 ;; Early versions of noutline don't have `outline-invisible-p'.
23081 (outline-invisible-p)))
23083 (defun org-back-to-heading (&optional invisible-ok)
23084 "Call `outline-back-to-heading', but provide a better error message."
23085 (condition-case nil
23086 (outline-back-to-heading invisible-ok)
23087 (error (error "Before first headline at position %d in buffer %s"
23088 (point) (current-buffer)))))
23090 (defun org-before-first-heading-p ()
23091 "Before first heading?"
23092 (save-excursion
23093 (end-of-line)
23094 (null (re-search-backward org-outline-regexp-bol nil t))))
23096 (defun org-at-heading-p (&optional ignored)
23097 (outline-on-heading-p t))
23098 ;; Compatibility alias with Org versions < 7.8.03
23099 (defalias 'org-on-heading-p 'org-at-heading-p)
23101 (defun org-at-comment-p nil
23102 "Is cursor in a line starting with a # character?"
23103 (save-excursion
23104 (beginning-of-line)
23105 (looking-at "^#")))
23107 (defun org-at-drawer-p nil
23108 "Is cursor at a drawer keyword?"
23109 (save-excursion
23110 (move-beginning-of-line 1)
23111 (looking-at org-drawer-regexp)))
23113 (defun org-at-block-p nil
23114 "Is cursor at a block keyword?"
23115 (save-excursion
23116 (move-beginning-of-line 1)
23117 (looking-at org-block-regexp)))
23119 (defun org-point-at-end-of-empty-headline ()
23120 "If point is at the end of an empty headline, return t, else nil.
23121 If the heading only contains a TODO keyword, it is still still considered
23122 empty."
23123 (and (looking-at "[ \t]*$")
23124 (when org-todo-line-regexp
23125 (save-excursion
23126 (beginning-of-line 1)
23127 (let ((case-fold-search nil))
23128 (looking-at org-todo-line-regexp)
23129 (string= (match-string 3) ""))))))
23131 (defun org-at-heading-or-item-p ()
23132 (or (org-at-heading-p) (org-at-item-p)))
23134 (defun org-at-target-p ()
23135 (or (org-in-regexp org-radio-target-regexp)
23136 (org-in-regexp org-target-regexp)))
23137 ;; Compatibility alias with Org versions < 7.8.03
23138 (defalias 'org-on-target-p 'org-at-target-p)
23140 (defun org-up-heading-all (arg)
23141 "Move to the heading line of which the present line is a subheading.
23142 This function considers both visible and invisible heading lines.
23143 With argument, move up ARG levels."
23144 (if (fboundp 'outline-up-heading-all)
23145 (outline-up-heading-all arg) ; emacs 21 version of outline.el
23146 (outline-up-heading arg t))) ; emacs 22 version of outline.el
23148 (defun org-up-heading-safe ()
23149 "Move to the heading line of which the present line is a subheading.
23150 This version will not throw an error. It will return the level of the
23151 headline found, or nil if no higher level is found.
23153 Also, this function will be a lot faster than `outline-up-heading',
23154 because it relies on stars being the outline starters. This can really
23155 make a significant difference in outlines with very many siblings."
23156 (let (start-level re)
23157 (org-back-to-heading t)
23158 (setq start-level (funcall outline-level))
23159 (if (equal start-level 1)
23161 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
23162 (if (re-search-backward re nil t)
23163 (funcall outline-level)))))
23165 (defun org-first-sibling-p ()
23166 "Is this heading the first child of its parents?"
23167 (interactive)
23168 (let ((re org-outline-regexp-bol)
23169 level l)
23170 (unless (org-at-heading-p t)
23171 (user-error "Not at a heading"))
23172 (setq level (funcall outline-level))
23173 (save-excursion
23174 (if (not (re-search-backward re nil t))
23176 (setq l (funcall outline-level))
23177 (< l level)))))
23179 (defun org-goto-sibling (&optional previous)
23180 "Goto the next sibling, even if it is invisible.
23181 When PREVIOUS is set, go to the previous sibling instead. Returns t
23182 when a sibling was found. When none is found, return nil and don't
23183 move point."
23184 (let ((fun (if previous 're-search-backward 're-search-forward))
23185 (pos (point))
23186 (re org-outline-regexp-bol)
23187 level l)
23188 (when (condition-case nil (org-back-to-heading t) (error nil))
23189 (setq level (funcall outline-level))
23190 (catch 'exit
23191 (or previous (forward-char 1))
23192 (while (funcall fun re nil t)
23193 (setq l (funcall outline-level))
23194 (when (< l level) (goto-char pos) (throw 'exit nil))
23195 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23196 (goto-char pos)
23197 nil))))
23199 (defun org-show-siblings ()
23200 "Show all siblings of the current headline."
23201 (save-excursion
23202 (while (org-goto-sibling) (org-flag-heading nil)))
23203 (save-excursion
23204 (while (org-goto-sibling 'previous)
23205 (org-flag-heading nil))))
23207 (defun org-goto-first-child ()
23208 "Goto the first child, even if it is invisible.
23209 Return t when a child was found. Otherwise don't move point and
23210 return nil."
23211 (let (level (pos (point)) (re org-outline-regexp-bol))
23212 (when (condition-case nil (org-back-to-heading t) (error nil))
23213 (setq level (outline-level))
23214 (forward-char 1)
23215 (if (and (re-search-forward re nil t) (> (outline-level) level))
23216 (progn (goto-char (match-beginning 0)) t)
23217 (goto-char pos) nil))))
23219 (defun org-show-hidden-entry ()
23220 "Show an entry where even the heading is hidden."
23221 (save-excursion
23222 (org-show-entry)))
23224 (defun org-flag-heading (flag &optional entry)
23225 "Flag the current heading. FLAG non-nil means make invisible.
23226 When ENTRY is non-nil, show the entire entry."
23227 (save-excursion
23228 (org-back-to-heading t)
23229 ;; Check if we should show the entire entry
23230 (if entry
23231 (progn
23232 (org-show-entry)
23233 (save-excursion
23234 (and (outline-next-heading)
23235 (org-flag-heading nil))))
23236 (outline-flag-region (max (point-min) (1- (point)))
23237 (save-excursion (outline-end-of-heading) (point))
23238 flag))))
23240 (defun org-get-next-sibling ()
23241 "Move to next heading of the same level, and return point.
23242 If there is no such heading, return nil.
23243 This is like outline-next-sibling, but invisible headings are ok."
23244 (let ((level (funcall outline-level)))
23245 (outline-next-heading)
23246 (while (and (not (eobp)) (> (funcall outline-level) level))
23247 (outline-next-heading))
23248 (if (or (eobp) (< (funcall outline-level) level))
23250 (point))))
23252 (defun org-get-last-sibling ()
23253 "Move to previous heading of the same level, and return point.
23254 If there is no such heading, return nil."
23255 (let ((opoint (point))
23256 (level (funcall outline-level)))
23257 (outline-previous-heading)
23258 (when (and (/= (point) opoint) (outline-on-heading-p t))
23259 (while (and (> (funcall outline-level) level)
23260 (not (bobp)))
23261 (outline-previous-heading))
23262 (if (< (funcall outline-level) level)
23264 (point)))))
23266 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23267 "Goto to the end of a subtree."
23268 ;; This contains an exact copy of the original function, but it uses
23269 ;; `org-back-to-heading', to make it work also in invisible
23270 ;; trees. And is uses an invisible-ok argument.
23271 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23272 ;; Furthermore, when used inside Org, finding the end of a large subtree
23273 ;; with many children and grandchildren etc, this can be much faster
23274 ;; than the outline version.
23275 (org-back-to-heading invisible-ok)
23276 (let ((first t)
23277 (level (funcall outline-level)))
23278 (if (and (derived-mode-p 'org-mode) (< level 1000))
23279 ;; A true heading (not a plain list item), in Org-mode
23280 ;; This means we can easily find the end by looking
23281 ;; only for the right number of stars. Using a regexp to do
23282 ;; this is so much faster than using a Lisp loop.
23283 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23284 (forward-char 1)
23285 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23286 ;; something else, do it the slow way
23287 (while (and (not (eobp))
23288 (or first (> (funcall outline-level) level)))
23289 (setq first nil)
23290 (outline-next-heading)))
23291 (unless to-heading
23292 (if (memq (preceding-char) '(?\n ?\^M))
23293 (progn
23294 ;; Go to end of line before heading
23295 (forward-char -1)
23296 (if (memq (preceding-char) '(?\n ?\^M))
23297 ;; leave blank line before heading
23298 (forward-char -1))))))
23299 (point))
23301 (defun org-end-of-meta-data-and-drawers ()
23302 "Jump to the first text after meta data and drawers in the current entry.
23303 This will move over empty lines, lines with planning time stamps,
23304 clocking lines, and drawers."
23305 (org-back-to-heading t)
23306 (let ((end (save-excursion (outline-next-heading) (point)))
23307 (re (concat "\\(" org-drawer-regexp "\\)"
23308 "\\|" "[ \t]*" org-keyword-time-regexp)))
23309 (forward-line 1)
23310 (while (re-search-forward re end t)
23311 (if (not (match-end 1))
23312 ;; empty or planning line
23313 (forward-line 1)
23314 ;; a drawer, find the end
23315 (re-search-forward "^[ \t]*:END:" end 'move)
23316 (forward-line 1)))
23317 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23318 (point)))
23320 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23321 "Move forward to the ARG'th subheading at same level as this one.
23322 Stop at the first and last subheadings of a superior heading.
23323 Normally this only looks at visible headings, but when INVISIBLE-OK is
23324 non-nil it will also look at invisible ones."
23325 (interactive "p")
23326 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23327 (if (and arg (< arg 0))
23328 (goto-char (point-min))
23329 (outline-next-heading))
23330 (org-at-heading-p)
23331 (let ((level (- (match-end 0) (match-beginning 0) 1))
23332 (f (if (and arg (< arg 0))
23333 're-search-backward
23334 're-search-forward))
23335 (count (if arg (abs arg) 1))
23336 (result (point)))
23337 (while (and (prog1 (> count 0)
23338 (forward-char (if (and arg (< arg 0)) -1 1)))
23339 (funcall f org-outline-regexp-bol nil 'move))
23340 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23341 (cond ((< l level) (setq count 0))
23342 ((and (= l level)
23343 (or invisible-ok
23344 (progn
23345 (goto-char (line-beginning-position))
23346 (not (outline-invisible-p)))))
23347 (setq count (1- count))
23348 (when (eq l level)
23349 (setq result (point)))))))
23350 (goto-char result))
23351 (beginning-of-line 1)))
23353 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23354 "Move backward to the ARG'th subheading at same level as this one.
23355 Stop at the first and last subheadings of a superior heading."
23356 (interactive "p")
23357 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23359 (defun org-next-block (arg &optional backward block-regexp)
23360 "Jump to the next block.
23361 With a prefix argument ARG, jump forward ARG many source blocks.
23362 When BACKWARD is non-nil, jump to the previous block.
23363 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23364 (interactive "p")
23365 (let ((re (or block-regexp org-block-regexp))
23366 (re-search-fn (or (and backward 're-search-backward)
23367 're-search-forward)))
23368 (if (looking-at re) (forward-char 1))
23369 (condition-case nil
23370 (funcall re-search-fn re nil nil arg)
23371 (error (error "No %s code blocks" (if backward "previous" "further" ))))
23372 (goto-char (match-beginning 0)) (org-show-context)))
23374 (defun org-previous-block (arg &optional block-regexp)
23375 "Jump to the previous block.
23376 With a prefix argument ARG, jump backward ARG many source blocks.
23377 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23378 (interactive "p")
23379 (org-next-block arg t block-regexp))
23381 (defun org-forward-paragraph ()
23382 "Move forward to beginning of next paragraph or equivalent.
23384 The function moves point to the beginning of the next visible
23385 structural element, which can be a paragraph, a table, a list
23386 item, etc. It also provides some special moves for convenience:
23388 - On an affiliated keyword, jump to the beginning of the
23389 relative element.
23390 - On an item or a footnote definition, move to the second
23391 element inside, if any.
23392 - On a table or a property drawer, jump after it.
23393 - On a verse or source block, stop after blank lines."
23394 (interactive)
23395 (when (eobp) (user-error "Cannot move further down"))
23396 (let* ((deactivate-mark nil)
23397 (element (org-element-at-point))
23398 (type (org-element-type element))
23399 (post-affiliated (org-element-property :post-affiliated element))
23400 (contents-begin (org-element-property :contents-begin element))
23401 (contents-end (org-element-property :contents-end element))
23402 (end (let ((end (org-element-property :end element)) (parent element))
23403 (while (and (setq parent (org-element-property :parent parent))
23404 (= (org-element-property :contents-end parent) end))
23405 (setq end (org-element-property :end parent)))
23406 end)))
23407 (cond ((not element)
23408 (skip-chars-forward " \r\t\n")
23409 (or (eobp) (beginning-of-line)))
23410 ;; On affiliated keywords, move to element's beginning.
23411 ((and post-affiliated (< (point) post-affiliated))
23412 (goto-char post-affiliated))
23413 ;; At a table row, move to the end of the table. Similarly,
23414 ;; at a node property, move to the end of the property
23415 ;; drawer.
23416 ((memq type '(node-property table-row))
23417 (goto-char (org-element-property
23418 :end (org-element-property :parent element))))
23419 ((memq type '(property-drawer table)) (goto-char end))
23420 ;; Consider blank lines as separators in verse and source
23421 ;; blocks to ease editing.
23422 ((memq type '(src-block verse-block))
23423 (when (eq type 'src-block)
23424 (setq contents-end
23425 (save-excursion (goto-char end)
23426 (skip-chars-backward " \r\t\n")
23427 (line-beginning-position))))
23428 (beginning-of-line)
23429 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23430 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23431 (goto-char end)
23432 (skip-chars-forward " \r\t\n")
23433 (if (= (point) contents-end) (goto-char end)
23434 (beginning-of-line))))
23435 ;; With no contents, just skip element.
23436 ((not contents-begin) (goto-char end))
23437 ;; If contents are invisible, skip the element altogether.
23438 ((outline-invisible-p (line-end-position))
23439 (case type
23440 (headline
23441 (org-with-limited-levels (outline-next-visible-heading 1)))
23442 ;; At a plain list, make sure we move to the next item
23443 ;; instead of skipping the whole list.
23444 (plain-list (forward-char)
23445 (org-forward-paragraph))
23446 (otherwise (goto-char end))))
23447 ((>= (point) contents-end) (goto-char end))
23448 ((>= (point) contents-begin)
23449 ;; This can only happen on paragraphs and plain lists.
23450 (case type
23451 (paragraph (goto-char end))
23452 ;; At a plain list, try to move to second element in
23453 ;; first item, if possible.
23454 (plain-list (end-of-line)
23455 (org-forward-paragraph))))
23456 ;; When contents start on the middle of a line (e.g. in
23457 ;; items and footnote definitions), try to reach first
23458 ;; element starting after current line.
23459 ((> (line-end-position) contents-begin)
23460 (end-of-line)
23461 (org-forward-paragraph))
23462 (t (goto-char contents-begin)))))
23464 (defun org-backward-paragraph ()
23465 "Move backward to start of previous paragraph or equivalent.
23467 The function moves point to the beginning of the current
23468 structural element, which can be a paragraph, a table, a list
23469 item, etc., or to the beginning of the previous visible one if
23470 point is already there. It also provides some special moves for
23471 convenience:
23473 - On an affiliated keyword, jump to the first one.
23474 - On a table or a property drawer, move to its beginning.
23475 - On a verse or source block, stop before blank lines."
23476 (interactive)
23477 (when (bobp) (user-error "Cannot move further up"))
23478 (let* ((deactivate-mark nil)
23479 (element (org-element-at-point))
23480 (type (org-element-type element))
23481 (contents-begin (org-element-property :contents-begin element))
23482 (contents-end (org-element-property :contents-end element))
23483 (post-affiliated (org-element-property :post-affiliated element))
23484 (begin (org-element-property :begin element)))
23485 (cond
23486 ((not element) (goto-char (point-min)))
23487 ((= (point) begin)
23488 (backward-char)
23489 (org-backward-paragraph))
23490 ((and post-affiliated (<= (point) post-affiliated)) (goto-char begin))
23491 ((memq type '(node-property table-row))
23492 (goto-char (org-element-property
23493 :post-affiliated (org-element-property :parent element))))
23494 ((memq type '(property-drawer table)) (goto-char begin))
23495 ((memq type '(src-block verse-block))
23496 (when (eq type 'src-block)
23497 (setq contents-begin
23498 (save-excursion (goto-char begin) (forward-line) (point))))
23499 (if (= (point) contents-begin) (goto-char post-affiliated)
23500 ;; Inside a verse block, see blank lines as paragraph
23501 ;; separators.
23502 (let ((origin (point)))
23503 (skip-chars-backward " \r\t\n" contents-begin)
23504 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
23505 (skip-chars-forward " \r\t\n" origin)
23506 (if (= (point) origin) (goto-char contents-begin)
23507 (beginning-of-line))))))
23508 ((not contents-begin) (goto-char (or post-affiliated begin)))
23509 ((eq type 'paragraph)
23510 (goto-char contents-begin)
23511 ;; When at first paragraph in an item or a footnote definition,
23512 ;; move directly to beginning of line.
23513 (let ((parent-contents
23514 (org-element-property
23515 :contents-begin (org-element-property :parent element))))
23516 (when (and parent-contents (= parent-contents contents-begin))
23517 (beginning-of-line))))
23518 ;; At the end of a greater element, move to the beginning of the
23519 ;; last element within.
23520 ((>= (point) contents-end)
23521 (goto-char (1- contents-end))
23522 (org-backward-paragraph))
23523 (t (goto-char (or post-affiliated begin))))
23524 ;; Ensure we never leave point invisible.
23525 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
23527 (defun org-forward-element ()
23528 "Move forward by one element.
23529 Move to the next element at the same level, when possible."
23530 (interactive)
23531 (cond ((eobp) (user-error "Cannot move further down"))
23532 ((org-with-limited-levels (org-at-heading-p))
23533 (let ((origin (point)))
23534 (goto-char (org-end-of-subtree nil t))
23535 (unless (org-with-limited-levels (org-at-heading-p))
23536 (goto-char origin)
23537 (user-error "Cannot move further down"))))
23539 (let* ((elem (org-element-at-point))
23540 (end (org-element-property :end elem))
23541 (parent (org-element-property :parent elem)))
23542 (cond ((and parent (= (org-element-property :contents-end parent) end))
23543 (goto-char (org-element-property :end parent)))
23544 ((integer-or-marker-p end) (goto-char end))
23545 (t (message "No element at point")))))))
23547 (defun org-backward-element ()
23548 "Move backward by one element.
23549 Move to the previous element at the same level, when possible."
23550 (interactive)
23551 (cond ((bobp) (user-error "Cannot move further up"))
23552 ((org-with-limited-levels (org-at-heading-p))
23553 ;; At a headline, move to the previous one, if any, or stay
23554 ;; here.
23555 (let ((origin (point)))
23556 (org-with-limited-levels (org-backward-heading-same-level 1))
23557 ;; When current headline has no sibling above, move to its
23558 ;; parent.
23559 (when (= (point) origin)
23560 (or (org-with-limited-levels (org-up-heading-safe))
23561 (progn (goto-char origin)
23562 (user-error "Cannot move further up"))))))
23564 (let* ((trail (org-element-at-point 'keep-trail))
23565 (elem (car trail))
23566 (prev-elem (nth 1 trail))
23567 (beg (org-element-property :begin elem)))
23568 (cond
23569 ;; Move to beginning of current element if point isn't
23570 ;; there already.
23571 ((null beg) (message "No element at point"))
23572 ((/= (point) beg) (goto-char beg))
23573 (prev-elem (goto-char (org-element-property :begin prev-elem)))
23574 ((org-before-first-heading-p) (goto-char (point-min)))
23575 (t (org-back-to-heading)))))))
23577 (defun org-up-element ()
23578 "Move to upper element."
23579 (interactive)
23580 (if (org-with-limited-levels (org-at-heading-p))
23581 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23582 (let* ((elem (org-element-at-point))
23583 (parent (org-element-property :parent elem)))
23584 (if parent (goto-char (org-element-property :begin parent))
23585 (if (org-with-limited-levels (org-before-first-heading-p))
23586 (user-error "No surrounding element")
23587 (org-with-limited-levels (org-back-to-heading)))))))
23589 (defvar org-element-greater-elements)
23590 (defun org-down-element ()
23591 "Move to inner element."
23592 (interactive)
23593 (let ((element (org-element-at-point)))
23594 (cond
23595 ((memq (org-element-type element) '(plain-list table))
23596 (goto-char (org-element-property :contents-begin element))
23597 (forward-char))
23598 ((memq (org-element-type element) org-element-greater-elements)
23599 ;; If contents are hidden, first disclose them.
23600 (when (org-element-property :hiddenp element) (org-cycle))
23601 (goto-char (or (org-element-property :contents-begin element)
23602 (user-error "No content for this element"))))
23603 (t (user-error "No inner element")))))
23605 (defun org-drag-element-backward ()
23606 "Move backward element at point."
23607 (interactive)
23608 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
23609 (let* ((trail (org-element-at-point 'keep-trail))
23610 (elem (car trail))
23611 (prev-elem (nth 1 trail)))
23612 ;; Error out if no previous element or previous element is
23613 ;; a parent of the current one.
23614 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23615 (user-error "Cannot drag element backward")
23616 (let ((pos (point)))
23617 (org-element-swap-A-B prev-elem elem)
23618 (goto-char (+ (org-element-property :begin prev-elem)
23619 (- pos (org-element-property :begin elem)))))))))
23621 (defun org-drag-element-forward ()
23622 "Move forward element at point."
23623 (interactive)
23624 (let* ((pos (point))
23625 (elem (org-element-at-point)))
23626 (when (= (point-max) (org-element-property :end elem))
23627 (user-error "Cannot drag element forward"))
23628 (goto-char (org-element-property :end elem))
23629 (let ((next-elem (org-element-at-point)))
23630 (when (or (org-element-nested-p elem next-elem)
23631 (and (eq (org-element-type next-elem) 'headline)
23632 (not (eq (org-element-type elem) 'headline))))
23633 (goto-char pos)
23634 (user-error "Cannot drag element forward"))
23635 ;; Compute new position of point: it's shifted by NEXT-ELEM
23636 ;; body's length (without final blanks) and by the length of
23637 ;; blanks between ELEM and NEXT-ELEM.
23638 (let ((size-next (- (save-excursion
23639 (goto-char (org-element-property :end next-elem))
23640 (skip-chars-backward " \r\t\n")
23641 (forward-line)
23642 ;; Small correction if buffer doesn't end
23643 ;; with a newline character.
23644 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23645 (org-element-property :begin next-elem)))
23646 (size-blank (- (org-element-property :end elem)
23647 (save-excursion
23648 (goto-char (org-element-property :end elem))
23649 (skip-chars-backward " \r\t\n")
23650 (forward-line)
23651 (point)))))
23652 (org-element-swap-A-B elem next-elem)
23653 (goto-char (+ pos size-next size-blank))))))
23655 (defun org-drag-line-forward (arg)
23656 "Drag the line at point ARG lines forward."
23657 (interactive "p")
23658 (dotimes (n (abs arg))
23659 (let ((c (current-column)))
23660 (if (< 0 arg)
23661 (progn
23662 (beginning-of-line 2)
23663 (transpose-lines 1)
23664 (beginning-of-line 0))
23665 (transpose-lines 1)
23666 (beginning-of-line -1))
23667 (org-move-to-column c))))
23669 (defun org-drag-line-backward (arg)
23670 "Drag the line at point ARG lines backward."
23671 (interactive "p")
23672 (org-drag-line-forward (- arg)))
23674 (defun org-mark-element ()
23675 "Put point at beginning of this element, mark at end.
23677 Interactively, if this command is repeated or (in Transient Mark
23678 mode) if the mark is active, it marks the next element after the
23679 ones already marked."
23680 (interactive)
23681 (let (deactivate-mark)
23682 (if (and (org-called-interactively-p 'any)
23683 (or (and (eq last-command this-command) (mark t))
23684 (and transient-mark-mode mark-active)))
23685 (set-mark
23686 (save-excursion
23687 (goto-char (mark))
23688 (goto-char (org-element-property :end (org-element-at-point)))))
23689 (let ((element (org-element-at-point)))
23690 (end-of-line)
23691 (push-mark (org-element-property :end element) t t)
23692 (goto-char (org-element-property :begin element))))))
23694 (defun org-narrow-to-element ()
23695 "Narrow buffer to current element."
23696 (interactive)
23697 (let ((elem (org-element-at-point)))
23698 (cond
23699 ((eq (car elem) 'headline)
23700 (narrow-to-region
23701 (org-element-property :begin elem)
23702 (org-element-property :end elem)))
23703 ((memq (car elem) org-element-greater-elements)
23704 (narrow-to-region
23705 (org-element-property :contents-begin elem)
23706 (org-element-property :contents-end elem)))
23708 (narrow-to-region
23709 (org-element-property :begin elem)
23710 (org-element-property :end elem))))))
23712 (defun org-transpose-element ()
23713 "Transpose current and previous elements, keeping blank lines between.
23714 Point is moved after both elements."
23715 (interactive)
23716 (org-skip-whitespace)
23717 (let ((end (org-element-property :end (org-element-at-point))))
23718 (org-drag-element-backward)
23719 (goto-char end)))
23721 (defun org-unindent-buffer ()
23722 "Un-indent the visible part of the buffer.
23723 Relative indentation (between items, inside blocks, etc.) isn't
23724 modified."
23725 (interactive)
23726 (unless (eq major-mode 'org-mode)
23727 (user-error "Cannot un-indent a buffer not in Org mode"))
23728 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
23729 unindent-tree ; For byte-compiler.
23730 (unindent-tree
23731 (function
23732 (lambda (contents)
23733 (mapc
23734 (lambda (element)
23735 (if (memq (org-element-type element) '(headline section))
23736 (funcall unindent-tree (org-element-contents element))
23737 (save-excursion
23738 (save-restriction
23739 (narrow-to-region
23740 (org-element-property :begin element)
23741 (org-element-property :end element))
23742 (org-do-remove-indentation)))))
23743 (reverse contents))))))
23744 (funcall unindent-tree (org-element-contents parse-tree))))
23746 (defun org-show-subtree ()
23747 "Show everything after this heading at deeper levels."
23748 (interactive)
23749 (outline-flag-region
23750 (point)
23751 (save-excursion
23752 (org-end-of-subtree t t))
23753 nil))
23755 (defun org-show-entry ()
23756 "Show the body directly following this heading.
23757 Show the heading too, if it is currently invisible."
23758 (interactive)
23759 (save-excursion
23760 (condition-case nil
23761 (progn
23762 (org-back-to-heading t)
23763 (outline-flag-region
23764 (max (point-min) (1- (point)))
23765 (save-excursion
23766 (if (re-search-forward
23767 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23768 (match-beginning 1)
23769 (point-max)))
23770 nil)
23771 (org-cycle-hide-drawers 'children))
23772 (error nil))))
23774 (defun org-make-options-regexp (kwds &optional extra)
23775 "Make a regular expression for keyword lines."
23776 (concat
23777 "^#\\+\\("
23778 (mapconcat 'regexp-quote kwds "\\|")
23779 (if extra (concat "\\|" extra))
23780 "\\):[ \t]*\\(.*\\)"))
23782 ;; Make isearch reveal the necessary context
23783 (defun org-isearch-end ()
23784 "Reveal context after isearch exits."
23785 (when isearch-success ; only if search was successful
23786 (if (featurep 'xemacs)
23787 ;; Under XEmacs, the hook is run in the correct place,
23788 ;; we directly show the context.
23789 (org-show-context 'isearch)
23790 ;; In Emacs the hook runs *before* restoring the overlays.
23791 ;; So we have to use a one-time post-command-hook to do this.
23792 ;; (Emacs 22 has a special variable, see function `org-mode')
23793 (unless (and (boundp 'isearch-mode-end-hook-quit)
23794 isearch-mode-end-hook-quit)
23795 ;; Only when the isearch was not quitted.
23796 (org-add-hook 'post-command-hook 'org-isearch-post-command
23797 'append 'local)))
23798 (org-fix-ellipsis-at-bol)))
23800 (defun org-isearch-post-command ()
23801 "Remove self from hook, and show context."
23802 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23803 (org-show-context 'isearch))
23806 ;;;; Integration with and fixes for other packages
23808 ;;; Imenu support
23810 (defvar org-imenu-markers nil
23811 "All markers currently used by Imenu.")
23812 (make-variable-buffer-local 'org-imenu-markers)
23814 (defun org-imenu-new-marker (&optional pos)
23815 "Return a new marker for use by Imenu, and remember the marker."
23816 (let ((m (make-marker)))
23817 (move-marker m (or pos (point)))
23818 (push m org-imenu-markers)
23821 (defun org-imenu-get-tree ()
23822 "Produce the index for Imenu."
23823 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23824 (setq org-imenu-markers nil)
23825 (let* ((n org-imenu-depth)
23826 (re (concat "^" (org-get-limited-outline-regexp)))
23827 (subs (make-vector (1+ n) nil))
23828 (last-level 0)
23829 m level head0 head)
23830 (save-excursion
23831 (save-restriction
23832 (widen)
23833 (goto-char (point-max))
23834 (while (re-search-backward re nil t)
23835 (setq level (org-reduced-level (funcall outline-level)))
23836 (when (and (<= level n)
23837 (looking-at org-complex-heading-regexp)
23838 (setq head0 (org-match-string-no-properties 4)))
23839 (setq head (org-link-display-format head0)
23840 m (org-imenu-new-marker))
23841 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23842 (if (>= level last-level)
23843 (push (cons head m) (aref subs level))
23844 (push (cons head (aref subs (1+ level))) (aref subs level))
23845 (loop for i from (1+ level) to n do (aset subs i nil)))
23846 (setq last-level level)))))
23847 (aref subs 1)))
23849 (eval-after-load "imenu"
23850 '(progn
23851 (add-hook 'imenu-after-jump-hook
23852 (lambda ()
23853 (if (derived-mode-p 'org-mode)
23854 (org-show-context 'org-goto))))))
23856 (defun org-link-display-format (link)
23857 "Replace a link with its the description.
23858 If there is no description, use the link target."
23859 (save-match-data
23860 (if (string-match org-bracket-link-analytic-regexp link)
23861 (replace-match (if (match-end 5)
23862 (match-string 5 link)
23863 (concat (match-string 1 link)
23864 (match-string 3 link)))
23865 nil t link)
23866 link)))
23868 (defun org-toggle-link-display ()
23869 "Toggle the literal or descriptive display of links."
23870 (interactive)
23871 (if org-descriptive-links
23872 (progn (org-remove-from-invisibility-spec '(org-link))
23873 (org-restart-font-lock)
23874 (setq org-descriptive-links nil))
23875 (progn (add-to-invisibility-spec '(org-link))
23876 (org-restart-font-lock)
23877 (setq org-descriptive-links t))))
23879 ;; Speedbar support
23881 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23882 "Overlay marking the agenda restriction line in speedbar.")
23883 (overlay-put org-speedbar-restriction-lock-overlay
23884 'face 'org-agenda-restriction-lock)
23885 (overlay-put org-speedbar-restriction-lock-overlay
23886 'help-echo "Agendas are currently limited to this item.")
23887 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23889 (defun org-speedbar-set-agenda-restriction ()
23890 "Restrict future agenda commands to the location at point in speedbar.
23891 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23892 (interactive)
23893 (require 'org-agenda)
23894 (let (p m tp np dir txt)
23895 (cond
23896 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23897 'org-imenu t))
23898 (setq m (get-text-property p 'org-imenu-marker))
23899 (with-current-buffer (marker-buffer m)
23900 (goto-char m)
23901 (org-agenda-set-restriction-lock 'subtree)))
23902 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23903 'speedbar-function 'speedbar-find-file))
23904 (setq tp (previous-single-property-change
23905 (1+ p) 'speedbar-function)
23906 np (next-single-property-change
23907 tp 'speedbar-function)
23908 dir (speedbar-line-directory)
23909 txt (buffer-substring-no-properties (or tp (point-min))
23910 (or np (point-max))))
23911 (with-current-buffer (find-file-noselect
23912 (let ((default-directory dir))
23913 (expand-file-name txt)))
23914 (unless (derived-mode-p 'org-mode)
23915 (user-error "Cannot restrict to non-Org-mode file"))
23916 (org-agenda-set-restriction-lock 'file)))
23917 (t (user-error "Don't know how to restrict Org-mode's agenda")))
23918 (move-overlay org-speedbar-restriction-lock-overlay
23919 (point-at-bol) (point-at-eol))
23920 (setq current-prefix-arg nil)
23921 (org-agenda-maybe-redo)))
23923 (defvar speedbar-file-key-map)
23924 (declare-function speedbar-add-supported-extension "speedbar" (extension))
23925 (eval-after-load "speedbar"
23926 '(progn
23927 (speedbar-add-supported-extension ".org")
23928 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23929 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23930 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23931 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23932 (add-hook 'speedbar-visiting-tag-hook
23933 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23935 ;;; Fixes and Hacks for problems with other packages
23937 ;; Make flyspell not check words in links, to not mess up our keymap
23938 (defvar org-element-affiliated-keywords) ; From org-element.el
23939 (defvar org-element-block-name-alist) ; From org-element.el
23940 (defun org-mode-flyspell-verify ()
23941 "Don't let flyspell put overlays at active buttons, or on
23942 {todo,all-time,additional-option-like}-keywords."
23943 (require 'org-element) ; For `org-element-affiliated-keywords'
23944 (let ((pos (max (1- (point)) (point-min)))
23945 (word (thing-at-point 'word)))
23946 (and (not (get-text-property pos 'keymap))
23947 (not (get-text-property pos 'org-no-flyspell))
23948 (not (member word org-todo-keywords-1))
23949 (not (member word org-all-time-keywords))
23950 (not (member word org-options-keywords))
23951 (not (member word (mapcar 'car org-startup-options)))
23952 (not (member-ignore-case word org-element-affiliated-keywords))
23953 (not (member-ignore-case word (org-get-export-keywords)))
23954 (not (member-ignore-case
23955 word (mapcar 'car org-element-block-name-alist)))
23956 (not (member-ignore-case word '("BEGIN" "END" "ATTR")))
23957 (not (org-in-src-block-p)))))
23959 (defun org-remove-flyspell-overlays-in (beg end)
23960 "Remove flyspell overlays in region."
23961 (and (org-bound-and-true-p flyspell-mode)
23962 (fboundp 'flyspell-delete-region-overlays)
23963 (flyspell-delete-region-overlays beg end))
23964 (add-text-properties beg end '(org-no-flyspell t)))
23966 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23967 (eval-after-load "bookmark"
23968 '(if (boundp 'bookmark-after-jump-hook)
23969 ;; We can use the hook
23970 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23971 ;; Hook not available, use advice
23972 (defadvice bookmark-jump (after org-make-visible activate)
23973 "Make the position visible."
23974 (org-bookmark-jump-unhide))))
23976 ;; Make sure saveplace shows the location if it was hidden
23977 (eval-after-load "saveplace"
23978 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23979 "Make the position visible."
23980 (org-bookmark-jump-unhide)))
23982 ;; Make sure ecb shows the location if it was hidden
23983 (eval-after-load "ecb"
23984 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23985 "Make hierarchy visible when jumping into location from ECB tree buffer."
23986 (if (derived-mode-p 'org-mode)
23987 (org-show-context))))
23989 (defun org-bookmark-jump-unhide ()
23990 "Unhide the current position, to show the bookmark location."
23991 (and (derived-mode-p 'org-mode)
23992 (or (outline-invisible-p)
23993 (save-excursion (goto-char (max (point-min) (1- (point))))
23994 (outline-invisible-p)))
23995 (org-show-context 'bookmark-jump)))
23997 ;; Make session.el ignore our circular variable
23998 (defvar session-globals-exclude)
23999 (eval-after-load "session"
24000 '(add-to-list 'session-globals-exclude 'org-mark-ring))
24002 ;;;; Finish up
24004 (provide 'org)
24006 (run-hooks 'org-load-hook)
24008 ;;; org.el ends here