Fix C-c C-c behaviour on some objects
[org-mode.git] / lisp / org.el
blobadaabebc6a536b7c645acc70a9b2e302d17dae0c
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2013 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;;; Commentary:
28 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
29 ;; project planning with a fast and effective plain-text system.
31 ;; Org-mode develops organizational tasks around NOTES files that contain
32 ;; information about projects as plain text. Org-mode is implemented on
33 ;; top of outline-mode, which makes it possible to keep the content of
34 ;; large files well structured. Visibility cycling and structure editing
35 ;; help to work with the tree. Tables are easily created with a built-in
36 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
37 ;; and scheduling. It dynamically compiles entries into an agenda that
38 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
39 ;; Plain text URL-like links connect to websites, emails, Usenet
40 ;; messages, BBDB entries, and any files related to the projects. For
41 ;; printing and sharing of notes, an Org-mode file can be exported as a
42 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
43 ;; iCalendar file. It can also serve as a publishing tool for a set of
44 ;; linked webpages.
46 ;; Installation and Activation
47 ;; ---------------------------
48 ;; See the corresponding sections in the manual at
50 ;; http://orgmode.org/org.html#Installation
52 ;; Documentation
53 ;; -------------
54 ;; The documentation of Org-mode can be found in the TeXInfo file. The
55 ;; distribution also contains a PDF version of it. At the homepage of
56 ;; Org-mode, you can read the same text online as HTML. There is also an
57 ;; excellent reference card made by Philip Rooke. This card can be found
58 ;; in the etc/ directory of Emacs 22.
60 ;; A list of recent changes can be found at
61 ;; http://orgmode.org/Changes.html
63 ;;; Code:
65 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
66 (defvar org-table-formula-constants-local nil
67 "Local version of `org-table-formula-constants'.")
68 (make-variable-buffer-local 'org-table-formula-constants-local)
70 ;;;; Require other packages
72 (eval-when-compile
73 (require 'cl)
74 (require 'gnus-sum))
76 (require 'calendar)
77 (require 'find-func)
78 (require 'format-spec)
80 (load "org-loaddefs.el" t t t)
82 (require 'org-macs)
83 (require 'org-compat)
85 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
86 ;; some places -- e.g. see the macro `org-with-limited-levels'.
88 ;; In Org buffers, the value of `outline-regexp' is that of
89 ;; `org-outline-regexp'. The only function still directly relying on
90 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
91 ;; job when `orgstruct-mode' is active.
92 (defvar org-outline-regexp "\\*+ "
93 "Regexp to match Org headlines.")
95 (defvar org-outline-regexp-bol "^\\*+ "
96 "Regexp to match Org headlines.
97 This is similar to `org-outline-regexp' but additionally makes
98 sure that we are at the beginning of the line.")
100 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
101 "Matches a headline, putting stars and text into groups.
102 Stars are put in group 1 and the trimmed body in group 2.")
104 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
105 (unless (boundp 'calendar-view-holidays-initially-flag)
106 (org-defvaralias 'calendar-view-holidays-initially-flag
107 'view-calendar-holidays-initially))
108 (unless (boundp 'calendar-view-diary-initially-flag)
109 (org-defvaralias 'calendar-view-diary-initially-flag
110 'view-diary-entries-initially))
111 (unless (boundp 'diary-fancy-buffer)
112 (org-defvaralias 'diary-fancy-buffer 'fancy-diary-buffer))
114 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
115 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
116 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
117 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
118 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
119 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
120 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
121 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
123 (declare-function orgtbl-mode "org-table" (&optional arg))
124 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
125 (declare-function org-beamer-mode "ox-beamer" ())
126 (declare-function org-table-edit-field "org-table" (arg))
127 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
128 (declare-function org-table-set-constants "org-table" ())
129 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
130 (declare-function org-id-get-create "org-id" (&optional force))
131 (declare-function org-id-find-id-file "org-id" (id))
132 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
133 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
134 (declare-function org-agenda-redo "org-agenda" (&optional all))
135 (declare-function org-table-align "org-table" ())
136 (declare-function org-table-paste-rectangle "org-table" ())
137 (declare-function org-table-maybe-eval-formula "org-table" ())
138 (declare-function org-table-maybe-recalculate-line "org-table" ())
140 (declare-function org-element--parse-objects "org-element"
141 (beg end acc restriction))
142 (declare-function org-element-at-point "org-element" (&optional keep-trail))
143 (declare-function org-element-contents "org-element" (element))
144 (declare-function org-element-context "org-element" (&optional element))
145 (declare-function org-element-interpret-data "org-element"
146 (data &optional parent))
147 (declare-function org-element-map "org-element"
148 (data types fun &optional info first-match no-recursion))
149 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
150 (declare-function org-element-parse-buffer "org-element"
151 (&optional granularity visible-only))
152 (declare-function org-element-property "org-element" (property element))
153 (declare-function org-element-put-property "org-element"
154 (element property value))
155 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
156 (declare-function org-element--parse-objects "org-element"
157 (beg end acc restriction))
158 (declare-function org-element-parse-buffer "org-element"
159 (&optional granularity visible-only))
160 (declare-function org-element-restriction "org-element" (element))
161 (declare-function org-element-type "org-element" (element))
163 ;; load languages based on value of `org-babel-load-languages'
164 (defvar org-babel-load-languages)
166 ;;;###autoload
167 (defun org-babel-do-load-languages (sym value)
168 "Load the languages defined in `org-babel-load-languages'."
169 (set-default sym value)
170 (mapc (lambda (pair)
171 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
172 (if active
173 (progn
174 (require (intern (concat "ob-" lang))))
175 (progn
176 (funcall 'fmakunbound
177 (intern (concat "org-babel-execute:" lang)))
178 (funcall 'fmakunbound
179 (intern (concat "org-babel-expand-body:" lang)))))))
180 org-babel-load-languages))
182 ;;;###autoload
183 (defun org-babel-load-file (file &optional compile)
184 "Load Emacs Lisp source code blocks in the Org-mode FILE.
185 This function exports the source code using `org-babel-tangle'
186 and then loads the resulting file using `load-file'. With prefix
187 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
188 file to byte-code before it is loaded."
189 (interactive "fFile to load: \nP")
190 (require 'ob-core)
191 (let* ((age (lambda (file)
192 (float-time
193 (time-subtract (current-time)
194 (nth 5 (or (file-attributes (file-truename file))
195 (file-attributes file)))))))
196 (base-name (file-name-sans-extension file))
197 (exported-file (concat base-name ".el")))
198 ;; tangle if the org-mode file is newer than the elisp file
199 (unless (and (file-exists-p exported-file)
200 (> (funcall age file) (funcall age exported-file)))
201 (setq exported-file
202 (car (org-babel-tangle-file file exported-file "emacs-lisp"))))
203 (message "%s %s"
204 (if compile
205 (progn (byte-compile-file exported-file 'load)
206 "Compiled and loaded")
207 (progn (load-file exported-file) "Loaded"))
208 exported-file)))
210 (defcustom org-babel-load-languages '((emacs-lisp . t))
211 "Languages which can be evaluated in Org-mode buffers.
212 This list can be used to load support for any of the languages
213 below, note that each language will depend on a different set of
214 system executables and/or Emacs modes. When a language is
215 \"loaded\", then code blocks in that language can be evaluated
216 with `org-babel-execute-src-block' bound by default to C-c
217 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
218 be set to remove code block evaluation from the C-c C-c
219 keybinding. By default only Emacs Lisp (which has no
220 requirements) is loaded."
221 :group 'org-babel
222 :set 'org-babel-do-load-languages
223 :version "24.1"
224 :type '(alist :tag "Babel Languages"
225 :key-type
226 (choice
227 (const :tag "Awk" awk)
228 (const :tag "C" C)
229 (const :tag "R" R)
230 (const :tag "Asymptote" asymptote)
231 (const :tag "Calc" calc)
232 (const :tag "Clojure" clojure)
233 (const :tag "CSS" css)
234 (const :tag "Ditaa" ditaa)
235 (const :tag "Dot" dot)
236 (const :tag "Emacs Lisp" emacs-lisp)
237 (const :tag "Fortran" fortran)
238 (const :tag "Gnuplot" gnuplot)
239 (const :tag "Haskell" haskell)
240 (const :tag "IO" io)
241 (const :tag "Java" java)
242 (const :tag "Javascript" js)
243 (const :tag "LaTeX" latex)
244 (const :tag "Ledger" ledger)
245 (const :tag "Lilypond" lilypond)
246 (const :tag "Lisp" lisp)
247 (const :tag "Makefile" makefile)
248 (const :tag "Maxima" maxima)
249 (const :tag "Matlab" matlab)
250 (const :tag "Mscgen" mscgen)
251 (const :tag "Ocaml" ocaml)
252 (const :tag "Octave" octave)
253 (const :tag "Org" org)
254 (const :tag "Perl" perl)
255 (const :tag "Pico Lisp" picolisp)
256 (const :tag "PlantUML" plantuml)
257 (const :tag "Python" python)
258 (const :tag "Ruby" ruby)
259 (const :tag "Sass" sass)
260 (const :tag "Scala" scala)
261 (const :tag "Scheme" scheme)
262 (const :tag "Screen" screen)
263 (const :tag "Shell Script" sh)
264 (const :tag "Shen" shen)
265 (const :tag "Sql" sql)
266 (const :tag "Sqlite" sqlite))
267 :value-type (boolean :tag "Activate" :value t)))
269 ;;;; Customization variables
270 (defcustom org-clone-delete-id nil
271 "Remove ID property of clones of a subtree.
272 When non-nil, clones of a subtree don't inherit the ID property.
273 Otherwise they inherit the ID property with a new unique
274 identifier."
275 :type 'boolean
276 :version "24.1"
277 :group 'org-id)
279 ;;; Version
280 (org-check-version)
282 ;;;###autoload
283 (defun org-version (&optional here full message)
284 "Show the org-mode version in the echo area.
285 With prefix argument HERE, insert it at point.
286 When FULL is non-nil, use a verbose version string.
287 When MESSAGE is non-nil, display a message with the version."
288 (interactive "P")
289 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
290 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
291 (load-suffixes (list ".el"))
292 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
293 (org-trash (or
294 (and (fboundp 'org-release) (fboundp 'org-git-version))
295 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
296 (load-suffixes save-load-suffixes)
297 (org-version (org-release))
298 (git-version (org-git-version))
299 (version (format "Org-mode version %s (%s @ %s)"
300 org-version
301 git-version
302 (if org-install-dir
303 (if (string= org-dir org-install-dir)
304 org-install-dir
305 (concat "mixed installation! " org-install-dir " and " org-dir))
306 "org-loaddefs.el can not be found!")))
307 (version1 (if full version org-version)))
308 (if (org-called-interactively-p 'interactive)
309 (if here
310 (insert version)
311 (message version))
312 (if message (message version1))
313 version1)))
315 (defconst org-version (org-version))
317 ;;; Compatibility constants
319 ;;; The custom variables
321 (defgroup org nil
322 "Outline-based notes management and organizer."
323 :tag "Org"
324 :group 'outlines
325 :group 'calendar)
327 (defcustom org-mode-hook nil
328 "Mode hook for Org-mode, run after the mode was turned on."
329 :group 'org
330 :type 'hook)
332 (defcustom org-load-hook nil
333 "Hook that is run after org.el has been loaded."
334 :group 'org
335 :type 'hook)
337 (defcustom org-log-buffer-setup-hook nil
338 "Hook that is run after an Org log buffer is created."
339 :group 'org
340 :version "24.1"
341 :type 'hook)
343 (defvar org-modules) ; defined below
344 (defvar org-modules-loaded nil
345 "Have the modules been loaded already?")
347 (defun org-load-modules-maybe (&optional force)
348 "Load all extensions listed in `org-modules'."
349 (when (or force (not org-modules-loaded))
350 (mapc (lambda (ext)
351 (condition-case nil (require ext)
352 (error (message "Problems while trying to load feature `%s'" ext))))
353 org-modules)
354 (setq org-modules-loaded t)))
356 (defun org-set-modules (var value)
357 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
358 (set var value)
359 (when (featurep 'org)
360 (org-load-modules-maybe 'force)))
362 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
363 "Modules that should always be loaded together with org.el.
365 If a description starts with <C>, the file is not part of Emacs
366 and loading it will require that you have downloaded and properly
367 installed the Org mode distribution.
369 You can also use this system to load external packages (i.e. neither Org
370 core modules, nor modules from the CONTRIB directory). Just add symbols
371 to the end of the list. If the package is called org-xyz.el, then you need
372 to add the symbol `xyz', and the package must have a call to:
374 \(provide 'org-xyz)
376 For export specific modules, see also `org-export-backends'."
377 :group 'org
378 :set 'org-set-modules
379 :version "24.4"
380 :package-version '(Org . "8.0")
381 :type
382 '(set :greedy t
383 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
384 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
385 (const :tag " crypt: Encryption of subtrees" org-crypt)
386 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
387 (const :tag " docview: Links to doc-view buffers" org-docview)
388 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
389 (const :tag " habit: Track your consistency with habits" org-habit)
390 (const :tag " id: Global IDs for identifying entries" org-id)
391 (const :tag " info: Links to Info nodes" org-info)
392 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
393 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
394 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
395 (const :tag " mouse: Additional mouse support" org-mouse)
396 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
397 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
398 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
400 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
401 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
402 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
403 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
404 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
405 (const :tag "C collector: Collect properties into tables" org-collector)
406 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
407 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
408 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
409 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
410 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
411 (const :tag "C eval: Include command output as text" org-eval)
412 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
413 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
414 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
415 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
416 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
417 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
418 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
419 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
420 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
421 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
422 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
423 (const :tag "C mew: Links to Mew folders/messages" org-mew)
424 (const :tag "C mtags: Support for muse-like tags" org-mtags)
425 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
426 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
427 (const :tag "C registry: A registry for Org-mode links" org-registry)
428 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
429 (const :tag "C secretary: Team management with org-mode" org-secretary)
430 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
431 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
432 (const :tag "C track: Keep up with Org-mode development" org-track)
433 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
434 (const :tag "C vm: Links to VM folders/messages" org-vm)
435 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
436 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
437 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
439 (defvar org-export--registered-backends) ; From ox.el.
440 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
441 (declare-function org-export-backend-name "ox" (backend))
442 (defcustom org-export-backends '(ascii html icalendar latex)
443 "List of export back-ends that should be always available.
445 If a description starts with <C>, the file is not part of Emacs
446 and loading it will require that you have downloaded and properly
447 installed the Org mode distribution.
449 Unlike to `org-modules', libraries in this list will not be
450 loaded along with Org, but only once the export framework is
451 needed.
453 This variable needs to be set before org.el is loaded. If you
454 need to make a change while Emacs is running, use the customize
455 interface or run the following code, where VAL stands for the new
456 value of the variable, after updating it:
458 \(progn
459 \(setq org-export--registered-backends
460 \(org-remove-if-not
461 \(lambda (backend)
462 \(let ((name (org-export-backend-name backend)))
463 \(or (memq name val)
464 \(catch 'parentp
465 \(dolist (b val)
466 \(and (org-export-derived-backend-p b name)
467 \(throw 'parentp t)))))))
468 org-export--registered-backends))
469 \(let ((new-list (mapcar 'org-export-backend-name
470 org-export--registered-backends)))
471 \(dolist (backend val)
472 \(cond
473 \((not (load (format \"ox-%s\" backend) t t))
474 \(message \"Problems while trying to load export back-end `%s'\"
475 backend))
476 \((not (memq backend new-list)) (push backend new-list))))
477 \(set-default 'org-export-backends new-list)))
479 Adding a back-end to this list will also pull the back-end it
480 depends on, if any."
481 :group 'org
482 :group 'org-export
483 :version "24.4"
484 :package-version '(Org . "8.0")
485 :initialize 'custom-initialize-set
486 :set (lambda (var val)
487 (if (not (featurep 'ox)) (set-default var val)
488 ;; Any back-end not required anymore (not present in VAL and not
489 ;; a parent of any back-end in the new value) is removed from the
490 ;; list of registered back-ends.
491 (setq org-export--registered-backends
492 (org-remove-if-not
493 (lambda (backend)
494 (let ((name (org-export-backend-name backend)))
495 (or (memq name val)
496 (catch 'parentp
497 (dolist (b val)
498 (and (org-export-derived-backend-p b name)
499 (throw 'parentp t)))))))
500 org-export--registered-backends))
501 ;; Now build NEW-LIST of both new back-ends and required
502 ;; parents.
503 (let ((new-list (mapcar 'org-export-backend-name
504 org-export--registered-backends)))
505 (dolist (backend val)
506 (cond
507 ((not (load (format "ox-%s" backend) t t))
508 (message "Problems while trying to load export back-end `%s'"
509 backend))
510 ((not (memq backend new-list)) (push backend new-list))))
511 ;; Set VAR to that list with fixed dependencies.
512 (set-default var new-list))))
513 :type '(set :greedy t
514 (const :tag " ascii Export buffer to ASCII format" ascii)
515 (const :tag " beamer Export buffer to Beamer presentation" beamer)
516 (const :tag " html Export buffer to HTML format" html)
517 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
518 (const :tag " latex Export buffer to LaTeX format" latex)
519 (const :tag " man Export buffer to MAN format" man)
520 (const :tag " md Export buffer to Markdown format" md)
521 (const :tag " odt Export buffer to ODT format" odt)
522 (const :tag " org Export buffer to Org format" org)
523 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
524 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
525 (const :tag "C deck Export buffer to deck.js presentations" deck)
526 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
527 (const :tag "C groff Export buffer to Groff format" groff)
528 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
529 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
530 (const :tag "C s5 Export buffer to s5 presentations" s5)
531 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
533 (eval-after-load 'ox
534 '(mapc
535 (lambda (backend)
536 (condition-case nil (require (intern (format "ox-%s" backend)))
537 (error (message "Problems while trying to load export back-end `%s'"
538 backend))))
539 org-export-backends))
541 (defcustom org-support-shift-select nil
542 "Non-nil means make shift-cursor commands select text when possible.
544 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
545 start selecting a region, or enlarge regions started in this way.
546 In Org-mode, in special contexts, these same keys are used for
547 other purposes, important enough to compete with shift selection.
548 Org tries to balance these needs by supporting `shift-select-mode'
549 outside these special contexts, under control of this variable.
551 The default of this variable is nil, to avoid confusing behavior. Shifted
552 cursor keys will then execute Org commands in the following contexts:
553 - on a headline, changing TODO state (left/right) and priority (up/down)
554 - on a time stamp, changing the time
555 - in a plain list item, changing the bullet type
556 - in a property definition line, switching between allowed values
557 - in the BEGIN line of a clock table (changing the time block).
558 Outside these contexts, the commands will throw an error.
560 When this variable is t and the cursor is not in a special
561 context, Org-mode will support shift-selection for making and
562 enlarging regions. To make this more effective, the bullet
563 cycling will no longer happen anywhere in an item line, but only
564 if the cursor is exactly on the bullet.
566 If you set this variable to the symbol `always', then the keys
567 will not be special in headlines, property lines, and item lines,
568 to make shift selection work there as well. If this is what you
569 want, you can use the following alternative commands: `C-c C-t'
570 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
571 can be used to switch TODO sets, `C-c -' to cycle item bullet
572 types, and properties can be edited by hand or in column view.
574 However, when the cursor is on a timestamp, shift-cursor commands
575 will still edit the time stamp - this is just too good to give up.
577 XEmacs user should have this variable set to nil, because
578 `shift-select-mode' is in Emacs 23 or later only."
579 :group 'org
580 :type '(choice
581 (const :tag "Never" nil)
582 (const :tag "When outside special context" t)
583 (const :tag "Everywhere except timestamps" always)))
585 (defcustom org-loop-over-headlines-in-active-region nil
586 "Shall some commands act upon headlines in the active region?
588 When set to `t', some commands will be performed in all headlines
589 within the active region.
591 When set to `start-level', some commands will be performed in all
592 headlines within the active region, provided that these headlines
593 are of the same level than the first one.
595 When set to a string, those commands will be performed on the
596 matching headlines within the active region. Such string must be
597 a tags/property/todo match as it is used in the agenda tags view.
599 The list of commands is: `org-schedule', `org-deadline',
600 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
601 `org-archive-to-archive-sibling'. The archiving commands skip
602 already archived entries."
603 :type '(choice (const :tag "Don't loop" nil)
604 (const :tag "All headlines in active region" t)
605 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
606 (string :tag "Tags/Property/Todo matcher"))
607 :version "24.1"
608 :group 'org-todo
609 :group 'org-archive)
611 (defgroup org-startup nil
612 "Options concerning startup of Org-mode."
613 :tag "Org Startup"
614 :group 'org)
616 (defcustom org-startup-folded t
617 "Non-nil means entering Org-mode will switch to OVERVIEW.
618 This can also be configured on a per-file basis by adding one of
619 the following lines anywhere in the buffer:
621 #+STARTUP: fold (or `overview', this is equivalent)
622 #+STARTUP: nofold (or `showall', this is equivalent)
623 #+STARTUP: content
624 #+STARTUP: showeverything
626 By default, this option is ignored when Org opens agenda files
627 for the first time. If you want the agenda to honor the startup
628 option, set `org-agenda-inhibit-startup' to nil."
629 :group 'org-startup
630 :type '(choice
631 (const :tag "nofold: show all" nil)
632 (const :tag "fold: overview" t)
633 (const :tag "content: all headlines" content)
634 (const :tag "show everything, even drawers" showeverything)))
636 (defcustom org-startup-truncated t
637 "Non-nil means entering Org-mode will set `truncate-lines'.
638 This is useful since some lines containing links can be very long and
639 uninteresting. Also tables look terrible when wrapped."
640 :group 'org-startup
641 :type 'boolean)
643 (defcustom org-startup-indented nil
644 "Non-nil means turn on `org-indent-mode' on startup.
645 This can also be configured on a per-file basis by adding one of
646 the following lines anywhere in the buffer:
648 #+STARTUP: indent
649 #+STARTUP: noindent"
650 :group 'org-structure
651 :type '(choice
652 (const :tag "Not" nil)
653 (const :tag "Globally (slow on startup in large files)" t)))
655 (defcustom org-use-sub-superscripts t
656 "Non-nil means interpret \"_\" and \"^\" for display.
658 If you want to control how Org exports those characters, see
659 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
660 used to be an alias for `org-export-with-sub-superscripts' in
661 Org <8.0, it is not anymore.
663 When this option is turned on, you can use TeX-like syntax for
664 sub- and superscripts within the buffer. Several characters after
665 \"_\" or \"^\" will be considered as a single item - so grouping
666 with {} is normally not needed. For example, the following things
667 will be parsed as single sub- or superscripts:
669 10^24 or 10^tau several digits will be considered 1 item.
670 10^-12 or 10^-tau a leading sign with digits or a word
671 x^2-y^3 will be read as x^2 - y^3, because items are
672 terminated by almost any nonword/nondigit char.
673 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
675 Still, ambiguity is possible. So when in doubt, use {} to enclose
676 the sub/superscript. If you set this variable to the symbol `{}',
677 the braces are *required* in order to trigger interpretations as
678 sub/superscript. This can be helpful in documents that need \"_\"
679 frequently in plain text."
680 :group 'org-startup
681 :version "24.4"
682 :package-version '(Org . "8.0")
683 :type '(choice
684 (const :tag "Always interpret" t)
685 (const :tag "Only with braces" {})
686 (const :tag "Never interpret" nil)))
688 (defcustom org-startup-with-beamer-mode nil
689 "Non-nil means turn on `org-beamer-mode' on startup.
690 This can also be configured on a per-file basis by adding one of
691 the following lines anywhere in the buffer:
693 #+STARTUP: beamer"
694 :group 'org-startup
695 :version "24.1"
696 :type 'boolean)
698 (defcustom org-startup-align-all-tables nil
699 "Non-nil means align all tables when visiting a file.
700 This is useful when the column width in tables is forced with <N> cookies
701 in table fields. Such tables will look correct only after the first re-align.
702 This can also be configured on a per-file basis by adding one of
703 the following lines anywhere in the buffer:
704 #+STARTUP: align
705 #+STARTUP: noalign"
706 :group 'org-startup
707 :type 'boolean)
709 (defcustom org-startup-with-inline-images nil
710 "Non-nil means show inline images when loading a new Org file.
711 This can also be configured on a per-file basis by adding one of
712 the following lines anywhere in the buffer:
713 #+STARTUP: inlineimages
714 #+STARTUP: noinlineimages"
715 :group 'org-startup
716 :version "24.1"
717 :type 'boolean)
719 (defcustom org-startup-with-latex-preview nil
720 "Non-nil means preview LaTeX fragments when loading a new Org file.
722 This can also be configured on a per-file basis by adding one of
723 the following lines anywhere in the buffer:
724 #+STARTUP: latexpreview
725 #+STARTUP: nolatexpreview"
726 :group 'org-startup
727 :version "24.4"
728 :package-version '(Org . "8.0")
729 :type 'boolean)
731 (defcustom org-insert-mode-line-in-empty-file nil
732 "Non-nil means insert the first line setting Org-mode in empty files.
733 When the function `org-mode' is called interactively in an empty file, this
734 normally means that the file name does not automatically trigger Org-mode.
735 To ensure that the file will always be in Org-mode in the future, a
736 line enforcing Org-mode will be inserted into the buffer, if this option
737 has been set."
738 :group 'org-startup
739 :type 'boolean)
741 (defcustom org-replace-disputed-keys nil
742 "Non-nil means use alternative key bindings for some keys.
743 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
744 These keys are also used by other packages like shift-selection-mode'
745 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
746 If you want to use Org-mode together with one of these other modes,
747 or more generally if you would like to move some Org-mode commands to
748 other keys, set this variable and configure the keys with the variable
749 `org-disputed-keys'.
751 This option is only relevant at load-time of Org-mode, and must be set
752 *before* org.el is loaded. Changing it requires a restart of Emacs to
753 become effective."
754 :group 'org-startup
755 :type 'boolean)
757 (defcustom org-use-extra-keys nil
758 "Non-nil means use extra key sequence definitions for certain commands.
759 This happens automatically if you run XEmacs or if `window-system'
760 is nil. This variable lets you do the same manually. You must
761 set it before loading org.
763 Example: on Carbon Emacs 22 running graphically, with an external
764 keyboard on a Powerbook, the default way of setting M-left might
765 not work for either Alt or ESC. Setting this variable will make
766 it work for ESC."
767 :group 'org-startup
768 :type 'boolean)
770 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
772 (defcustom org-disputed-keys
773 '(([(shift up)] . [(meta p)])
774 ([(shift down)] . [(meta n)])
775 ([(shift left)] . [(meta -)])
776 ([(shift right)] . [(meta +)])
777 ([(control shift right)] . [(meta shift +)])
778 ([(control shift left)] . [(meta shift -)]))
779 "Keys for which Org-mode and other modes compete.
780 This is an alist, cars are the default keys, second element specifies
781 the alternative to use when `org-replace-disputed-keys' is t.
783 Keys can be specified in any syntax supported by `define-key'.
784 The value of this option takes effect only at Org-mode's startup,
785 therefore you'll have to restart Emacs to apply it after changing."
786 :group 'org-startup
787 :type 'alist)
789 (defun org-key (key)
790 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
791 Or return the original if not disputed.
792 Also apply the translations defined in `org-xemacs-key-equivalents'."
793 (when org-replace-disputed-keys
794 (let* ((nkey (key-description key))
795 (x (org-find-if (lambda (x)
796 (equal (key-description (car x)) nkey))
797 org-disputed-keys)))
798 (setq key (if x (cdr x) key))))
799 (when (featurep 'xemacs)
800 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
801 key)
803 (defun org-find-if (predicate seq)
804 (catch 'exit
805 (while seq
806 (if (funcall predicate (car seq))
807 (throw 'exit (car seq))
808 (pop seq)))))
810 (defun org-defkey (keymap key def)
811 "Define a key, possibly translated, as returned by `org-key'."
812 (define-key keymap (org-key key) def))
814 (defcustom org-ellipsis nil
815 "The ellipsis to use in the Org-mode outline.
816 When nil, just use the standard three dots. When a string, use that instead,
817 When a face, use the standard 3 dots, but with the specified face.
818 The change affects only Org-mode (which will then use its own display table).
819 Changing this requires executing `M-x org-mode' in a buffer to become
820 effective."
821 :group 'org-startup
822 :type '(choice (const :tag "Default" nil)
823 (face :tag "Face" :value org-warning)
824 (string :tag "String" :value "...#")))
826 (defvar org-display-table nil
827 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
829 (defgroup org-keywords nil
830 "Keywords in Org-mode."
831 :tag "Org Keywords"
832 :group 'org)
834 (defcustom org-deadline-string "DEADLINE:"
835 "String to mark deadline entries.
836 A deadline is this string, followed by a time stamp. Should be a word,
837 terminated by a colon. You can insert a schedule keyword and
838 a timestamp with \\[org-deadline].
839 Changes become only effective after restarting Emacs."
840 :group 'org-keywords
841 :type 'string)
843 (defcustom org-scheduled-string "SCHEDULED:"
844 "String to mark scheduled TODO entries.
845 A schedule is this string, followed by a time stamp. Should be a word,
846 terminated by a colon. You can insert a schedule keyword and
847 a timestamp with \\[org-schedule].
848 Changes become only effective after restarting Emacs."
849 :group 'org-keywords
850 :type 'string)
852 (defcustom org-closed-string "CLOSED:"
853 "String used as the prefix for timestamps logging closing a TODO entry."
854 :group 'org-keywords
855 :type 'string)
857 (defcustom org-clock-string "CLOCK:"
858 "String used as prefix for timestamps clocking work hours on an item."
859 :group 'org-keywords
860 :type 'string)
862 (defcustom org-closed-keep-when-no-todo nil
863 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
864 :group 'org-todo
865 :group 'org-keywords
866 :version "24.4"
867 :package-version '(Org . "8.0")
868 :type 'boolean)
870 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
871 org-scheduled-string "\\|"
872 org-deadline-string "\\|"
873 org-closed-string "\\|"
874 org-clock-string "\\)")
875 "Matches a line with planning or clock info.")
877 (defcustom org-comment-string "COMMENT"
878 "Entries starting with this keyword will never be exported.
879 An entry can be toggled between COMMENT and normal with
880 \\[org-toggle-comment].
881 Changes become only effective after restarting Emacs."
882 :group 'org-keywords
883 :type 'string)
885 (defcustom org-quote-string "QUOTE"
886 "Entries starting with this keyword will be exported in fixed-width font.
887 Quoting applies only to the text in the entry following the headline, and does
888 not extend beyond the next headline, even if that is lower level.
889 An entry can be toggled between QUOTE and normal with
890 \\[org-toggle-fixed-width-section]."
891 :group 'org-keywords
892 :type 'string)
894 (defconst org-repeat-re
895 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
896 "Regular expression for specifying repeated events.
897 After a match, group 1 contains the repeat expression.")
899 (defgroup org-structure nil
900 "Options concerning the general structure of Org-mode files."
901 :tag "Org Structure"
902 :group 'org)
904 (defgroup org-reveal-location nil
905 "Options about how to make context of a location visible."
906 :tag "Org Reveal Location"
907 :group 'org-structure)
909 (defconst org-context-choice
910 '(choice
911 (const :tag "Always" t)
912 (const :tag "Never" nil)
913 (repeat :greedy t :tag "Individual contexts"
914 (cons
915 (choice :tag "Context"
916 (const agenda)
917 (const org-goto)
918 (const occur-tree)
919 (const tags-tree)
920 (const link-search)
921 (const mark-goto)
922 (const bookmark-jump)
923 (const isearch)
924 (const default))
925 (boolean))))
926 "Contexts for the reveal options.")
928 (defcustom org-show-hierarchy-above '((default . t))
929 "Non-nil means show full hierarchy when revealing a location.
930 Org-mode often shows locations in an org-mode file which might have
931 been invisible before. When this is set, the hierarchy of headings
932 above the exposed location is shown.
933 Turning this off for example for sparse trees makes them very compact.
934 Instead of t, this can also be an alist specifying this option for different
935 contexts. Valid contexts are
936 agenda when exposing an entry from the agenda
937 org-goto when using the command `org-goto' on key C-c C-j
938 occur-tree when using the command `org-occur' on key C-c /
939 tags-tree when constructing a sparse tree based on tags matches
940 link-search when exposing search matches associated with a link
941 mark-goto when exposing the jump goal of a mark
942 bookmark-jump when exposing a bookmark location
943 isearch when exiting from an incremental search
944 default default for all contexts not set explicitly"
945 :group 'org-reveal-location
946 :type org-context-choice)
948 (defcustom org-show-following-heading '((default . nil))
949 "Non-nil means show following heading when revealing a location.
950 Org-mode often shows locations in an org-mode file which might have
951 been invisible before. When this is set, the heading following the
952 match is shown.
953 Turning this off for example for sparse trees makes them very compact,
954 but makes it harder to edit the location of the match. In such a case,
955 use the command \\[org-reveal] to show more context.
956 Instead of t, this can also be an alist specifying this option for different
957 contexts. See `org-show-hierarchy-above' for valid contexts."
958 :group 'org-reveal-location
959 :type org-context-choice)
961 (defcustom org-show-siblings '((default . nil) (isearch t) (bookmark-jump t))
962 "Non-nil means show all sibling heading when revealing a location.
963 Org-mode often shows locations in an org-mode file which might have
964 been invisible before. When this is set, the sibling of the current entry
965 heading are all made visible. If `org-show-hierarchy-above' is t,
966 the same happens on each level of the hierarchy above the current entry.
968 By default this is on for the isearch context, off for all other contexts.
969 Turning this off for example for sparse trees makes them very compact,
970 but makes it harder to edit the location of the match. In such a case,
971 use the command \\[org-reveal] to show more context.
972 Instead of t, this can also be an alist specifying this option for different
973 contexts. See `org-show-hierarchy-above' for valid contexts."
974 :group 'org-reveal-location
975 :type org-context-choice
976 :version "24.4"
977 :package-version '(Org . "8.0"))
979 (defcustom org-show-entry-below '((default . nil))
980 "Non-nil means show the entry below a headline when revealing a location.
981 Org-mode often shows locations in an org-mode file which might have
982 been invisible before. When this is set, the text below the headline that is
983 exposed is also shown.
985 By default this is off for all contexts.
986 Instead of t, this can also be an alist specifying this option for different
987 contexts. See `org-show-hierarchy-above' for valid contexts."
988 :group 'org-reveal-location
989 :type org-context-choice)
991 (defcustom org-indirect-buffer-display 'other-window
992 "How should indirect tree buffers be displayed?
993 This applies to indirect buffers created with the commands
994 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
995 Valid values are:
996 current-window Display in the current window
997 other-window Just display in another window.
998 dedicated-frame Create one new frame, and re-use it each time.
999 new-frame Make a new frame each time. Note that in this case
1000 previously-made indirect buffers are kept, and you need to
1001 kill these buffers yourself."
1002 :group 'org-structure
1003 :group 'org-agenda-windows
1004 :type '(choice
1005 (const :tag "In current window" current-window)
1006 (const :tag "In current frame, other window" other-window)
1007 (const :tag "Each time a new frame" new-frame)
1008 (const :tag "One dedicated frame" dedicated-frame)))
1010 (defcustom org-use-speed-commands nil
1011 "Non-nil means activate single letter commands at beginning of a headline.
1012 This may also be a function to test for appropriate locations where speed
1013 commands should be active."
1014 :group 'org-structure
1015 :type '(choice
1016 (const :tag "Never" nil)
1017 (const :tag "At beginning of headline stars" t)
1018 (function)))
1020 (defcustom org-speed-commands-user nil
1021 "Alist of additional speed commands.
1022 This list will be checked before `org-speed-commands-default'
1023 when the variable `org-use-speed-commands' is non-nil
1024 and when the cursor is at the beginning of a headline.
1025 The car if each entry is a string with a single letter, which must
1026 be assigned to `self-insert-command' in the global map.
1027 The cdr is either a command to be called interactively, a function
1028 to be called, or a form to be evaluated.
1029 An entry that is just a list with a single string will be interpreted
1030 as a descriptive headline that will be added when listing the speed
1031 commands in the Help buffer using the `?' speed command."
1032 :group 'org-structure
1033 :type '(repeat :value ("k" . ignore)
1034 (choice :value ("k" . ignore)
1035 (list :tag "Descriptive Headline" (string :tag "Headline"))
1036 (cons :tag "Letter and Command"
1037 (string :tag "Command letter")
1038 (choice
1039 (function)
1040 (sexp))))))
1042 (defcustom org-bookmark-names-plist
1043 '(:last-capture "org-capture-last-stored"
1044 :last-refile "org-refile-last-stored"
1045 :last-capture-marker "org-capture-last-stored-marker")
1046 "Names for bookmarks automatically set by some Org commands.
1047 This can provide strings as names for a number of bookmarks Org sets
1048 automatically. The following keys are currently implemented:
1049 :last-capture
1050 :last-capture-marker
1051 :last-refile
1052 When a key does not show up in the property list, the corresponding bookmark
1053 is not set."
1054 :group 'org-structure
1055 :type 'plist)
1057 (defgroup org-cycle nil
1058 "Options concerning visibility cycling in Org-mode."
1059 :tag "Org Cycle"
1060 :group 'org-structure)
1062 (defcustom org-cycle-skip-children-state-if-no-children t
1063 "Non-nil means skip CHILDREN state in entries that don't have any."
1064 :group 'org-cycle
1065 :type 'boolean)
1067 (defcustom org-cycle-max-level nil
1068 "Maximum level which should still be subject to visibility cycling.
1069 Levels higher than this will, for cycling, be treated as text, not a headline.
1070 When `org-odd-levels-only' is set, a value of N in this variable actually
1071 means 2N-1 stars as the limiting headline.
1072 When nil, cycle all levels.
1073 Note that the limiting level of cycling is also influenced by
1074 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1075 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1076 than its value."
1077 :group 'org-cycle
1078 :type '(choice
1079 (const :tag "No limit" nil)
1080 (integer :tag "Maximum level")))
1082 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
1083 "Names of drawers. Drawers are not opened by cycling on the headline above.
1084 Drawers only open with a TAB on the drawer line itself. A drawer looks like
1085 this:
1086 :DRAWERNAME:
1087 .....
1088 :END:
1089 The drawer \"PROPERTIES\" is special for capturing properties through
1090 the property API.
1092 Drawers can be defined on the per-file basis with a line like:
1094 #+DRAWERS: HIDDEN STATE PROPERTIES"
1095 :group 'org-structure
1096 :group 'org-cycle
1097 :type '(repeat (string :tag "Drawer Name")))
1099 (defcustom org-hide-block-startup nil
1100 "Non-nil means entering Org-mode will fold all blocks.
1101 This can also be set in on a per-file basis with
1103 #+STARTUP: hideblocks
1104 #+STARTUP: showblocks"
1105 :group 'org-startup
1106 :group 'org-cycle
1107 :type 'boolean)
1109 (defcustom org-cycle-global-at-bob nil
1110 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1111 This makes it possible to do global cycling without having to use S-TAB or
1112 \\[universal-argument] TAB. For this special case to work, the first line
1113 of the buffer must not be a headline -- it may be empty or some other text.
1114 When used in this way, `org-cycle-hook' is disabled temporarily to make
1115 sure the cursor stays at the beginning of the buffer. When this option is
1116 nil, don't do anything special at the beginning of the buffer."
1117 :group 'org-cycle
1118 :type 'boolean)
1120 (defcustom org-cycle-level-after-item/entry-creation t
1121 "Non-nil means cycle entry level or item indentation in new empty entries.
1123 When the cursor is at the end of an empty headline, i.e., with only stars
1124 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1125 and then all possible ancestor states, before returning to the original state.
1126 This makes data entry extremely fast: M-RET to create a new headline,
1127 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1129 When the cursor is at the end of an empty plain list item, one TAB will
1130 make it a subitem, two or more tabs will back up to make this an item
1131 higher up in the item hierarchy."
1132 :group 'org-cycle
1133 :type 'boolean)
1135 (defcustom org-cycle-emulate-tab t
1136 "Where should `org-cycle' emulate TAB.
1137 nil Never
1138 white Only in completely white lines
1139 whitestart Only at the beginning of lines, before the first non-white char
1140 t Everywhere except in headlines
1141 exc-hl-bol Everywhere except at the start of a headline
1142 If TAB is used in a place where it does not emulate TAB, the current subtree
1143 visibility is cycled."
1144 :group 'org-cycle
1145 :type '(choice (const :tag "Never" nil)
1146 (const :tag "Only in completely white lines" white)
1147 (const :tag "Before first char in a line" whitestart)
1148 (const :tag "Everywhere except in headlines" t)
1149 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1151 (defcustom org-cycle-separator-lines 2
1152 "Number of empty lines needed to keep an empty line between collapsed trees.
1153 If you leave an empty line between the end of a subtree and the following
1154 headline, this empty line is hidden when the subtree is folded.
1155 Org-mode will leave (exactly) one empty line visible if the number of
1156 empty lines is equal or larger to the number given in this variable.
1157 So the default 2 means at least 2 empty lines after the end of a subtree
1158 are needed to produce free space between a collapsed subtree and the
1159 following headline.
1161 If the number is negative, and the number of empty lines is at least -N,
1162 all empty lines are shown.
1164 Special case: when 0, never leave empty lines in collapsed view."
1165 :group 'org-cycle
1166 :type 'integer)
1167 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1169 (defcustom org-pre-cycle-hook nil
1170 "Hook that is run before visibility cycling is happening.
1171 The function(s) in this hook must accept a single argument which indicates
1172 the new state that will be set right after running this hook. The
1173 argument is a symbol. Before a global state change, it can have the values
1174 `overview', `content', or `all'. Before a local state change, it can have
1175 the values `folded', `children', or `subtree'."
1176 :group 'org-cycle
1177 :type 'hook)
1179 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1180 org-cycle-hide-drawers
1181 org-cycle-hide-inline-tasks
1182 org-cycle-show-empty-lines
1183 org-optimize-window-after-visibility-change)
1184 "Hook that is run after `org-cycle' has changed the buffer visibility.
1185 The function(s) in this hook must accept a single argument which indicates
1186 the new state that was set by the most recent `org-cycle' command. The
1187 argument is a symbol. After a global state change, it can have the values
1188 `overview', `contents', or `all'. After a local state change, it can have
1189 the values `folded', `children', or `subtree'."
1190 :group 'org-cycle
1191 :type 'hook)
1193 (defgroup org-edit-structure nil
1194 "Options concerning structure editing in Org-mode."
1195 :tag "Org Edit Structure"
1196 :group 'org-structure)
1198 (defcustom org-odd-levels-only nil
1199 "Non-nil means skip even levels and only use odd levels for the outline.
1200 This has the effect that two stars are being added/taken away in
1201 promotion/demotion commands. It also influences how levels are
1202 handled by the exporters.
1203 Changing it requires restart of `font-lock-mode' to become effective
1204 for fontification also in regions already fontified.
1205 You may also set this on a per-file basis by adding one of the following
1206 lines to the buffer:
1208 #+STARTUP: odd
1209 #+STARTUP: oddeven"
1210 :group 'org-edit-structure
1211 :group 'org-appearance
1212 :type 'boolean)
1214 (defcustom org-adapt-indentation t
1215 "Non-nil means adapt indentation to outline node level.
1217 When this variable is set, Org assumes that you write outlines by
1218 indenting text in each node to align with the headline (after the stars).
1219 The following issues are influenced by this variable:
1221 - When this is set and the *entire* text in an entry is indented, the
1222 indentation is increased by one space in a demotion command, and
1223 decreased by one in a promotion command. If any line in the entry
1224 body starts with text at column 0, indentation is not changed at all.
1226 - Property drawers and planning information is inserted indented when
1227 this variable s set. When nil, they will not be indented.
1229 - TAB indents a line relative to context. The lines below a headline
1230 will be indented when this variable is set.
1232 Note that this is all about true indentation, by adding and removing
1233 space characters. See also `org-indent.el' which does level-dependent
1234 indentation in a virtual way, i.e. at display time in Emacs."
1235 :group 'org-edit-structure
1236 :type 'boolean)
1238 (defcustom org-special-ctrl-a/e nil
1239 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1241 When t, `C-a' will bring back the cursor to the beginning of the
1242 headline text, i.e. after the stars and after a possible TODO
1243 keyword. In an item, this will be the position after bullet and
1244 check-box, if any. When the cursor is already at that position,
1245 another `C-a' will bring it to the beginning of the line.
1247 `C-e' will jump to the end of the headline, ignoring the presence
1248 of tags in the headline. A second `C-e' will then jump to the
1249 true end of the line, after any tags. This also means that, when
1250 this variable is non-nil, `C-e' also will never jump beyond the
1251 end of the heading of a folded section, i.e. not after the
1252 ellipses.
1254 When set to the symbol `reversed', the first `C-a' or `C-e' works
1255 normally, going to the true line boundary first. Only a directly
1256 following, identical keypress will bring the cursor to the
1257 special positions.
1259 This may also be a cons cell where the behavior for `C-a' and
1260 `C-e' is set separately."
1261 :group 'org-edit-structure
1262 :type '(choice
1263 (const :tag "off" nil)
1264 (const :tag "on: after stars/bullet and before tags first" t)
1265 (const :tag "reversed: true line boundary first" reversed)
1266 (cons :tag "Set C-a and C-e separately"
1267 (choice :tag "Special C-a"
1268 (const :tag "off" nil)
1269 (const :tag "on: after stars/bullet first" t)
1270 (const :tag "reversed: before stars/bullet first" reversed))
1271 (choice :tag "Special C-e"
1272 (const :tag "off" nil)
1273 (const :tag "on: before tags first" t)
1274 (const :tag "reversed: after tags first" reversed)))))
1275 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1277 (defcustom org-special-ctrl-k nil
1278 "Non-nil means `C-k' will behave specially in headlines.
1279 When nil, `C-k' will call the default `kill-line' command.
1280 When t, the following will happen while the cursor is in the headline:
1282 - When the cursor is at the beginning of a headline, kill the entire
1283 line and possible the folded subtree below the line.
1284 - When in the middle of the headline text, kill the headline up to the tags.
1285 - When after the headline text, kill the tags."
1286 :group 'org-edit-structure
1287 :type 'boolean)
1289 (defcustom org-ctrl-k-protect-subtree nil
1290 "Non-nil means, do not delete a hidden subtree with C-k.
1291 When set to the symbol `error', simply throw an error when C-k is
1292 used to kill (part-of) a headline that has hidden text behind it.
1293 Any other non-nil value will result in a query to the user, if it is
1294 OK to kill that hidden subtree. When nil, kill without remorse."
1295 :group 'org-edit-structure
1296 :version "24.1"
1297 :type '(choice
1298 (const :tag "Do not protect hidden subtrees" nil)
1299 (const :tag "Protect hidden subtrees with a security query" t)
1300 (const :tag "Never kill a hidden subtree with C-k" error)))
1302 (defcustom org-special-ctrl-o t
1303 "Non-nil means, make `C-o' insert a row in tables."
1304 :group 'org-edit-structure
1305 :type 'boolean)
1307 (defcustom org-catch-invisible-edits nil
1308 "Check if in invisible region before inserting or deleting a character.
1309 Valid values are:
1311 nil Do not check, so just do invisible edits.
1312 error Throw an error and do nothing.
1313 show Make point visible, and do the requested edit.
1314 show-and-error Make point visible, then throw an error and abort the edit.
1315 smart Make point visible, and do insertion/deletion if it is
1316 adjacent to visible text and the change feels predictable.
1317 Never delete a previously invisible character or add in the
1318 middle or right after an invisible region. Basically, this
1319 allows insertion and backward-delete right before ellipses.
1320 FIXME: maybe in this case we should not even show?"
1321 :group 'org-edit-structure
1322 :version "24.1"
1323 :type '(choice
1324 (const :tag "Do not check" nil)
1325 (const :tag "Throw error when trying to edit" error)
1326 (const :tag "Unhide, but do not do the edit" show-and-error)
1327 (const :tag "Show invisible part and do the edit" show)
1328 (const :tag "Be smart and do the right thing" smart)))
1330 (defcustom org-yank-folded-subtrees t
1331 "Non-nil means when yanking subtrees, fold them.
1332 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1333 it starts with a heading and all other headings in it are either children
1334 or siblings, then fold all the subtrees. However, do this only if no
1335 text after the yank would be swallowed into a folded tree by this action."
1336 :group 'org-edit-structure
1337 :type 'boolean)
1339 (defcustom org-yank-adjusted-subtrees nil
1340 "Non-nil means when yanking subtrees, adjust the level.
1341 With this setting, `org-paste-subtree' is used to insert the subtree, see
1342 this function for details."
1343 :group 'org-edit-structure
1344 :type 'boolean)
1346 (defcustom org-M-RET-may-split-line '((default . t))
1347 "Non-nil means M-RET will split the line at the cursor position.
1348 When nil, it will go to the end of the line before making a
1349 new line.
1350 You may also set this option in a different way for different
1351 contexts. Valid contexts are:
1353 headline when creating a new headline
1354 item when creating a new item
1355 table in a table field
1356 default the value to be used for all contexts not explicitly
1357 customized"
1358 :group 'org-structure
1359 :group 'org-table
1360 :type '(choice
1361 (const :tag "Always" t)
1362 (const :tag "Never" nil)
1363 (repeat :greedy t :tag "Individual contexts"
1364 (cons
1365 (choice :tag "Context"
1366 (const headline)
1367 (const item)
1368 (const table)
1369 (const default))
1370 (boolean)))))
1373 (defcustom org-insert-heading-respect-content nil
1374 "Non-nil means insert new headings after the current subtree.
1375 When nil, the new heading is created directly after the current line.
1376 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1377 this variable on for the duration of the command."
1378 :group 'org-structure
1379 :type 'boolean)
1381 (defcustom org-blank-before-new-entry '((heading . auto)
1382 (plain-list-item . auto))
1383 "Should `org-insert-heading' leave a blank line before new heading/item?
1384 The value is an alist, with `heading' and `plain-list-item' as CAR,
1385 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1386 which case Org will look at the surrounding headings/items and try to
1387 make an intelligent decision whether to insert a blank line or not.
1389 For plain lists, if `org-list-empty-line-terminates-plain-lists' is set,
1390 the setting here is ignored and no empty line is inserted to avoid breaking
1391 the list structure."
1392 :group 'org-edit-structure
1393 :type '(list
1394 (cons (const heading)
1395 (choice (const :tag "Never" nil)
1396 (const :tag "Always" t)
1397 (const :tag "Auto" auto)))
1398 (cons (const plain-list-item)
1399 (choice (const :tag "Never" nil)
1400 (const :tag "Always" t)
1401 (const :tag "Auto" auto)))))
1403 (defcustom org-insert-heading-hook nil
1404 "Hook being run after inserting a new heading."
1405 :group 'org-edit-structure
1406 :type 'hook)
1408 (defcustom org-enable-fixed-width-editor t
1409 "Non-nil means lines starting with \":\" are treated as fixed-width.
1410 This currently only means they are never auto-wrapped.
1411 When nil, such lines will be treated like ordinary lines.
1412 See also the QUOTE keyword."
1413 :group 'org-edit-structure
1414 :type 'boolean)
1416 (defcustom org-goto-auto-isearch t
1417 "Non-nil means typing characters in `org-goto' starts incremental search.
1418 When nil, you can use these keybindings to navigate the buffer:
1420 q Quit the org-goto interface
1421 n Go to the next visible heading
1422 p Go to the previous visible heading
1423 f Go one heading forward on same level
1424 b Go one heading backward on same level
1425 u Go one heading up"
1426 :group 'org-edit-structure
1427 :type 'boolean)
1429 (defgroup org-sparse-trees nil
1430 "Options concerning sparse trees in Org-mode."
1431 :tag "Org Sparse Trees"
1432 :group 'org-structure)
1434 (defcustom org-highlight-sparse-tree-matches t
1435 "Non-nil means highlight all matches that define a sparse tree.
1436 The highlights will automatically disappear the next time the buffer is
1437 changed by an edit command."
1438 :group 'org-sparse-trees
1439 :type 'boolean)
1441 (defcustom org-remove-highlights-with-change t
1442 "Non-nil means any change to the buffer will remove temporary highlights.
1443 Such highlights are created by `org-occur' and `org-clock-display'.
1444 When nil, `C-c C-c needs to be used to get rid of the highlights.
1445 The highlights created by `org-preview-latex-fragment' always need
1446 `C-c C-c' to be removed."
1447 :group 'org-sparse-trees
1448 :group 'org-time
1449 :type 'boolean)
1452 (defcustom org-occur-hook '(org-first-headline-recenter)
1453 "Hook that is run after `org-occur' has constructed a sparse tree.
1454 This can be used to recenter the window to show as much of the structure
1455 as possible."
1456 :group 'org-sparse-trees
1457 :type 'hook)
1459 (defgroup org-imenu-and-speedbar nil
1460 "Options concerning imenu and speedbar in Org-mode."
1461 :tag "Org Imenu and Speedbar"
1462 :group 'org-structure)
1464 (defcustom org-imenu-depth 2
1465 "The maximum level for Imenu access to Org-mode headlines.
1466 This also applied for speedbar access."
1467 :group 'org-imenu-and-speedbar
1468 :type 'integer)
1470 (defgroup org-table nil
1471 "Options concerning tables in Org-mode."
1472 :tag "Org Table"
1473 :group 'org)
1475 (defcustom org-enable-table-editor 'optimized
1476 "Non-nil means lines starting with \"|\" are handled by the table editor.
1477 When nil, such lines will be treated like ordinary lines.
1479 When equal to the symbol `optimized', the table editor will be optimized to
1480 do the following:
1481 - Automatic overwrite mode in front of whitespace in table fields.
1482 This makes the structure of the table stay in tact as long as the edited
1483 field does not exceed the column width.
1484 - Minimize the number of realigns. Normally, the table is aligned each time
1485 TAB or RET are pressed to move to another field. With optimization this
1486 happens only if changes to a field might have changed the column width.
1487 Optimization requires replacing the functions `self-insert-command',
1488 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1489 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1490 very good at guessing when a re-align will be necessary, but you can always
1491 force one with \\[org-ctrl-c-ctrl-c].
1493 If you would like to use the optimized version in Org-mode, but the
1494 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1496 This variable can be used to turn on and off the table editor during a session,
1497 but in order to toggle optimization, a restart is required.
1499 See also the variable `org-table-auto-blank-field'."
1500 :group 'org-table
1501 :type '(choice
1502 (const :tag "off" nil)
1503 (const :tag "on" t)
1504 (const :tag "on, optimized" optimized)))
1506 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1507 (version<= emacs-version "24.1"))
1508 "Non-nil means cluster self-insert commands for undo when possible.
1509 If this is set, then, like in the Emacs command loop, 20 consecutive
1510 characters will be undone together.
1511 This is configurable, because there is some impact on typing performance."
1512 :group 'org-table
1513 :type 'boolean)
1515 (defcustom org-table-tab-recognizes-table.el t
1516 "Non-nil means TAB will automatically notice a table.el table.
1517 When it sees such a table, it moves point into it and - if necessary -
1518 calls `table-recognize-table'."
1519 :group 'org-table-editing
1520 :type 'boolean)
1522 (defgroup org-link nil
1523 "Options concerning links in Org-mode."
1524 :tag "Org Link"
1525 :group 'org)
1527 (defvar org-link-abbrev-alist-local nil
1528 "Buffer-local version of `org-link-abbrev-alist', which see.
1529 The value of this is taken from the #+LINK lines.")
1530 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1532 (defcustom org-link-abbrev-alist nil
1533 "Alist of link abbreviations.
1534 The car of each element is a string, to be replaced at the start of a link.
1535 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1536 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1538 [[linkkey:tag][description]]
1540 The 'linkkey' must be a word word, starting with a letter, followed
1541 by letters, numbers, '-' or '_'.
1543 If REPLACE is a string, the tag will simply be appended to create the link.
1544 If the string contains \"%s\", the tag will be inserted there. If the string
1545 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1546 at that point (see the function `url-hexify-string'). If the string contains
1547 the specifier \"%(my-function)\", then the custom function `my-function' will
1548 be invoked: this function takes the tag as its only argument and must return
1549 a string.
1551 REPLACE may also be a function that will be called with the tag as the
1552 only argument to create the link, which should be returned as a string.
1554 See the manual for examples."
1555 :group 'org-link
1556 :type '(repeat
1557 (cons
1558 (string :tag "Protocol")
1559 (choice
1560 (string :tag "Format")
1561 (function)))))
1563 (defcustom org-descriptive-links t
1564 "Non-nil means Org will display descriptive links.
1565 E.g. [[http://orgmode.org][Org website]] will be displayed as
1566 \"Org Website\", hiding the link itself and just displaying its
1567 description. When set to `nil', Org will display the full links
1568 literally.
1570 You can interactively set the value of this variable by calling
1571 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1572 :group 'org-link
1573 :type 'boolean)
1575 (defcustom org-link-file-path-type 'adaptive
1576 "How the path name in file links should be stored.
1577 Valid values are:
1579 relative Relative to the current directory, i.e. the directory of the file
1580 into which the link is being inserted.
1581 absolute Absolute path, if possible with ~ for home directory.
1582 noabbrev Absolute path, no abbreviation of home directory.
1583 adaptive Use relative path for files in the current directory and sub-
1584 directories of it. For other files, use an absolute path."
1585 :group 'org-link
1586 :type '(choice
1587 (const relative)
1588 (const absolute)
1589 (const noabbrev)
1590 (const adaptive)))
1592 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1593 "Types of links that should be activated in Org-mode files.
1594 This is a list of symbols, each leading to the activation of a certain link
1595 type. In principle, it does not hurt to turn on most link types - there may
1596 be a small gain when turning off unused link types. The types are:
1598 bracket The recommended [[link][description]] or [[link]] links with hiding.
1599 angle Links in angular brackets that may contain whitespace like
1600 <bbdb:Carsten Dominik>.
1601 plain Plain links in normal text, no whitespace, like http://google.com.
1602 radio Text that is matched by a radio target, see manual for details.
1603 tag Tag settings in a headline (link to tag search).
1604 date Time stamps (link to calendar).
1605 footnote Footnote labels.
1607 Changing this variable requires a restart of Emacs to become effective."
1608 :group 'org-link
1609 :type '(set :greedy t
1610 (const :tag "Double bracket links" bracket)
1611 (const :tag "Angular bracket links" angle)
1612 (const :tag "Plain text links" plain)
1613 (const :tag "Radio target matches" radio)
1614 (const :tag "Tags" tag)
1615 (const :tag "Timestamps" date)
1616 (const :tag "Footnotes" footnote)))
1618 (defcustom org-make-link-description-function nil
1619 "Function to use for generating link descriptions from links.
1620 When nil, the link location will be used. This function must take
1621 two parameters: the first one is the link, the second one is the
1622 description generated by `org-insert-link'. The function should
1623 return the description to use."
1624 :group 'org-link
1625 :type '(choice (const nil) (function)))
1627 (defgroup org-link-store nil
1628 "Options concerning storing links in Org-mode."
1629 :tag "Org Store Link"
1630 :group 'org-link)
1632 (defcustom org-url-hexify-p t
1633 "When non-nil, hexify URL when creating a link."
1634 :type 'boolean
1635 :version "24.3"
1636 :group 'org-link-store)
1638 (defcustom org-email-link-description-format "Email %c: %.30s"
1639 "Format of the description part of a link to an email or usenet message.
1640 The following %-escapes will be replaced by corresponding information:
1642 %F full \"From\" field
1643 %f name, taken from \"From\" field, address if no name
1644 %T full \"To\" field
1645 %t first name in \"To\" field, address if no name
1646 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1647 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1648 %s subject
1649 %d date
1650 %m message-id.
1652 You may use normal field width specification between the % and the letter.
1653 This is for example useful to limit the length of the subject.
1655 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1656 :group 'org-link-store
1657 :type 'string)
1659 (defcustom org-from-is-user-regexp
1660 (let (r1 r2)
1661 (when (and user-mail-address (not (string= user-mail-address "")))
1662 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1663 (when (and user-full-name (not (string= user-full-name "")))
1664 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1665 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1666 "Regexp matched against the \"From:\" header of an email or usenet message.
1667 It should match if the message is from the user him/herself."
1668 :group 'org-link-store
1669 :type 'regexp)
1671 (defcustom org-context-in-file-links t
1672 "Non-nil means file links from `org-store-link' contain context.
1673 A search string will be added to the file name with :: as separator and
1674 used to find the context when the link is activated by the command
1675 `org-open-at-point'. When this option is t, the entire active region
1676 will be placed in the search string of the file link. If set to a
1677 positive integer, only the first n lines of context will be stored.
1679 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1680 negates this setting for the duration of the command."
1681 :group 'org-link-store
1682 :type '(choice boolean integer))
1684 (defcustom org-keep-stored-link-after-insertion nil
1685 "Non-nil means keep link in list for entire session.
1687 The command `org-store-link' adds a link pointing to the current
1688 location to an internal list. These links accumulate during a session.
1689 The command `org-insert-link' can be used to insert links into any
1690 Org-mode file (offering completion for all stored links). When this
1691 option is nil, every link which has been inserted once using \\[org-insert-link]
1692 will be removed from the list, to make completing the unused links
1693 more efficient."
1694 :group 'org-link-store
1695 :type 'boolean)
1697 (defgroup org-link-follow nil
1698 "Options concerning following links in Org-mode."
1699 :tag "Org Follow Link"
1700 :group 'org-link)
1702 (defcustom org-link-translation-function nil
1703 "Function to translate links with different syntax to Org syntax.
1704 This can be used to translate links created for example by the Planner
1705 or emacs-wiki packages to Org syntax.
1706 The function must accept two parameters, a TYPE containing the link
1707 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1708 which is everything after the link protocol. It should return a cons
1709 with possibly modified values of type and path.
1710 Org contains a function for this, so if you set this variable to
1711 `org-translate-link-from-planner', you should be able follow many
1712 links created by planner."
1713 :group 'org-link-follow
1714 :type '(choice (const nil) (function)))
1716 (defcustom org-follow-link-hook nil
1717 "Hook that is run after a link has been followed."
1718 :group 'org-link-follow
1719 :type 'hook)
1721 (defcustom org-tab-follows-link nil
1722 "Non-nil means on links TAB will follow the link.
1723 Needs to be set before org.el is loaded.
1724 This really should not be used, it does not make sense, and the
1725 implementation is bad."
1726 :group 'org-link-follow
1727 :type 'boolean)
1729 (defcustom org-return-follows-link nil
1730 "Non-nil means on links RET will follow the link.
1731 In tables, the special behavior of RET has precedence."
1732 :group 'org-link-follow
1733 :type 'boolean)
1735 (defcustom org-mouse-1-follows-link
1736 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1737 "Non-nil means mouse-1 on a link will follow the link.
1738 A longer mouse click will still set point. Does not work on XEmacs.
1739 Needs to be set before org.el is loaded."
1740 :group 'org-link-follow
1741 :version "24.4"
1742 :package-version '(Org . "8.3")
1743 :type '(choice
1744 (const :tag "A double click follows the link" 'double)
1745 (const :tag "Unconditionally follow the link with mouse-1" t)
1746 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
1748 (defcustom org-mark-ring-length 4
1749 "Number of different positions to be recorded in the ring.
1750 Changing this requires a restart of Emacs to work correctly."
1751 :group 'org-link-follow
1752 :type 'integer)
1754 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1755 "Non-nil means internal links in Org files must exactly match a headline.
1756 When nil, the link search tries to match a phrase with all words
1757 in the search text."
1758 :group 'org-link-follow
1759 :version "24.1"
1760 :type '(choice
1761 (const :tag "Use fuzzy text search" nil)
1762 (const :tag "Match only exact headline" t)
1763 (const :tag "Match exact headline or query to create it"
1764 query-to-create)))
1766 (defcustom org-link-frame-setup
1767 '((vm . vm-visit-folder-other-frame)
1768 (vm-imap . vm-visit-imap-folder-other-frame)
1769 (gnus . org-gnus-no-new-news)
1770 (file . find-file-other-window)
1771 (wl . wl-other-frame))
1772 "Setup the frame configuration for following links.
1773 When following a link with Emacs, it may often be useful to display
1774 this link in another window or frame. This variable can be used to
1775 set this up for the different types of links.
1776 For VM, use any of
1777 `vm-visit-folder'
1778 `vm-visit-folder-other-window'
1779 `vm-visit-folder-other-frame'
1780 For Gnus, use any of
1781 `gnus'
1782 `gnus-other-frame'
1783 `org-gnus-no-new-news'
1784 For FILE, use any of
1785 `find-file'
1786 `find-file-other-window'
1787 `find-file-other-frame'
1788 For Wanderlust use any of
1789 `wl'
1790 `wl-other-frame'
1791 For the calendar, use the variable `calendar-setup'.
1792 For BBDB, it is currently only possible to display the matches in
1793 another window."
1794 :group 'org-link-follow
1795 :type '(list
1796 (cons (const vm)
1797 (choice
1798 (const vm-visit-folder)
1799 (const vm-visit-folder-other-window)
1800 (const vm-visit-folder-other-frame)))
1801 (cons (const vm-imap)
1802 (choice
1803 (const vm-visit-imap-folder)
1804 (const vm-visit-imap-folder-other-window)
1805 (const vm-visit-imap-folder-other-frame)))
1806 (cons (const gnus)
1807 (choice
1808 (const gnus)
1809 (const gnus-other-frame)
1810 (const org-gnus-no-new-news)))
1811 (cons (const file)
1812 (choice
1813 (const find-file)
1814 (const find-file-other-window)
1815 (const find-file-other-frame)))
1816 (cons (const wl)
1817 (choice
1818 (const wl)
1819 (const wl-other-frame)))))
1821 (defcustom org-display-internal-link-with-indirect-buffer nil
1822 "Non-nil means use indirect buffer to display infile links.
1823 Activating internal links (from one location in a file to another location
1824 in the same file) normally just jumps to the location. When the link is
1825 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1826 is displayed in
1827 another window. When this option is set, the other window actually displays
1828 an indirect buffer clone of the current buffer, to avoid any visibility
1829 changes to the current buffer."
1830 :group 'org-link-follow
1831 :type 'boolean)
1833 (defcustom org-open-non-existing-files nil
1834 "Non-nil means `org-open-file' will open non-existing files.
1835 When nil, an error will be generated.
1836 This variable applies only to external applications because they
1837 might choke on non-existing files. If the link is to a file that
1838 will be opened in Emacs, the variable is ignored."
1839 :group 'org-link-follow
1840 :type 'boolean)
1842 (defcustom org-open-directory-means-index-dot-org nil
1843 "Non-nil means a link to a directory really means to index.org.
1844 When nil, following a directory link will run dired or open a finder/explorer
1845 window on that directory."
1846 :group 'org-link-follow
1847 :type 'boolean)
1849 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1850 "Function and arguments to call for following mailto links.
1851 This is a list with the first element being a Lisp function, and the
1852 remaining elements being arguments to the function. In string arguments,
1853 %a will be replaced by the address, and %s will be replaced by the subject
1854 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1855 :group 'org-link-follow
1856 :type '(choice
1857 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1858 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1859 (const :tag "message-mail" (message-mail "%a" "%s"))
1860 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1862 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1863 "Non-nil means ask for confirmation before executing shell links.
1864 Shell links can be dangerous: just think about a link
1866 [[shell:rm -rf ~/*][Google Search]]
1868 This link would show up in your Org-mode document as \"Google Search\",
1869 but really it would remove your entire home directory.
1870 Therefore we advise against setting this variable to nil.
1871 Just change it to `y-or-n-p' if you want to confirm with a
1872 single keystroke rather than having to type \"yes\"."
1873 :group 'org-link-follow
1874 :type '(choice
1875 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1876 (const :tag "with y-or-n (faster)" y-or-n-p)
1877 (const :tag "no confirmation (dangerous)" nil)))
1878 (put 'org-confirm-shell-link-function
1879 'safe-local-variable
1880 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1882 (defcustom org-confirm-shell-link-not-regexp ""
1883 "A regexp to skip confirmation for shell links."
1884 :group 'org-link-follow
1885 :version "24.1"
1886 :type 'regexp)
1888 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1889 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1890 Elisp links can be dangerous: just think about a link
1892 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1894 This link would show up in your Org-mode document as \"Google Search\",
1895 but really it would remove your entire home directory.
1896 Therefore we advise against setting this variable to nil.
1897 Just change it to `y-or-n-p' if you want to confirm with a
1898 single keystroke rather than having to type \"yes\"."
1899 :group 'org-link-follow
1900 :type '(choice
1901 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1902 (const :tag "with y-or-n (faster)" y-or-n-p)
1903 (const :tag "no confirmation (dangerous)" nil)))
1904 (put 'org-confirm-shell-link-function
1905 'safe-local-variable
1906 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1908 (defcustom org-confirm-elisp-link-not-regexp ""
1909 "A regexp to skip confirmation for Elisp links."
1910 :group 'org-link-follow
1911 :version "24.1"
1912 :type 'regexp)
1914 (defconst org-file-apps-defaults-gnu
1915 '((remote . emacs)
1916 (system . mailcap)
1917 (t . mailcap))
1918 "Default file applications on a UNIX or GNU/Linux system.
1919 See `org-file-apps'.")
1921 (defconst org-file-apps-defaults-macosx
1922 '((remote . emacs)
1923 (t . "open %s")
1924 (system . "open %s")
1925 ("ps.gz" . "gv %s")
1926 ("eps.gz" . "gv %s")
1927 ("dvi" . "xdvi %s")
1928 ("fig" . "xfig %s"))
1929 "Default file applications on a MacOS X system.
1930 The system \"open\" is known as a default, but we use X11 applications
1931 for some files for which the OS does not have a good default.
1932 See `org-file-apps'.")
1934 (defconst org-file-apps-defaults-windowsnt
1935 (list
1936 '(remote . emacs)
1937 (cons t
1938 (list (if (featurep 'xemacs)
1939 'mswindows-shell-execute
1940 'w32-shell-execute)
1941 "open" 'file))
1942 (cons 'system
1943 (list (if (featurep 'xemacs)
1944 'mswindows-shell-execute
1945 'w32-shell-execute)
1946 "open" 'file)))
1947 "Default file applications on a Windows NT system.
1948 The system \"open\" is used for most files.
1949 See `org-file-apps'.")
1951 (defcustom org-file-apps
1952 '((auto-mode . emacs)
1953 ("\\.mm\\'" . default)
1954 ("\\.x?html?\\'" . default)
1955 ("\\.pdf\\'" . default))
1956 "External applications for opening `file:path' items in a document.
1957 Org-mode uses system defaults for different file types, but
1958 you can use this variable to set the application for a given file
1959 extension. The entries in this list are cons cells where the car identifies
1960 files and the cdr the corresponding command. Possible values for the
1961 file identifier are
1962 \"string\" A string as a file identifier can be interpreted in different
1963 ways, depending on its contents:
1965 - Alphanumeric characters only:
1966 Match links with this file extension.
1967 Example: (\"pdf\" . \"evince %s\")
1968 to open PDFs with evince.
1970 - Regular expression: Match links where the
1971 filename matches the regexp. If you want to
1972 use groups here, use shy groups.
1974 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1975 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1976 to open *.html and *.xhtml with firefox.
1978 - Regular expression which contains (non-shy) groups:
1979 Match links where the whole link, including \"::\", and
1980 anything after that, matches the regexp.
1981 In a custom command string, %1, %2, etc. are replaced with
1982 the parts of the link that were matched by the groups.
1983 For backwards compatibility, if a command string is given
1984 that does not use any of the group matches, this case is
1985 handled identically to the second one (i.e. match against
1986 file name only).
1987 In a custom lisp form, you can access the group matches with
1988 (match-string n link).
1990 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1991 to open [[file:document.pdf::5]] with evince at page 5.
1993 `directory' Matches a directory
1994 `remote' Matches a remote file, accessible through tramp or efs.
1995 Remote files most likely should be visited through Emacs
1996 because external applications cannot handle such paths.
1997 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1998 so all files Emacs knows how to handle. Using this with
1999 command `emacs' will open most files in Emacs. Beware that this
2000 will also open html files inside Emacs, unless you add
2001 (\"html\" . default) to the list as well.
2002 t Default for files not matched by any of the other options.
2003 `system' The system command to open files, like `open' on Windows
2004 and Mac OS X, and mailcap under GNU/Linux. This is the command
2005 that will be selected if you call `C-c C-o' with a double
2006 \\[universal-argument] \\[universal-argument] prefix.
2008 Possible values for the command are:
2009 `emacs' The file will be visited by the current Emacs process.
2010 `default' Use the default application for this file type, which is the
2011 association for t in the list, most likely in the system-specific
2012 part.
2013 This can be used to overrule an unwanted setting in the
2014 system-specific variable.
2015 `system' Use the system command for opening files, like \"open\".
2016 This command is specified by the entry whose car is `system'.
2017 Most likely, the system-specific version of this variable
2018 does define this command, but you can overrule/replace it
2019 here.
2020 string A command to be executed by a shell; %s will be replaced
2021 by the path to the file.
2022 sexp A Lisp form which will be evaluated. The file path will
2023 be available in the Lisp variable `file'.
2024 For more examples, see the system specific constants
2025 `org-file-apps-defaults-macosx'
2026 `org-file-apps-defaults-windowsnt'
2027 `org-file-apps-defaults-gnu'."
2028 :group 'org-link-follow
2029 :type '(repeat
2030 (cons (choice :value ""
2031 (string :tag "Extension")
2032 (const :tag "System command to open files" system)
2033 (const :tag "Default for unrecognized files" t)
2034 (const :tag "Remote file" remote)
2035 (const :tag "Links to a directory" directory)
2036 (const :tag "Any files that have Emacs modes"
2037 auto-mode))
2038 (choice :value ""
2039 (const :tag "Visit with Emacs" emacs)
2040 (const :tag "Use default" default)
2041 (const :tag "Use the system command" system)
2042 (string :tag "Command")
2043 (sexp :tag "Lisp form")))))
2045 (defcustom org-doi-server-url "http://dx.doi.org/"
2046 "The URL of the DOI server."
2047 :type 'string
2048 :version "24.3"
2049 :group 'org-link-follow)
2051 (defgroup org-refile nil
2052 "Options concerning refiling entries in Org-mode."
2053 :tag "Org Refile"
2054 :group 'org)
2056 (defcustom org-directory "~/org"
2057 "Directory with org files.
2058 This is just a default location to look for Org files. There is no need
2059 at all to put your files into this directory. It is only used in the
2060 following situations:
2062 1. When a capture template specifies a target file that is not an
2063 absolute path. The path will then be interpreted relative to
2064 `org-directory'
2065 2. When a capture note is filed away in an interactive way (when exiting the
2066 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2067 with `org-directory' as the default path."
2068 :group 'org-refile
2069 :group 'org-capture
2070 :type 'directory)
2072 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2073 "Default target for storing notes.
2074 Used as a fall back file for org-capture.el, for templates that
2075 do not specify a target file."
2076 :group 'org-refile
2077 :group 'org-capture
2078 :type '(choice
2079 (const :tag "Default from remember-data-file" nil)
2080 file))
2082 (defcustom org-goto-interface 'outline
2083 "The default interface to be used for `org-goto'.
2084 Allowed values are:
2085 outline The interface shows an outline of the relevant file
2086 and the correct heading is found by moving through
2087 the outline or by searching with incremental search.
2088 outline-path-completion Headlines in the current buffer are offered via
2089 completion. This is the interface also used by
2090 the refile command."
2091 :group 'org-refile
2092 :type '(choice
2093 (const :tag "Outline" outline)
2094 (const :tag "Outline-path-completion" outline-path-completion)))
2096 (defcustom org-goto-max-level 5
2097 "Maximum target level when running `org-goto' with refile interface."
2098 :group 'org-refile
2099 :type 'integer)
2101 (defcustom org-reverse-note-order nil
2102 "Non-nil means store new notes at the beginning of a file or entry.
2103 When nil, new notes will be filed to the end of a file or entry.
2104 This can also be a list with cons cells of regular expressions that
2105 are matched against file names, and values."
2106 :group 'org-capture
2107 :group 'org-refile
2108 :type '(choice
2109 (const :tag "Reverse always" t)
2110 (const :tag "Reverse never" nil)
2111 (repeat :tag "By file name regexp"
2112 (cons regexp boolean))))
2114 (defcustom org-log-refile nil
2115 "Information to record when a task is refiled.
2117 Possible values are:
2119 nil Don't add anything
2120 time Add a time stamp to the task
2121 note Prompt for a note and add it with template `org-log-note-headings'
2123 This option can also be set with on a per-file-basis with
2125 #+STARTUP: nologrefile
2126 #+STARTUP: logrefile
2127 #+STARTUP: lognoterefile
2129 You can have local logging settings for a subtree by setting the LOGGING
2130 property to one or more of these keywords.
2132 When bulk-refiling from the agenda, the value `note' is forbidden and
2133 will temporarily be changed to `time'."
2134 :group 'org-refile
2135 :group 'org-progress
2136 :version "24.1"
2137 :type '(choice
2138 (const :tag "No logging" nil)
2139 (const :tag "Record timestamp" time)
2140 (const :tag "Record timestamp with note." note)))
2142 (defcustom org-refile-targets nil
2143 "Targets for refiling entries with \\[org-refile].
2144 This is a list of cons cells. Each cell contains:
2145 - a specification of the files to be considered, either a list of files,
2146 or a symbol whose function or variable value will be used to retrieve
2147 a file name or a list of file names. If you use `org-agenda-files' for
2148 that, all agenda files will be scanned for targets. Nil means consider
2149 headings in the current buffer.
2150 - A specification of how to find candidate refile targets. This may be
2151 any of:
2152 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2153 This tag has to be present in all target headlines, inheritance will
2154 not be considered.
2155 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2156 todo keyword.
2157 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2158 headlines that are refiling targets.
2159 - a cons cell (:level . N). Any headline of level N is considered a target.
2160 Note that, when `org-odd-levels-only' is set, level corresponds to
2161 order in hierarchy, not to the number of stars.
2162 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2163 Note that, when `org-odd-levels-only' is set, level corresponds to
2164 order in hierarchy, not to the number of stars.
2166 Each element of this list generates a set of possible targets.
2167 The union of these sets is presented (with completion) to
2168 the user by `org-refile'.
2170 You can set the variable `org-refile-target-verify-function' to a function
2171 to verify each headline found by the simple criteria above.
2173 When this variable is nil, all top-level headlines in the current buffer
2174 are used, equivalent to the value `((nil . (:level . 1))'."
2175 :group 'org-refile
2176 :type '(repeat
2177 (cons
2178 (choice :value org-agenda-files
2179 (const :tag "All agenda files" org-agenda-files)
2180 (const :tag "Current buffer" nil)
2181 (function) (variable) (file))
2182 (choice :tag "Identify target headline by"
2183 (cons :tag "Specific tag" (const :value :tag) (string))
2184 (cons :tag "TODO keyword" (const :value :todo) (string))
2185 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2186 (cons :tag "Level number" (const :value :level) (integer))
2187 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2189 (defcustom org-refile-target-verify-function nil
2190 "Function to verify if the headline at point should be a refile target.
2191 The function will be called without arguments, with point at the
2192 beginning of the headline. It should return t and leave point
2193 where it is if the headline is a valid target for refiling.
2195 If the target should not be selected, the function must return nil.
2196 In addition to this, it may move point to a place from where the search
2197 should be continued. For example, the function may decide that the entire
2198 subtree of the current entry should be excluded and move point to the end
2199 of the subtree."
2200 :group 'org-refile
2201 :type '(choice
2202 (const nil)
2203 (function)))
2205 (defcustom org-refile-use-cache nil
2206 "Non-nil means cache refile targets to speed up the process.
2207 The cache for a particular file will be updated automatically when
2208 the buffer has been killed, or when any of the marker used for flagging
2209 refile targets no longer points at a live buffer.
2210 If you have added new entries to a buffer that might themselves be targets,
2211 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2212 find that easier, `C-u C-u C-u C-c C-w'."
2213 :group 'org-refile
2214 :version "24.1"
2215 :type 'boolean)
2217 (defcustom org-refile-use-outline-path nil
2218 "Non-nil means provide refile targets as paths.
2219 So a level 3 headline will be available as level1/level2/level3.
2221 When the value is `file', also include the file name (without directory)
2222 into the path. In this case, you can also stop the completion after
2223 the file name, to get entries inserted as top level in the file.
2225 When `full-file-path', include the full file path."
2226 :group 'org-refile
2227 :type '(choice
2228 (const :tag "Not" nil)
2229 (const :tag "Yes" t)
2230 (const :tag "Start with file name" file)
2231 (const :tag "Start with full file path" full-file-path)))
2233 (defcustom org-outline-path-complete-in-steps t
2234 "Non-nil means complete the outline path in hierarchical steps.
2235 When Org-mode uses the refile interface to select an outline path
2236 \(see variable `org-refile-use-outline-path'), the completion of
2237 the path can be done is a single go, or if can be done in steps down
2238 the headline hierarchy. Going in steps is probably the best if you
2239 do not use a special completion package like `ido' or `icicles'.
2240 However, when using these packages, going in one step can be very
2241 fast, while still showing the whole path to the entry."
2242 :group 'org-refile
2243 :type 'boolean)
2245 (defcustom org-refile-allow-creating-parent-nodes nil
2246 "Non-nil means allow to create new nodes as refile targets.
2247 New nodes are then created by adding \"/new node name\" to the completion
2248 of an existing node. When the value of this variable is `confirm',
2249 new node creation must be confirmed by the user (recommended)
2250 When nil, the completion must match an existing entry.
2252 Note that, if the new heading is not seen by the criteria
2253 listed in `org-refile-targets', multiple instances of the same
2254 heading would be created by trying again to file under the new
2255 heading."
2256 :group 'org-refile
2257 :type '(choice
2258 (const :tag "Never" nil)
2259 (const :tag "Always" t)
2260 (const :tag "Prompt for confirmation" confirm)))
2262 (defcustom org-refile-active-region-within-subtree nil
2263 "Non-nil means also refile active region within a subtree.
2265 By default `org-refile' doesn't allow refiling regions if they
2266 don't contain a set of subtrees, but it might be convenient to
2267 do so sometimes: in that case, the first line of the region is
2268 converted to a headline before refiling."
2269 :group 'org-refile
2270 :version "24.1"
2271 :type 'boolean)
2273 (defgroup org-todo nil
2274 "Options concerning TODO items in Org-mode."
2275 :tag "Org TODO"
2276 :group 'org)
2278 (defgroup org-progress nil
2279 "Options concerning Progress logging in Org-mode."
2280 :tag "Org Progress"
2281 :group 'org-time)
2283 (defvar org-todo-interpretation-widgets
2284 '((:tag "Sequence (cycling hits every state)" sequence)
2285 (:tag "Type (cycling directly to DONE)" type))
2286 "The available interpretation symbols for customizing `org-todo-keywords'.
2287 Interested libraries should add to this list.")
2289 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2290 "List of TODO entry keyword sequences and their interpretation.
2291 \\<org-mode-map>This is a list of sequences.
2293 Each sequence starts with a symbol, either `sequence' or `type',
2294 indicating if the keywords should be interpreted as a sequence of
2295 action steps, or as different types of TODO items. The first
2296 keywords are states requiring action - these states will select a headline
2297 for inclusion into the global TODO list Org-mode produces. If one of
2298 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2299 signify that no further action is necessary. If \"|\" is not found,
2300 the last keyword is treated as the only DONE state of the sequence.
2302 The command \\[org-todo] cycles an entry through these states, and one
2303 additional state where no keyword is present. For details about this
2304 cycling, see the manual.
2306 TODO keywords and interpretation can also be set on a per-file basis with
2307 the special #+SEQ_TODO and #+TYP_TODO lines.
2309 Each keyword can optionally specify a character for fast state selection
2310 \(in combination with the variable `org-use-fast-todo-selection')
2311 and specifiers for state change logging, using the same syntax that
2312 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2313 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2314 indicates to record a time stamp each time this state is selected.
2316 Each keyword may also specify if a timestamp or a note should be
2317 recorded when entering or leaving the state, by adding additional
2318 characters in the parenthesis after the keyword. This looks like this:
2319 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2320 record only the time of the state change. With X and Y being either
2321 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2322 Y when leaving the state if and only if the *target* state does not
2323 define X. You may omit any of the fast-selection key or X or /Y,
2324 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2326 For backward compatibility, this variable may also be just a list
2327 of keywords. In this case the interpretation (sequence or type) will be
2328 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2329 :group 'org-todo
2330 :group 'org-keywords
2331 :type '(choice
2332 (repeat :tag "Old syntax, just keywords"
2333 (string :tag "Keyword"))
2334 (repeat :tag "New syntax"
2335 (cons
2336 (choice
2337 :tag "Interpretation"
2338 ;;Quick and dirty way to see
2339 ;;`org-todo-interpretations'. This takes the
2340 ;;place of item arguments
2341 :convert-widget
2342 (lambda (widget)
2343 (widget-put widget
2344 :args (mapcar
2345 #'(lambda (x)
2346 (widget-convert
2347 (cons 'const x)))
2348 org-todo-interpretation-widgets))
2349 widget))
2350 (repeat
2351 (string :tag "Keyword"))))))
2353 (defvar org-todo-keywords-1 nil
2354 "All TODO and DONE keywords active in a buffer.")
2355 (make-variable-buffer-local 'org-todo-keywords-1)
2356 (defvar org-todo-keywords-for-agenda nil)
2357 (defvar org-done-keywords-for-agenda nil)
2358 (defvar org-drawers-for-agenda nil)
2359 (defvar org-todo-keyword-alist-for-agenda nil)
2360 (defvar org-tag-alist-for-agenda nil
2361 "Alist of all tags from all agenda files.")
2362 (defvar org-tag-groups-alist-for-agenda nil
2363 "Alist of all groups tags from all current agenda files.")
2364 (defvar org-tag-groups-alist nil)
2365 (make-variable-buffer-local 'org-tag-groups-alist)
2366 (defvar org-agenda-contributing-files nil)
2367 (defvar org-not-done-keywords nil)
2368 (make-variable-buffer-local 'org-not-done-keywords)
2369 (defvar org-done-keywords nil)
2370 (make-variable-buffer-local 'org-done-keywords)
2371 (defvar org-todo-heads nil)
2372 (make-variable-buffer-local 'org-todo-heads)
2373 (defvar org-todo-sets nil)
2374 (make-variable-buffer-local 'org-todo-sets)
2375 (defvar org-todo-log-states nil)
2376 (make-variable-buffer-local 'org-todo-log-states)
2377 (defvar org-todo-kwd-alist nil)
2378 (make-variable-buffer-local 'org-todo-kwd-alist)
2379 (defvar org-todo-key-alist nil)
2380 (make-variable-buffer-local 'org-todo-key-alist)
2381 (defvar org-todo-key-trigger nil)
2382 (make-variable-buffer-local 'org-todo-key-trigger)
2384 (defcustom org-todo-interpretation 'sequence
2385 "Controls how TODO keywords are interpreted.
2386 This variable is in principle obsolete and is only used for
2387 backward compatibility, if the interpretation of todo keywords is
2388 not given already in `org-todo-keywords'. See that variable for
2389 more information."
2390 :group 'org-todo
2391 :group 'org-keywords
2392 :type '(choice (const sequence)
2393 (const type)))
2395 (defcustom org-use-fast-todo-selection t
2396 "Non-nil means use the fast todo selection scheme with C-c C-t.
2397 This variable describes if and under what circumstances the cycling
2398 mechanism for TODO keywords will be replaced by a single-key, direct
2399 selection scheme.
2401 When nil, fast selection is never used.
2403 When the symbol `prefix', it will be used when `org-todo' is called
2404 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2405 `C-u t' in an agenda buffer.
2407 When t, fast selection is used by default. In this case, the prefix
2408 argument forces cycling instead.
2410 In all cases, the special interface is only used if access keys have
2411 actually been assigned by the user, i.e. if keywords in the configuration
2412 are followed by a letter in parenthesis, like TODO(t)."
2413 :group 'org-todo
2414 :type '(choice
2415 (const :tag "Never" nil)
2416 (const :tag "By default" t)
2417 (const :tag "Only with C-u C-c C-t" prefix)))
2419 (defcustom org-provide-todo-statistics t
2420 "Non-nil means update todo statistics after insert and toggle.
2421 ALL-HEADLINES means update todo statistics by including headlines
2422 with no TODO keyword as well, counting them as not done.
2423 A list of TODO keywords means the same, but skip keywords that are
2424 not in this list.
2426 When this is set, todo statistics is updated in the parent of the
2427 current entry each time a todo state is changed."
2428 :group 'org-todo
2429 :type '(choice
2430 (const :tag "Yes, only for TODO entries" t)
2431 (const :tag "Yes, including all entries" 'all-headlines)
2432 (repeat :tag "Yes, for TODOs in this list"
2433 (string :tag "TODO keyword"))
2434 (other :tag "No TODO statistics" nil)))
2436 (defcustom org-hierarchical-todo-statistics t
2437 "Non-nil means TODO statistics covers just direct children.
2438 When nil, all entries in the subtree are considered.
2439 This has only an effect if `org-provide-todo-statistics' is set.
2440 To set this to nil for only a single subtree, use a COOKIE_DATA
2441 property and include the word \"recursive\" into the value."
2442 :group 'org-todo
2443 :type 'boolean)
2445 (defcustom org-after-todo-state-change-hook nil
2446 "Hook which is run after the state of a TODO item was changed.
2447 The new state (a string with a TODO keyword, or nil) is available in the
2448 Lisp variable `org-state'."
2449 :group 'org-todo
2450 :type 'hook)
2452 (defvar org-blocker-hook nil
2453 "Hook for functions that are allowed to block a state change.
2455 Functions in this hook should not modify the buffer.
2456 Each function gets as its single argument a property list,
2457 see `org-trigger-hook' for more information about this list.
2459 If any of the functions in this hook returns nil, the state change
2460 is blocked.")
2462 (defvar org-trigger-hook nil
2463 "Hook for functions that are triggered by a state change.
2465 Each function gets as its single argument a property list with at
2466 least the following elements:
2468 (:type type-of-change :position pos-at-entry-start
2469 :from old-state :to new-state)
2471 Depending on the type, more properties may be present.
2473 This mechanism is currently implemented for:
2475 TODO state changes
2476 ------------------
2477 :type todo-state-change
2478 :from previous state (keyword as a string), or nil, or a symbol
2479 'todo' or 'done', to indicate the general type of state.
2480 :to new state, like in :from")
2482 (defcustom org-enforce-todo-dependencies nil
2483 "Non-nil means undone TODO entries will block switching the parent to DONE.
2484 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2485 be blocked if any prior sibling is not yet done.
2486 Finally, if the parent is blocked because of ordered siblings of its own,
2487 the child will also be blocked."
2488 :set (lambda (var val)
2489 (set var val)
2490 (if val
2491 (add-hook 'org-blocker-hook
2492 'org-block-todo-from-children-or-siblings-or-parent)
2493 (remove-hook 'org-blocker-hook
2494 'org-block-todo-from-children-or-siblings-or-parent)))
2495 :group 'org-todo
2496 :type 'boolean)
2498 (defcustom org-enforce-todo-checkbox-dependencies nil
2499 "Non-nil means unchecked boxes will block switching the parent to DONE.
2500 When this is nil, checkboxes have no influence on switching TODO states.
2501 When non-nil, you first need to check off all check boxes before the TODO
2502 entry can be switched to DONE.
2503 This variable needs to be set before org.el is loaded, and you need to
2504 restart Emacs after a change to make the change effective. The only way
2505 to change is while Emacs is running is through the customize interface."
2506 :set (lambda (var val)
2507 (set var val)
2508 (if val
2509 (add-hook 'org-blocker-hook
2510 'org-block-todo-from-checkboxes)
2511 (remove-hook 'org-blocker-hook
2512 'org-block-todo-from-checkboxes)))
2513 :group 'org-todo
2514 :type 'boolean)
2516 (defcustom org-treat-insert-todo-heading-as-state-change nil
2517 "Non-nil means inserting a TODO heading is treated as state change.
2518 So when the command \\[org-insert-todo-heading] is used, state change
2519 logging will apply if appropriate. When nil, the new TODO item will
2520 be inserted directly, and no logging will take place."
2521 :group 'org-todo
2522 :type 'boolean)
2524 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2525 "Non-nil means switching TODO states with S-cursor counts as state change.
2526 This is the default behavior. However, setting this to nil allows a
2527 convenient way to select a TODO state and bypass any logging associated
2528 with that."
2529 :group 'org-todo
2530 :type 'boolean)
2532 (defcustom org-todo-state-tags-triggers nil
2533 "Tag changes that should be triggered by TODO state changes.
2534 This is a list. Each entry is
2536 (state-change (tag . flag) .......)
2538 State-change can be a string with a state, and empty string to indicate the
2539 state that has no TODO keyword, or it can be one of the symbols `todo'
2540 or `done', meaning any not-done or done state, respectively."
2541 :group 'org-todo
2542 :group 'org-tags
2543 :type '(repeat
2544 (cons (choice :tag "When changing to"
2545 (const :tag "Not-done state" todo)
2546 (const :tag "Done state" done)
2547 (string :tag "State"))
2548 (repeat
2549 (cons :tag "Tag action"
2550 (string :tag "Tag")
2551 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2553 (defcustom org-log-done nil
2554 "Information to record when a task moves to the DONE state.
2556 Possible values are:
2558 nil Don't add anything, just change the keyword
2559 time Add a time stamp to the task
2560 note Prompt for a note and add it with template `org-log-note-headings'
2562 This option can also be set with on a per-file-basis with
2564 #+STARTUP: nologdone
2565 #+STARTUP: logdone
2566 #+STARTUP: lognotedone
2568 You can have local logging settings for a subtree by setting the LOGGING
2569 property to one or more of these keywords."
2570 :group 'org-todo
2571 :group 'org-progress
2572 :type '(choice
2573 (const :tag "No logging" nil)
2574 (const :tag "Record CLOSED timestamp" time)
2575 (const :tag "Record CLOSED timestamp with note." note)))
2577 ;; Normalize old uses of org-log-done.
2578 (cond
2579 ((eq org-log-done t) (setq org-log-done 'time))
2580 ((and (listp org-log-done) (memq 'done org-log-done))
2581 (setq org-log-done 'note)))
2583 (defcustom org-log-reschedule nil
2584 "Information to record when the scheduling date of a tasks is modified.
2586 Possible values are:
2588 nil Don't add anything, just change the date
2589 time Add a time stamp to the task
2590 note Prompt for a note and add it with template `org-log-note-headings'
2592 This option can also be set with on a per-file-basis with
2594 #+STARTUP: nologreschedule
2595 #+STARTUP: logreschedule
2596 #+STARTUP: lognotereschedule"
2597 :group 'org-todo
2598 :group 'org-progress
2599 :type '(choice
2600 (const :tag "No logging" nil)
2601 (const :tag "Record timestamp" time)
2602 (const :tag "Record timestamp with note." note)))
2604 (defcustom org-log-redeadline nil
2605 "Information to record when the deadline date of a tasks is modified.
2607 Possible values are:
2609 nil Don't add anything, just change the date
2610 time Add a time stamp to the task
2611 note Prompt for a note and add it with template `org-log-note-headings'
2613 This option can also be set with on a per-file-basis with
2615 #+STARTUP: nologredeadline
2616 #+STARTUP: logredeadline
2617 #+STARTUP: lognoteredeadline
2619 You can have local logging settings for a subtree by setting the LOGGING
2620 property to one or more of these keywords."
2621 :group 'org-todo
2622 :group 'org-progress
2623 :type '(choice
2624 (const :tag "No logging" nil)
2625 (const :tag "Record timestamp" time)
2626 (const :tag "Record timestamp with note." note)))
2628 (defcustom org-log-note-clock-out nil
2629 "Non-nil means record a note when clocking out of an item.
2630 This can also be configured on a per-file basis by adding one of
2631 the following lines anywhere in the buffer:
2633 #+STARTUP: lognoteclock-out
2634 #+STARTUP: nolognoteclock-out"
2635 :group 'org-todo
2636 :group 'org-progress
2637 :type 'boolean)
2639 (defcustom org-log-done-with-time t
2640 "Non-nil means the CLOSED time stamp will contain date and time.
2641 When nil, only the date will be recorded."
2642 :group 'org-progress
2643 :type 'boolean)
2645 (defcustom org-log-note-headings
2646 '((done . "CLOSING NOTE %t")
2647 (state . "State %-12s from %-12S %t")
2648 (note . "Note taken on %t")
2649 (reschedule . "Rescheduled from %S on %t")
2650 (delschedule . "Not scheduled, was %S on %t")
2651 (redeadline . "New deadline from %S on %t")
2652 (deldeadline . "Removed deadline, was %S on %t")
2653 (refile . "Refiled on %t")
2654 (clock-out . ""))
2655 "Headings for notes added to entries.
2656 The value is an alist, with the car being a symbol indicating the note
2657 context, and the cdr is the heading to be used. The heading may also be the
2658 empty string.
2659 %t in the heading will be replaced by a time stamp.
2660 %T will be an active time stamp instead the default inactive one
2661 %d will be replaced by a short-format time stamp.
2662 %D will be replaced by an active short-format time stamp.
2663 %s will be replaced by the new TODO state, in double quotes.
2664 %S will be replaced by the old TODO state, in double quotes.
2665 %u will be replaced by the user name.
2666 %U will be replaced by the full user name.
2668 In fact, it is not a good idea to change the `state' entry, because
2669 agenda log mode depends on the format of these entries."
2670 :group 'org-todo
2671 :group 'org-progress
2672 :type '(list :greedy t
2673 (cons (const :tag "Heading when closing an item" done) string)
2674 (cons (const :tag
2675 "Heading when changing todo state (todo sequence only)"
2676 state) string)
2677 (cons (const :tag "Heading when just taking a note" note) string)
2678 (cons (const :tag "Heading when rescheduling" reschedule) string)
2679 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2680 (cons (const :tag "Heading when changing deadline" redeadline) string)
2681 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2682 (cons (const :tag "Heading when refiling" refile) string)
2683 (cons (const :tag "Heading when clocking out" clock-out) string)))
2685 (unless (assq 'note org-log-note-headings)
2686 (push '(note . "%t") org-log-note-headings))
2688 (defcustom org-log-into-drawer nil
2689 "Non-nil means insert state change notes and time stamps into a drawer.
2690 When nil, state changes notes will be inserted after the headline and
2691 any scheduling and clock lines, but not inside a drawer.
2693 The value of this variable should be the name of the drawer to use.
2694 LOGBOOK is proposed as the default drawer for this purpose, you can
2695 also set this to a string to define the drawer of your choice.
2697 A value of t is also allowed, representing \"LOGBOOK\".
2699 A value of t or nil can also be set with on a per-file-basis with
2701 #+STARTUP: logdrawer
2702 #+STARTUP: nologdrawer
2704 If this variable is set, `org-log-state-notes-insert-after-drawers'
2705 will be ignored.
2707 You can set the property LOG_INTO_DRAWER to overrule this setting for
2708 a subtree."
2709 :group 'org-todo
2710 :group 'org-progress
2711 :type '(choice
2712 (const :tag "Not into a drawer" nil)
2713 (const :tag "LOGBOOK" t)
2714 (string :tag "Other")))
2716 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2718 (defun org-log-into-drawer ()
2719 "Return the value of `org-log-into-drawer', but let properties overrule.
2720 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2721 used instead of the default value."
2722 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2723 (cond
2724 ((not p) org-log-into-drawer)
2725 ((equal p "nil") nil)
2726 ((equal p "t") "LOGBOOK")
2727 (t p))))
2729 (defcustom org-log-state-notes-insert-after-drawers nil
2730 "Non-nil means insert state change notes after any drawers in entry.
2731 Only the drawers that *immediately* follow the headline and the
2732 deadline/scheduled line are skipped.
2733 When nil, insert notes right after the heading and perhaps the line
2734 with deadline/scheduling if present.
2736 This variable will have no effect if `org-log-into-drawer' is
2737 set."
2738 :group 'org-todo
2739 :group 'org-progress
2740 :type 'boolean)
2742 (defcustom org-log-states-order-reversed t
2743 "Non-nil means the latest state note will be directly after heading.
2744 When nil, the state change notes will be ordered according to time.
2746 This option can also be set with on a per-file-basis with
2748 #+STARTUP: logstatesreversed
2749 #+STARTUP: nologstatesreversed"
2750 :group 'org-todo
2751 :group 'org-progress
2752 :type 'boolean)
2754 (defcustom org-todo-repeat-to-state nil
2755 "The TODO state to which a repeater should return the repeating task.
2756 By default this is the first task in a TODO sequence, or the previous state
2757 in a TODO_TYP set. But you can specify another task here.
2758 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2759 :group 'org-todo
2760 :version "24.1"
2761 :type '(choice (const :tag "Head of sequence" nil)
2762 (string :tag "Specific state")))
2764 (defcustom org-log-repeat 'time
2765 "Non-nil means record moving through the DONE state when triggering repeat.
2766 An auto-repeating task is immediately switched back to TODO when
2767 marked DONE. If you are not logging state changes (by adding \"@\"
2768 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2769 record a closing note, there will be no record of the task moving
2770 through DONE. This variable forces taking a note anyway.
2772 nil Don't force a record
2773 time Record a time stamp
2774 note Prompt for a note and add it with template `org-log-note-headings'
2776 This option can also be set with on a per-file-basis with
2778 #+STARTUP: nologrepeat
2779 #+STARTUP: logrepeat
2780 #+STARTUP: lognoterepeat
2782 You can have local logging settings for a subtree by setting the LOGGING
2783 property to one or more of these keywords."
2784 :group 'org-todo
2785 :group 'org-progress
2786 :type '(choice
2787 (const :tag "Don't force a record" nil)
2788 (const :tag "Force recording the DONE state" time)
2789 (const :tag "Force recording a note with the DONE state" note)))
2792 (defgroup org-priorities nil
2793 "Priorities in Org-mode."
2794 :tag "Org Priorities"
2795 :group 'org-todo)
2797 (defcustom org-enable-priority-commands t
2798 "Non-nil means priority commands are active.
2799 When nil, these commands will be disabled, so that you never accidentally
2800 set a priority."
2801 :group 'org-priorities
2802 :type 'boolean)
2804 (defcustom org-highest-priority ?A
2805 "The highest priority of TODO items. A character like ?A, ?B etc.
2806 Must have a smaller ASCII number than `org-lowest-priority'."
2807 :group 'org-priorities
2808 :type 'character)
2810 (defcustom org-lowest-priority ?C
2811 "The lowest priority of TODO items. A character like ?A, ?B etc.
2812 Must have a larger ASCII number than `org-highest-priority'."
2813 :group 'org-priorities
2814 :type 'character)
2816 (defcustom org-default-priority ?B
2817 "The default priority of TODO items.
2818 This is the priority an item gets if no explicit priority is given.
2819 When starting to cycle on an empty priority the first step in the cycle
2820 depends on `org-priority-start-cycle-with-default'. The resulting first
2821 step priority must not exceed the range from `org-highest-priority' to
2822 `org-lowest-priority' which means that `org-default-priority' has to be
2823 in this range exclusive or inclusive the range boundaries. Else the
2824 first step refuses to set the default and the second will fall back
2825 to (depending on the command used) the highest or lowest priority."
2826 :group 'org-priorities
2827 :type 'character)
2829 (defcustom org-priority-start-cycle-with-default t
2830 "Non-nil means start with default priority when starting to cycle.
2831 When this is nil, the first step in the cycle will be (depending on the
2832 command used) one higher or lower than the default priority.
2833 See also `org-default-priority'."
2834 :group 'org-priorities
2835 :type 'boolean)
2837 (defcustom org-get-priority-function nil
2838 "Function to extract the priority from a string.
2839 The string is normally the headline. If this is nil Org computes the
2840 priority from the priority cookie like [#A] in the headline. It returns
2841 an integer, increasing by 1000 for each priority level.
2842 The user can set a different function here, which should take a string
2843 as an argument and return the numeric priority."
2844 :group 'org-priorities
2845 :version "24.1"
2846 :type '(choice
2847 (const nil)
2848 (function)))
2850 (defgroup org-time nil
2851 "Options concerning time stamps and deadlines in Org-mode."
2852 :tag "Org Time"
2853 :group 'org)
2855 (defcustom org-insert-labeled-timestamps-at-point nil
2856 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2857 When nil, these labeled time stamps are forces into the second line of an
2858 entry, just after the headline. When scheduling from the global TODO list,
2859 the time stamp will always be forced into the second line."
2860 :group 'org-time
2861 :type 'boolean)
2863 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2864 "Formats for `format-time-string' which are used for time stamps.
2865 It is not recommended to change this constant.")
2867 (defcustom org-time-stamp-rounding-minutes '(0 5)
2868 "Number of minutes to round time stamps to.
2869 These are two values, the first applies when first creating a time stamp.
2870 The second applies when changing it with the commands `S-up' and `S-down'.
2871 When changing the time stamp, this means that it will change in steps
2872 of N minutes, as given by the second value.
2874 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2875 numbers should be factors of 60, so for example 5, 10, 15.
2877 When this is larger than 1, you can still force an exact time stamp by using
2878 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2879 and by using a prefix arg to `S-up/down' to specify the exact number
2880 of minutes to shift."
2881 :group 'org-time
2882 :get #'(lambda (var) ; Make sure both elements are there
2883 (if (integerp (default-value var))
2884 (list (default-value var) 5)
2885 (default-value var)))
2886 :type '(list
2887 (integer :tag "when inserting times")
2888 (integer :tag "when modifying times")))
2890 ;; Normalize old customizations of this variable.
2891 (when (integerp org-time-stamp-rounding-minutes)
2892 (setq org-time-stamp-rounding-minutes
2893 (list org-time-stamp-rounding-minutes
2894 org-time-stamp-rounding-minutes)))
2896 (defcustom org-display-custom-times nil
2897 "Non-nil means overlay custom formats over all time stamps.
2898 The formats are defined through the variable `org-time-stamp-custom-formats'.
2899 To turn this on on a per-file basis, insert anywhere in the file:
2900 #+STARTUP: customtime"
2901 :group 'org-time
2902 :set 'set-default
2903 :type 'sexp)
2904 (make-variable-buffer-local 'org-display-custom-times)
2906 (defcustom org-time-stamp-custom-formats
2907 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2908 "Custom formats for time stamps. See `format-time-string' for the syntax.
2909 These are overlaid over the default ISO format if the variable
2910 `org-display-custom-times' is set. Time like %H:%M should be at the
2911 end of the second format. The custom formats are also honored by export
2912 commands, if custom time display is turned on at the time of export."
2913 :group 'org-time
2914 :type 'sexp)
2916 (defun org-time-stamp-format (&optional long inactive)
2917 "Get the right format for a time string."
2918 (let ((f (if long (cdr org-time-stamp-formats)
2919 (car org-time-stamp-formats))))
2920 (if inactive
2921 (concat "[" (substring f 1 -1) "]")
2922 f)))
2924 (defcustom org-time-clocksum-format
2925 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2926 "The format string used when creating CLOCKSUM lines.
2927 This is also used when Org mode generates a time duration.
2929 The value can be a single format string containing two
2930 %-sequences, which will be filled with the number of hours and
2931 minutes in that order.
2933 Alternatively, the value can be a plist associating any of the
2934 keys :years, :months, :weeks, :days, :hours or :minutes with
2935 format strings. The time duration is formatted using only the
2936 time components that are needed and concatenating the results.
2937 If a time unit in absent, it falls back to the next smallest
2938 unit.
2940 The keys :require-years, :require-months, :require-days,
2941 :require-weeks, :require-hours, :require-minutes are also
2942 meaningful. A non-nil value for these keys indicates that the
2943 corresponding time component should always be included, even if
2944 its value is 0.
2947 For example,
2949 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2950 :require-minutes t)
2952 means durations longer than a day will be expressed in days,
2953 hours and minutes, and durations less than a day will always be
2954 expressed in hours and minutes (even for durations less than an
2955 hour).
2957 The value
2959 \(:days \"%dd\" :minutes \"%dm\")
2961 means durations longer than a day will be expressed in days and
2962 minutes, and durations less than a day will be expressed entirely
2963 in minutes (even for durations longer than an hour)."
2964 :group 'org-time
2965 :group 'org-clock
2966 :version "24.4"
2967 :package-version '(Org . "8.0")
2968 :type '(choice (string :tag "Format string")
2969 (set :tag "Plist"
2970 (group :inline t (const :tag "Years" :years)
2971 (string :tag "Format string"))
2972 (group :inline t
2973 (const :tag "Always show years" :require-years)
2974 (const t))
2975 (group :inline t (const :tag "Months" :months)
2976 (string :tag "Format string"))
2977 (group :inline t
2978 (const :tag "Always show months" :require-months)
2979 (const t))
2980 (group :inline t (const :tag "Weeks" :weeks)
2981 (string :tag "Format string"))
2982 (group :inline t
2983 (const :tag "Always show weeks" :require-weeks)
2984 (const t))
2985 (group :inline t (const :tag "Days" :days)
2986 (string :tag "Format string"))
2987 (group :inline t
2988 (const :tag "Always show days" :require-days)
2989 (const t))
2990 (group :inline t (const :tag "Hours" :hours)
2991 (string :tag "Format string"))
2992 (group :inline t
2993 (const :tag "Always show hours" :require-hours)
2994 (const t))
2995 (group :inline t (const :tag "Minutes" :minutes)
2996 (string :tag "Format string"))
2997 (group :inline t
2998 (const :tag "Always show minutes" :require-minutes)
2999 (const t)))))
3001 (defcustom org-time-clocksum-use-fractional nil
3002 "When non-nil, \\[org-clock-display] uses fractional times.
3003 See `org-time-clocksum-format' for more on time clock formats."
3004 :group 'org-time
3005 :group 'org-clock
3006 :version "24.3"
3007 :type 'boolean)
3009 (defcustom org-time-clocksum-use-effort-durations nil
3010 "When non-nil, \\[org-clock-display] uses effort durations.
3011 E.g. by default, one day is considered to be a 8 hours effort,
3012 so a task that has been clocked for 16 hours will be displayed
3013 as during 2 days in the clock display or in the clocktable.
3015 See `org-effort-durations' on how to set effort durations
3016 and `org-time-clocksum-format' for more on time clock formats."
3017 :group 'org-time
3018 :group 'org-clock
3019 :version "24.4"
3020 :package-version '(Org . "8.0")
3021 :type 'boolean)
3023 (defcustom org-time-clocksum-fractional-format "%.2f"
3024 "The format string used when creating CLOCKSUM lines,
3025 or when Org mode generates a time duration, if
3026 `org-time-clocksum-use-fractional' is enabled.
3028 The value can be a single format string containing one
3029 %-sequence, which will be filled with the number of hours as
3030 a float.
3032 Alternatively, the value can be a plist associating any of the
3033 keys :years, :months, :weeks, :days, :hours or :minutes with
3034 a format string. The time duration is formatted using the
3035 largest time unit which gives a non-zero integer part. If all
3036 specified formats have zero integer part, the smallest time unit
3037 is used."
3038 :group 'org-time
3039 :type '(choice (string :tag "Format string")
3040 (set (group :inline t (const :tag "Years" :years)
3041 (string :tag "Format string"))
3042 (group :inline t (const :tag "Months" :months)
3043 (string :tag "Format string"))
3044 (group :inline t (const :tag "Weeks" :weeks)
3045 (string :tag "Format string"))
3046 (group :inline t (const :tag "Days" :days)
3047 (string :tag "Format string"))
3048 (group :inline t (const :tag "Hours" :hours)
3049 (string :tag "Format string"))
3050 (group :inline t (const :tag "Minutes" :minutes)
3051 (string :tag "Format string")))))
3053 (defcustom org-deadline-warning-days 14
3054 "Number of days before expiration during which a deadline becomes active.
3055 This variable governs the display in sparse trees and in the agenda.
3056 When 0 or negative, it means use this number (the absolute value of it)
3057 even if a deadline has a different individual lead time specified.
3059 Custom commands can set this variable in the options section."
3060 :group 'org-time
3061 :group 'org-agenda-daily/weekly
3062 :type 'integer)
3064 (defcustom org-scheduled-delay-days 0
3065 "Number of days before a scheduled item becomes active.
3066 This variable governs the display in sparse trees and in the agenda.
3067 The default value (i.e. 0) means: don't delay scheduled item.
3068 When negative, it means use this number (the absolute value of it)
3069 even if a scheduled item has a different individual delay time
3070 specified.
3072 Custom commands can set this variable in the options section."
3073 :group 'org-time
3074 :group 'org-agenda-daily/weekly
3075 :version "24.4"
3076 :package-version '(Org . "8.0")
3077 :type 'integer)
3079 (defcustom org-read-date-prefer-future t
3080 "Non-nil means assume future for incomplete date input from user.
3081 This affects the following situations:
3082 1. The user gives a month but not a year.
3083 For example, if it is April and you enter \"feb 2\", this will be read
3084 as Feb 2, *next* year. \"May 5\", however, will be this year.
3085 2. The user gives a day, but no month.
3086 For example, if today is the 15th, and you enter \"3\", Org-mode will
3087 read this as the third of *next* month. However, if you enter \"17\",
3088 it will be considered as *this* month.
3090 If you set this variable to the symbol `time', then also the following
3091 will work:
3093 3. If the user gives a time.
3094 If the time is before now, it will be interpreted as tomorrow.
3096 Currently none of this works for ISO week specifications.
3098 When this option is nil, the current day, month and year will always be
3099 used as defaults.
3101 See also `org-agenda-jump-prefer-future'."
3102 :group 'org-time
3103 :type '(choice
3104 (const :tag "Never" nil)
3105 (const :tag "Check month and day" t)
3106 (const :tag "Check month, day, and time" time)))
3108 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3109 "Should the agenda jump command prefer the future for incomplete dates?
3110 The default is to do the same as configured in `org-read-date-prefer-future'.
3111 But you can also set a deviating value here.
3112 This may t or nil, or the symbol `org-read-date-prefer-future'."
3113 :group 'org-agenda
3114 :group 'org-time
3115 :version "24.1"
3116 :type '(choice
3117 (const :tag "Use org-read-date-prefer-future"
3118 org-read-date-prefer-future)
3119 (const :tag "Never" nil)
3120 (const :tag "Always" t)))
3122 (defcustom org-read-date-force-compatible-dates t
3123 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3125 Depending on the system Emacs is running on, certain dates cannot
3126 be represented with the type used internally to represent time.
3127 Dates between 1970-1-1 and 2038-1-1 can always be represented
3128 correctly. Some systems allow for earlier dates, some for later,
3129 some for both. One way to find out it to insert any date into an
3130 Org buffer, putting the cursor on the year and hitting S-up and
3131 S-down to test the range.
3133 When this variable is set to t, the date/time prompt will not let
3134 you specify dates outside the 1970-2037 range, so it is certain that
3135 these dates will work in whatever version of Emacs you are
3136 running, and also that you can move a file from one Emacs implementation
3137 to another. WHenever Org is forcing the year for you, it will display
3138 a message and beep.
3140 When this variable is nil, Org will check if the date is
3141 representable in the specific Emacs implementation you are using.
3142 If not, it will force a year, usually the current year, and beep
3143 to remind you. Currently this setting is not recommended because
3144 the likelihood that you will open your Org files in an Emacs that
3145 has limited date range is not negligible.
3147 A workaround for this problem is to use diary sexp dates for time
3148 stamps outside of this range."
3149 :group 'org-time
3150 :version "24.1"
3151 :type 'boolean)
3153 (defcustom org-read-date-display-live t
3154 "Non-nil means display current interpretation of date prompt live.
3155 This display will be in an overlay, in the minibuffer."
3156 :group 'org-time
3157 :type 'boolean)
3159 (defcustom org-read-date-popup-calendar t
3160 "Non-nil means pop up a calendar when prompting for a date.
3161 In the calendar, the date can be selected with mouse-1. However, the
3162 minibuffer will also be active, and you can simply enter the date as well.
3163 When nil, only the minibuffer will be available."
3164 :group 'org-time
3165 :type 'boolean)
3166 (org-defvaralias 'org-popup-calendar-for-date-prompt
3167 'org-read-date-popup-calendar)
3169 (make-obsolete-variable
3170 'org-read-date-minibuffer-setup-hook
3171 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3172 (defcustom org-read-date-minibuffer-setup-hook nil
3173 "Hook to be used to set up keys for the date/time interface.
3174 Add key definitions to `minibuffer-local-map', which will be a
3175 temporary copy.
3177 WARNING: This option is obsolete, you should use
3178 `org-read-date-minibuffer-local-map' to set up keys."
3179 :group 'org-time
3180 :type 'hook)
3182 (defcustom org-extend-today-until 0
3183 "The hour when your day really ends. Must be an integer.
3184 This has influence for the following applications:
3185 - When switching the agenda to \"today\". It it is still earlier than
3186 the time given here, the day recognized as TODAY is actually yesterday.
3187 - When a date is read from the user and it is still before the time given
3188 here, the current date and time will be assumed to be yesterday, 23:59.
3189 Also, timestamps inserted in capture templates follow this rule.
3191 IMPORTANT: This is a feature whose implementation is and likely will
3192 remain incomplete. Really, it is only here because past midnight seems to
3193 be the favorite working time of John Wiegley :-)"
3194 :group 'org-time
3195 :type 'integer)
3197 (defcustom org-use-effective-time nil
3198 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3199 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3200 \"effective time\" of any timestamps between midnight and 8am will be
3201 23:59 of the previous day."
3202 :group 'org-time
3203 :version "24.1"
3204 :type 'boolean)
3206 (defcustom org-use-last-clock-out-time-as-effective-time nil
3207 "When non-nil, use the last clock out time for `org-todo'.
3208 Note that this option has precedence over the combined use of
3209 `org-use-effective-time' and `org-extend-today-until'."
3210 :group 'org-time
3211 :version "24.4"
3212 :package-version '(Org . "8.0")
3213 :type 'boolean)
3215 (defcustom org-edit-timestamp-down-means-later nil
3216 "Non-nil means S-down will increase the time in a time stamp.
3217 When nil, S-up will increase."
3218 :group 'org-time
3219 :type 'boolean)
3221 (defcustom org-calendar-follow-timestamp-change t
3222 "Non-nil means make the calendar window follow timestamp changes.
3223 When a timestamp is modified and the calendar window is visible, it will be
3224 moved to the new date."
3225 :group 'org-time
3226 :type 'boolean)
3228 (defgroup org-tags nil
3229 "Options concerning tags in Org-mode."
3230 :tag "Org Tags"
3231 :group 'org)
3233 (defcustom org-tag-alist nil
3234 "List of tags allowed in Org-mode files.
3235 When this list is nil, Org-mode will base TAG input on what is already in the
3236 buffer.
3237 The value of this variable is an alist, the car of each entry must be a
3238 keyword as a string, the cdr may be a character that is used to select
3239 that tag through the fast-tag-selection interface.
3240 See the manual for details."
3241 :group 'org-tags
3242 :type '(repeat
3243 (choice
3244 (cons (string :tag "Tag name")
3245 (character :tag "Access char"))
3246 (list :tag "Start radio group"
3247 (const :startgroup)
3248 (option (string :tag "Group description")))
3249 (list :tag "Group tags delimiter"
3250 (const :grouptags))
3251 (list :tag "End radio group"
3252 (const :endgroup)
3253 (option (string :tag "Group description")))
3254 (const :tag "New line" (:newline)))))
3256 (defcustom org-tag-persistent-alist nil
3257 "List of tags that will always appear in all Org-mode files.
3258 This is in addition to any in buffer settings or customizations
3259 of `org-tag-alist'.
3260 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3261 The value of this variable is an alist, the car of each entry must be a
3262 keyword as a string, the cdr may be a character that is used to select
3263 that tag through the fast-tag-selection interface.
3264 See the manual for details.
3265 To disable these tags on a per-file basis, insert anywhere in the file:
3266 #+STARTUP: noptag"
3267 :group 'org-tags
3268 :type '(repeat
3269 (choice
3270 (cons (string :tag "Tag name")
3271 (character :tag "Access char"))
3272 (const :tag "Start radio group" (:startgroup))
3273 (const :tag "Group tags delimiter" (:grouptags))
3274 (const :tag "End radio group" (:endgroup))
3275 (const :tag "New line" (:newline)))))
3277 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3278 "If non-nil, always offer completion for all tags of all agenda files.
3279 Instead of customizing this variable directly, you might want to
3280 set it locally for capture buffers, because there no list of
3281 tags in that file can be created dynamically (there are none).
3283 (add-hook 'org-capture-mode-hook
3284 (lambda ()
3285 (set (make-local-variable
3286 'org-complete-tags-always-offer-all-agenda-tags)
3287 t)))"
3288 :group 'org-tags
3289 :version "24.1"
3290 :type 'boolean)
3292 (defvar org-file-tags nil
3293 "List of tags that can be inherited by all entries in the file.
3294 The tags will be inherited if the variable `org-use-tag-inheritance'
3295 says they should be.
3296 This variable is populated from #+FILETAGS lines.")
3298 (defcustom org-use-fast-tag-selection 'auto
3299 "Non-nil means use fast tag selection scheme.
3300 This is a special interface to select and deselect tags with single keys.
3301 When nil, fast selection is never used.
3302 When the symbol `auto', fast selection is used if and only if selection
3303 characters for tags have been configured, either through the variable
3304 `org-tag-alist' or through a #+TAGS line in the buffer.
3305 When t, fast selection is always used and selection keys are assigned
3306 automatically if necessary."
3307 :group 'org-tags
3308 :type '(choice
3309 (const :tag "Always" t)
3310 (const :tag "Never" nil)
3311 (const :tag "When selection characters are configured" auto)))
3313 (defcustom org-fast-tag-selection-single-key nil
3314 "Non-nil means fast tag selection exits after first change.
3315 When nil, you have to press RET to exit it.
3316 During fast tag selection, you can toggle this flag with `C-c'.
3317 This variable can also have the value `expert'. In this case, the window
3318 displaying the tags menu is not even shown, until you press C-c again."
3319 :group 'org-tags
3320 :type '(choice
3321 (const :tag "No" nil)
3322 (const :tag "Yes" t)
3323 (const :tag "Expert" expert)))
3325 (defvar org-fast-tag-selection-include-todo nil
3326 "Non-nil means fast tags selection interface will also offer TODO states.
3327 This is an undocumented feature, you should not rely on it.")
3329 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3330 "The column to which tags should be indented in a headline.
3331 If this number is positive, it specifies the column. If it is negative,
3332 it means that the tags should be flushright to that column. For example,
3333 -80 works well for a normal 80 character screen.
3334 When 0, place tags directly after headline text, with only one space in
3335 between."
3336 :group 'org-tags
3337 :type 'integer)
3339 (defcustom org-auto-align-tags t
3340 "Non-nil keeps tags aligned when modifying headlines.
3341 Some operations (i.e. demoting) change the length of a headline and
3342 therefore shift the tags around. With this option turned on, after
3343 each such operation the tags are again aligned to `org-tags-column'."
3344 :group 'org-tags
3345 :type 'boolean)
3347 (defcustom org-use-tag-inheritance t
3348 "Non-nil means tags in levels apply also for sublevels.
3349 When nil, only the tags directly given in a specific line apply there.
3350 This may also be a list of tags that should be inherited, or a regexp that
3351 matches tags that should be inherited. Additional control is possible
3352 with the variable `org-tags-exclude-from-inheritance' which gives an
3353 explicit list of tags to be excluded from inheritance, even if the value of
3354 `org-use-tag-inheritance' would select it for inheritance.
3356 If this option is t, a match early-on in a tree can lead to a large
3357 number of matches in the subtree when constructing the agenda or creating
3358 a sparse tree. If you only want to see the first match in a tree during
3359 a search, check out the variable `org-tags-match-list-sublevels'."
3360 :group 'org-tags
3361 :type '(choice
3362 (const :tag "Not" nil)
3363 (const :tag "Always" t)
3364 (repeat :tag "Specific tags" (string :tag "Tag"))
3365 (regexp :tag "Tags matched by regexp")))
3367 (defcustom org-tags-exclude-from-inheritance nil
3368 "List of tags that should never be inherited.
3369 This is a way to exclude a few tags from inheritance. For way to do
3370 the opposite, to actively allow inheritance for selected tags,
3371 see the variable `org-use-tag-inheritance'."
3372 :group 'org-tags
3373 :type '(repeat (string :tag "Tag")))
3375 (defun org-tag-inherit-p (tag)
3376 "Check if TAG is one that should be inherited."
3377 (cond
3378 ((member tag org-tags-exclude-from-inheritance) nil)
3379 ((eq org-use-tag-inheritance t) t)
3380 ((not org-use-tag-inheritance) nil)
3381 ((stringp org-use-tag-inheritance)
3382 (string-match org-use-tag-inheritance tag))
3383 ((listp org-use-tag-inheritance)
3384 (member tag org-use-tag-inheritance))
3385 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3387 (defcustom org-tags-match-list-sublevels t
3388 "Non-nil means list also sublevels of headlines matching a search.
3389 This variable applies to tags/property searches, and also to stuck
3390 projects because this search is based on a tags match as well.
3392 When set to the symbol `indented', sublevels are indented with
3393 leading dots.
3395 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3396 the sublevels of a headline matching a tag search often also match
3397 the same search. Listing all of them can create very long lists.
3398 Setting this variable to nil causes subtrees of a match to be skipped.
3400 This variable is semi-obsolete and probably should always be true. It
3401 is better to limit inheritance to certain tags using the variables
3402 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3403 :group 'org-tags
3404 :type '(choice
3405 (const :tag "No, don't list them" nil)
3406 (const :tag "Yes, do list them" t)
3407 (const :tag "List them, indented with leading dots" indented)))
3409 (defcustom org-tags-sort-function nil
3410 "When set, tags are sorted using this function as a comparator."
3411 :group 'org-tags
3412 :type '(choice
3413 (const :tag "No sorting" nil)
3414 (const :tag "Alphabetical" string<)
3415 (const :tag "Reverse alphabetical" string>)
3416 (function :tag "Custom function" nil)))
3418 (defvar org-tags-history nil
3419 "History of minibuffer reads for tags.")
3420 (defvar org-last-tags-completion-table nil
3421 "The last used completion table for tags.")
3422 (defvar org-after-tags-change-hook nil
3423 "Hook that is run after the tags in a line have changed.")
3425 (defgroup org-properties nil
3426 "Options concerning properties in Org-mode."
3427 :tag "Org Properties"
3428 :group 'org)
3430 (defcustom org-property-format "%-10s %s"
3431 "How property key/value pairs should be formatted by `indent-line'.
3432 When `indent-line' hits a property definition, it will format the line
3433 according to this format, mainly to make sure that the values are
3434 lined-up with respect to each other."
3435 :group 'org-properties
3436 :type 'string)
3438 (defcustom org-properties-postprocess-alist nil
3439 "Alist of properties and functions to adjust inserted values.
3440 Elements of this alist must be of the form
3442 ([string] [function])
3444 where [string] must be a property name and [function] must be a
3445 lambda expression: this lambda expression must take one argument,
3446 the value to adjust, and return the new value as a string.
3448 For example, this element will allow the property \"Remaining\"
3449 to be updated wrt the relation between the \"Effort\" property
3450 and the clock summary:
3452 ((\"Remaining\" (lambda(value)
3453 (let ((clocksum (org-clock-sum-current-item))
3454 (effort (org-duration-string-to-minutes
3455 (org-entry-get (point) \"Effort\"))))
3456 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3457 :group 'org-properties
3458 :version "24.1"
3459 :type '(alist :key-type (string :tag "Property")
3460 :value-type (function :tag "Function")))
3462 (defcustom org-use-property-inheritance nil
3463 "Non-nil means properties apply also for sublevels.
3465 This setting is chiefly used during property searches. Turning it on can
3466 cause significant overhead when doing a search, which is why it is not
3467 on by default.
3469 When nil, only the properties directly given in the current entry count.
3470 When t, every property is inherited. The value may also be a list of
3471 properties that should have inheritance, or a regular expression matching
3472 properties that should be inherited.
3474 However, note that some special properties use inheritance under special
3475 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3476 and the properties ending in \"_ALL\" when they are used as descriptor
3477 for valid values of a property.
3479 Note for programmers:
3480 When querying an entry with `org-entry-get', you can control if inheritance
3481 should be used. By default, `org-entry-get' looks only at the local
3482 properties. You can request inheritance by setting the inherit argument
3483 to t (to force inheritance) or to `selective' (to respect the setting
3484 in this variable)."
3485 :group 'org-properties
3486 :type '(choice
3487 (const :tag "Not" nil)
3488 (const :tag "Always" t)
3489 (repeat :tag "Specific properties" (string :tag "Property"))
3490 (regexp :tag "Properties matched by regexp")))
3492 (defun org-property-inherit-p (property)
3493 "Check if PROPERTY is one that should be inherited."
3494 (cond
3495 ((eq org-use-property-inheritance t) t)
3496 ((not org-use-property-inheritance) nil)
3497 ((stringp org-use-property-inheritance)
3498 (string-match org-use-property-inheritance property))
3499 ((listp org-use-property-inheritance)
3500 (member property org-use-property-inheritance))
3501 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3503 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3504 "The default column format, if no other format has been defined.
3505 This variable can be set on the per-file basis by inserting a line
3507 #+COLUMNS: %25ITEM ....."
3508 :group 'org-properties
3509 :type 'string)
3511 (defcustom org-columns-ellipses ".."
3512 "The ellipses to be used when a field in column view is truncated.
3513 When this is the empty string, as many characters as possible are shown,
3514 but then there will be no visual indication that the field has been truncated.
3515 When this is a string of length N, the last N characters of a truncated
3516 field are replaced by this string. If the column is narrower than the
3517 ellipses string, only part of the ellipses string will be shown."
3518 :group 'org-properties
3519 :type 'string)
3521 (defcustom org-columns-modify-value-for-display-function nil
3522 "Function that modifies values for display in column view.
3523 For example, it can be used to cut out a certain part from a time stamp.
3524 The function must take 2 arguments:
3526 column-title The title of the column (*not* the property name)
3527 value The value that should be modified.
3529 The function should return the value that should be displayed,
3530 or nil if the normal value should be used."
3531 :group 'org-properties
3532 :type '(choice (const nil) (function)))
3534 (defcustom org-effort-property "Effort"
3535 "The property that is being used to keep track of effort estimates.
3536 Effort estimates given in this property need to have the format H:MM."
3537 :group 'org-properties
3538 :group 'org-progress
3539 :type '(string :tag "Property"))
3541 (defconst org-global-properties-fixed
3542 '(("VISIBILITY_ALL" . "folded children content all")
3543 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3544 "List of property/value pairs that can be inherited by any entry.
3546 These are fixed values, for the preset properties. The user variable
3547 that can be used to add to this list is `org-global-properties'.
3549 The entries in this list are cons cells where the car is a property
3550 name and cdr is a string with the value. If the value represents
3551 multiple items like an \"_ALL\" property, separate the items by
3552 spaces.")
3554 (defcustom org-global-properties nil
3555 "List of property/value pairs that can be inherited by any entry.
3557 This list will be combined with the constant `org-global-properties-fixed'.
3559 The entries in this list are cons cells where the car is a property
3560 name and cdr is a string with the value.
3562 You can set buffer-local values for the same purpose in the variable
3563 `org-file-properties' this by adding lines like
3565 #+PROPERTY: NAME VALUE"
3566 :group 'org-properties
3567 :type '(repeat
3568 (cons (string :tag "Property")
3569 (string :tag "Value"))))
3571 (defvar org-file-properties nil
3572 "List of property/value pairs that can be inherited by any entry.
3573 Valid for the current buffer.
3574 This variable is populated from #+PROPERTY lines.")
3575 (make-variable-buffer-local 'org-file-properties)
3577 (defgroup org-agenda nil
3578 "Options concerning agenda views in Org-mode."
3579 :tag "Org Agenda"
3580 :group 'org)
3582 (defvar org-category nil
3583 "Variable used by org files to set a category for agenda display.
3584 Such files should use a file variable to set it, for example
3586 # -*- mode: org; org-category: \"ELisp\"
3588 or contain a special line
3590 #+CATEGORY: ELisp
3592 If the file does not specify a category, then file's base name
3593 is used instead.")
3594 (make-variable-buffer-local 'org-category)
3595 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3597 (defcustom org-agenda-files nil
3598 "The files to be used for agenda display.
3599 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3600 \\[org-remove-file]. You can also use customize to edit the list.
3602 If an entry is a directory, all files in that directory that are matched by
3603 `org-agenda-file-regexp' will be part of the file list.
3605 If the value of the variable is not a list but a single file name, then
3606 the list of agenda files is actually stored and maintained in that file, one
3607 agenda file per line. In this file paths can be given relative to
3608 `org-directory'. Tilde expansion and environment variable substitution
3609 are also made."
3610 :group 'org-agenda
3611 :type '(choice
3612 (repeat :tag "List of files and directories" file)
3613 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3615 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3616 "Regular expression to match files for `org-agenda-files'.
3617 If any element in the list in that variable contains a directory instead
3618 of a normal file, all files in that directory that are matched by this
3619 regular expression will be included."
3620 :group 'org-agenda
3621 :type 'regexp)
3623 (defcustom org-agenda-text-search-extra-files nil
3624 "List of extra files to be searched by text search commands.
3625 These files will be searched in addition to the agenda files by the
3626 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3627 Note that these files will only be searched for text search commands,
3628 not for the other agenda views like todo lists, tag searches or the weekly
3629 agenda. This variable is intended to list notes and possibly archive files
3630 that should also be searched by these two commands.
3631 In fact, if the first element in the list is the symbol `agenda-archives',
3632 then all archive files of all agenda files will be added to the search
3633 scope."
3634 :group 'org-agenda
3635 :type '(set :greedy t
3636 (const :tag "Agenda Archives" agenda-archives)
3637 (repeat :inline t (file))))
3639 (org-defvaralias 'org-agenda-multi-occur-extra-files
3640 'org-agenda-text-search-extra-files)
3642 (defcustom org-agenda-skip-unavailable-files nil
3643 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3644 A nil value means to remove them, after a query, from the list."
3645 :group 'org-agenda
3646 :type 'boolean)
3648 (defcustom org-calendar-to-agenda-key [?c]
3649 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3650 The command `org-calendar-goto-agenda' will be bound to this key. The
3651 default is the character `c' because then `c' can be used to switch back and
3652 forth between agenda and calendar."
3653 :group 'org-agenda
3654 :type 'sexp)
3656 (defcustom org-calendar-insert-diary-entry-key [?i]
3657 "The key to be installed in `calendar-mode-map' for adding diary entries.
3658 This option is irrelevant until `org-agenda-diary-file' has been configured
3659 to point to an Org-mode file. When that is the case, the command
3660 `org-agenda-diary-entry' will be bound to the key given here, by default
3661 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3662 if you want to continue doing this, you need to change this to a different
3663 key."
3664 :group 'org-agenda
3665 :type 'sexp)
3667 (defcustom org-agenda-diary-file 'diary-file
3668 "File to which to add new entries with the `i' key in agenda and calendar.
3669 When this is the symbol `diary-file', the functionality in the Emacs
3670 calendar will be used to add entries to the `diary-file'. But when this
3671 points to a file, `org-agenda-diary-entry' will be used instead."
3672 :group 'org-agenda
3673 :type '(choice
3674 (const :tag "The standard Emacs diary file" diary-file)
3675 (file :tag "Special Org file diary entries")))
3677 (eval-after-load "calendar"
3678 '(progn
3679 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3680 'org-calendar-goto-agenda)
3681 (add-hook 'calendar-mode-hook
3682 (lambda ()
3683 (unless (eq org-agenda-diary-file 'diary-file)
3684 (define-key calendar-mode-map
3685 org-calendar-insert-diary-entry-key
3686 'org-agenda-diary-entry))))))
3688 (defgroup org-latex nil
3689 "Options for embedding LaTeX code into Org-mode."
3690 :tag "Org LaTeX"
3691 :group 'org)
3693 (defcustom org-format-latex-options
3694 '(:foreground default :background default :scale 1.0
3695 :html-foreground "Black" :html-background "Transparent"
3696 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3697 "Options for creating images from LaTeX fragments.
3698 This is a property list with the following properties:
3699 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3700 `default' means use the foreground of the default face.
3701 `auto' means use the foreground from the text face.
3702 :background the background color, or \"Transparent\".
3703 `default' means use the background of the default face.
3704 `auto' means use the background from the text face.
3705 :scale a scaling factor for the size of the images, to get more pixels
3706 :html-foreground, :html-background, :html-scale
3707 the same numbers for HTML export.
3708 :matchers a list indicating which matchers should be used to
3709 find LaTeX fragments. Valid members of this list are:
3710 \"begin\" find environments
3711 \"$1\" find single characters surrounded by $.$
3712 \"$\" find math expressions surrounded by $...$
3713 \"$$\" find math expressions surrounded by $$....$$
3714 \"\\(\" find math expressions surrounded by \\(...\\)
3715 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3716 :group 'org-latex
3717 :type 'plist)
3719 (defcustom org-format-latex-signal-error t
3720 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3721 When nil, just push out a message."
3722 :group 'org-latex
3723 :version "24.1"
3724 :type 'boolean)
3726 (defcustom org-latex-to-mathml-jar-file nil
3727 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3728 Use this to specify additional executable file say a jar file.
3730 When using MathToWeb as the converter, specify the full-path to
3731 your mathtoweb.jar file."
3732 :group 'org-latex
3733 :version "24.1"
3734 :type '(choice
3735 (const :tag "None" nil)
3736 (file :tag "JAR file" :must-match t)))
3738 (defcustom org-latex-to-mathml-convert-command nil
3739 "Command to convert LaTeX fragments to MathML.
3740 Replace format-specifiers in the command as noted below and use
3741 `shell-command' to convert LaTeX to MathML.
3742 %j: Executable file in fully expanded form as specified by
3743 `org-latex-to-mathml-jar-file'.
3744 %I: Input LaTeX file in fully expanded form
3745 %o: Output MathML file
3746 This command is used by `org-create-math-formula'.
3748 When using MathToWeb as the converter, set this to
3749 \"java -jar %j -unicode -force -df %o %I\"."
3750 :group 'org-latex
3751 :version "24.1"
3752 :type '(choice
3753 (const :tag "None" nil)
3754 (string :tag "\nShell command")))
3756 (defcustom org-latex-create-formula-image-program 'dvipng
3757 "Program to convert LaTeX fragments with.
3759 dvipng Process the LaTeX fragments to dvi file, then convert
3760 dvi files to png files using dvipng.
3761 This will also include processing of non-math environments.
3762 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3763 to convert pdf files to png files"
3764 :group 'org-latex
3765 :version "24.1"
3766 :type '(choice
3767 (const :tag "dvipng" dvipng)
3768 (const :tag "imagemagick" imagemagick)))
3770 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3771 "Path to store latex preview images.
3772 A relative path here creates many directories relative to the
3773 processed org files paths. An absolute path puts all preview
3774 images at the same place."
3775 :group 'org-latex
3776 :version "24.3"
3777 :type 'string)
3779 (defun org-format-latex-mathml-available-p ()
3780 "Return t if `org-latex-to-mathml-convert-command' is usable."
3781 (save-match-data
3782 (when (and (boundp 'org-latex-to-mathml-convert-command)
3783 org-latex-to-mathml-convert-command)
3784 (let ((executable (car (split-string
3785 org-latex-to-mathml-convert-command))))
3786 (when (executable-find executable)
3787 (if (string-match
3788 "%j" org-latex-to-mathml-convert-command)
3789 (file-readable-p org-latex-to-mathml-jar-file)
3790 t))))))
3792 (defcustom org-format-latex-header "\\documentclass{article}
3793 \\usepackage[usenames]{color}
3794 \[PACKAGES]
3795 \[DEFAULT-PACKAGES]
3796 \\pagestyle{empty} % do not remove
3797 % The settings below are copied from fullpage.sty
3798 \\setlength{\\textwidth}{\\paperwidth}
3799 \\addtolength{\\textwidth}{-3cm}
3800 \\setlength{\\oddsidemargin}{1.5cm}
3801 \\addtolength{\\oddsidemargin}{-2.54cm}
3802 \\setlength{\\evensidemargin}{\\oddsidemargin}
3803 \\setlength{\\textheight}{\\paperheight}
3804 \\addtolength{\\textheight}{-\\headheight}
3805 \\addtolength{\\textheight}{-\\headsep}
3806 \\addtolength{\\textheight}{-\\footskip}
3807 \\addtolength{\\textheight}{-3cm}
3808 \\setlength{\\topmargin}{1.5cm}
3809 \\addtolength{\\topmargin}{-2.54cm}"
3810 "The document header used for processing LaTeX fragments.
3811 It is imperative that this header make sure that no page number
3812 appears on the page. The package defined in the variables
3813 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3814 will either replace the placeholder \"[PACKAGES]\" in this
3815 header, or they will be appended."
3816 :group 'org-latex
3817 :type 'string)
3819 (defun org-set-packages-alist (var val)
3820 "Set the packages alist and make sure it has 3 elements per entry."
3821 (set var (mapcar (lambda (x)
3822 (if (and (consp x) (= (length x) 2))
3823 (list (car x) (nth 1 x) t)
3825 val)))
3827 (defun org-get-packages-alist (var)
3828 "Get the packages alist and make sure it has 3 elements per entry."
3829 (mapcar (lambda (x)
3830 (if (and (consp x) (= (length x) 2))
3831 (list (car x) (nth 1 x) t)
3833 (default-value var)))
3835 (defcustom org-latex-default-packages-alist
3836 '(("AUTO" "inputenc" t)
3837 ("T1" "fontenc" t)
3838 ("" "fixltx2e" nil)
3839 ("" "graphicx" t)
3840 ("" "longtable" nil)
3841 ("" "float" nil)
3842 ("" "wrapfig" nil)
3843 ("" "rotating" nil)
3844 ("normalem" "ulem" t)
3845 ("" "amsmath" t)
3846 ("" "textcomp" t)
3847 ("" "marvosym" t)
3848 ("" "wasysym" t)
3849 ("" "amssymb" t)
3850 ("" "hyperref" nil)
3851 "\\tolerance=1000")
3852 "Alist of default packages to be inserted in the header.
3854 Change this only if one of the packages here causes an
3855 incompatibility with another package you are using.
3857 The packages in this list are needed by one part or another of
3858 Org mode to function properly:
3860 - inputenc, fontenc: for basic font and character selection
3861 - fixltx2e: Important patches of LaTeX itself
3862 - graphicx: for including images
3863 - longtable: For multipage tables
3864 - float, wrapfig: for figure placement
3865 - rotating: for sideways figures and tables
3866 - ulem: for underline and strike-through
3867 - amsmath: for subscript and superscript and math environments
3868 - textcomp, marvosymb, wasysym, amssymb: for various symbols used
3869 for interpreting the entities in `org-entities'. You can skip
3870 some of these packages if you don't use any of their symbols.
3871 - hyperref: for cross references
3873 Therefore you should not modify this variable unless you know
3874 what you are doing. The one reason to change it anyway is that
3875 you might be loading some other package that conflicts with one
3876 of the default packages. Each cell is of the format
3877 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
3878 the package also needs to be included when compiling LaTeX
3879 snippets into images for inclusion into non-LaTeX output."
3880 :group 'org-latex
3881 :group 'org-export-latex
3882 :set 'org-set-packages-alist
3883 :get 'org-get-packages-alist
3884 :version "24.1"
3885 :type '(repeat
3886 (choice
3887 (list :tag "options/package pair"
3888 (string :tag "options")
3889 (string :tag "package")
3890 (boolean :tag "Snippet"))
3891 (string :tag "A line of LaTeX"))))
3893 (defcustom org-latex-packages-alist nil
3894 "Alist of packages to be inserted in every LaTeX header.
3896 These will be inserted after `org-latex-default-packages-alist'.
3897 Each cell is of the format:
3899 \(\"options\" \"package\" snippet-flag)
3901 SNIPPET-FLAG, when t, indicates that this package is also needed
3902 when turning LaTeX snippets into images for inclusion into
3903 non-LaTeX output.
3905 Make sure that you only list packages here which:
3907 - you want in every file
3908 - do not conflict with the setup in `org-format-latex-header'.
3909 - do not conflict with the default packages in
3910 `org-latex-default-packages-alist'."
3911 :group 'org-latex
3912 :group 'org-export-latex
3913 :set 'org-set-packages-alist
3914 :get 'org-get-packages-alist
3915 :type '(repeat
3916 (choice
3917 (list :tag "options/package pair"
3918 (string :tag "options")
3919 (string :tag "package")
3920 (boolean :tag "Snippet"))
3921 (string :tag "A line of LaTeX"))))
3923 (defgroup org-appearance nil
3924 "Settings for Org-mode appearance."
3925 :tag "Org Appearance"
3926 :group 'org)
3928 (defcustom org-level-color-stars-only nil
3929 "Non-nil means fontify only the stars in each headline.
3930 When nil, the entire headline is fontified.
3931 Changing it requires restart of `font-lock-mode' to become effective
3932 also in regions already fontified."
3933 :group 'org-appearance
3934 :type 'boolean)
3936 (defcustom org-hide-leading-stars nil
3937 "Non-nil means hide the first N-1 stars in a headline.
3938 This works by using the face `org-hide' for these stars. This
3939 face is white for a light background, and black for a dark
3940 background. You may have to customize the face `org-hide' to
3941 make this work.
3942 Changing it requires restart of `font-lock-mode' to become effective
3943 also in regions already fontified.
3944 You may also set this on a per-file basis by adding one of the following
3945 lines to the buffer:
3947 #+STARTUP: hidestars
3948 #+STARTUP: showstars"
3949 :group 'org-appearance
3950 :type 'boolean)
3952 (defcustom org-hidden-keywords nil
3953 "List of symbols corresponding to keywords to be hidden the org buffer.
3954 For example, a value '(title) for this list will make the document's title
3955 appear in the buffer without the initial #+TITLE: keyword."
3956 :group 'org-appearance
3957 :version "24.1"
3958 :type '(set (const :tag "#+AUTHOR" author)
3959 (const :tag "#+DATE" date)
3960 (const :tag "#+EMAIL" email)
3961 (const :tag "#+TITLE" title)))
3963 (defcustom org-custom-properties nil
3964 "List of properties (as strings) with a special meaning.
3965 The default use of these custom properties is to let the user
3966 hide them with `org-toggle-custom-properties-visibility'."
3967 :group 'org-properties
3968 :group 'org-appearance
3969 :version "24.3"
3970 :type '(repeat (string :tag "Property Name")))
3972 (defcustom org-fontify-done-headline nil
3973 "Non-nil means change the face of a headline if it is marked DONE.
3974 Normally, only the TODO/DONE keyword indicates the state of a headline.
3975 When this is non-nil, the headline after the keyword is set to the
3976 `org-headline-done' as an additional indication."
3977 :group 'org-appearance
3978 :type 'boolean)
3980 (defcustom org-fontify-emphasized-text t
3981 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3982 Changing this variable requires a restart of Emacs to take effect."
3983 :group 'org-appearance
3984 :type 'boolean)
3986 (defcustom org-fontify-whole-heading-line nil
3987 "Non-nil means fontify the whole line for headings.
3988 This is useful when setting a background color for the
3989 org-level-* faces."
3990 :group 'org-appearance
3991 :type 'boolean)
3993 (defcustom org-highlight-latex-and-related nil
3994 "Non-nil means highlight LaTeX related syntax in the buffer.
3995 When non nil, the value should be a list containing any of the
3996 following symbols:
3997 `latex' Highlight LaTeX snippets and environments.
3998 `script' Highlight subscript and superscript.
3999 `entities' Highlight entities."
4000 :group 'org-appearance
4001 :version "24.4"
4002 :package-version '(Org . "8.0")
4003 :type '(choice
4004 (const :tag "No highlighting" nil)
4005 (set :greedy t :tag "Highlight"
4006 (const :tag "LaTeX snippets and environments" latex)
4007 (const :tag "Subscript and superscript" script)
4008 (const :tag "Entities" entities))))
4010 (defcustom org-hide-emphasis-markers nil
4011 "Non-nil mean font-lock should hide the emphasis marker characters."
4012 :group 'org-appearance
4013 :type 'boolean)
4015 (defcustom org-pretty-entities nil
4016 "Non-nil means show entities as UTF8 characters.
4017 When nil, the \\name form remains in the buffer."
4018 :group 'org-appearance
4019 :version "24.1"
4020 :type 'boolean)
4022 (defcustom org-pretty-entities-include-sub-superscripts t
4023 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4024 :group 'org-appearance
4025 :version "24.1"
4026 :type 'boolean)
4028 (defvar org-emph-re nil
4029 "Regular expression for matching emphasis.
4030 After a match, the match groups contain these elements:
4031 0 The match of the full regular expression, including the characters
4032 before and after the proper match
4033 1 The character before the proper match, or empty at beginning of line
4034 2 The proper match, including the leading and trailing markers
4035 3 The leading marker like * or /, indicating the type of highlighting
4036 4 The text between the emphasis markers, not including the markers
4037 5 The character after the match, empty at the end of a line")
4038 (defvar org-verbatim-re nil
4039 "Regular expression for matching verbatim text.")
4040 (defvar org-emphasis-regexp-components) ; defined just below
4041 (defvar org-emphasis-alist) ; defined just below
4042 (defun org-set-emph-re (var val)
4043 "Set variable and compute the emphasis regular expression."
4044 (set var val)
4045 (when (and (boundp 'org-emphasis-alist)
4046 (boundp 'org-emphasis-regexp-components)
4047 org-emphasis-alist org-emphasis-regexp-components)
4048 (let* ((e org-emphasis-regexp-components)
4049 (pre (car e))
4050 (post (nth 1 e))
4051 (border (nth 2 e))
4052 (body (nth 3 e))
4053 (nl (nth 4 e))
4054 (body1 (concat body "*?"))
4055 (markers (mapconcat 'car org-emphasis-alist ""))
4056 (vmarkers (mapconcat
4057 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4058 org-emphasis-alist "")))
4059 ;; make sure special characters appear at the right position in the class
4060 (if (string-match "\\^" markers)
4061 (setq markers (concat (replace-match "" t t markers) "^")))
4062 (if (string-match "-" markers)
4063 (setq markers (concat (replace-match "" t t markers) "-")))
4064 (if (string-match "\\^" vmarkers)
4065 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4066 (if (string-match "-" vmarkers)
4067 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4068 (if (> nl 0)
4069 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4070 (int-to-string nl) "\\}")))
4071 ;; Make the regexp
4072 (setq org-emph-re
4073 (concat "\\([" pre "]\\|^\\)"
4074 "\\("
4075 "\\([" markers "]\\)"
4076 "\\("
4077 "[^" border "]\\|"
4078 "[^" border "]"
4079 body1
4080 "[^" border "]"
4081 "\\)"
4082 "\\3\\)"
4083 "\\([" post "]\\|$\\)"))
4084 (setq org-verbatim-re
4085 (concat "\\([" pre "]\\|^\\)"
4086 "\\("
4087 "\\([" vmarkers "]\\)"
4088 "\\("
4089 "[^" border "]\\|"
4090 "[^" border "]"
4091 body1
4092 "[^" border "]"
4093 "\\)"
4094 "\\3\\)"
4095 "\\([" post "]\\|$\\)")))))
4097 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4098 ;; set this option proved cumbersome. See this message/thread:
4099 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4100 (defvar org-emphasis-regexp-components
4101 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4102 "Components used to build the regular expression for emphasis.
4103 This is a list with five entries. Terminology: In an emphasis string
4104 like \" *strong word* \", we call the initial space PREMATCH, the final
4105 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4106 and \"trong wor\" is the body. The different components in this variable
4107 specify what is allowed/forbidden in each part:
4109 pre Chars allowed as prematch. Beginning of line will be allowed too.
4110 post Chars allowed as postmatch. End of line will be allowed too.
4111 border The chars *forbidden* as border characters.
4112 body-regexp A regexp like \".\" to match a body character. Don't use
4113 non-shy groups here, and don't allow newline here.
4114 newline The maximum number of newlines allowed in an emphasis exp.
4116 You need to reload Org or to restart Emacs after customizing this.")
4118 (defcustom org-emphasis-alist
4119 `(("*" bold)
4120 ("/" italic)
4121 ("_" underline)
4122 ("=" org-code verbatim)
4123 ("~" org-verbatim verbatim)
4124 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4125 "Alist of characters and faces to emphasize text.
4126 Text starting and ending with a special character will be emphasized,
4127 for example *bold*, _underlined_ and /italic/. This variable sets the
4128 marker characters and the face to be used by font-lock for highlighting
4129 in Org-mode Emacs buffers.
4131 You need to reload Org or to restart Emacs after customizing this."
4132 :group 'org-appearance
4133 :set 'org-set-emph-re
4134 :version "24.4"
4135 :package-version '(Org . "8.0")
4136 :type '(repeat
4137 (list
4138 (string :tag "Marker character")
4139 (choice
4140 (face :tag "Font-lock-face")
4141 (plist :tag "Face property list"))
4142 (option (const verbatim)))))
4144 (defvar org-protecting-blocks
4145 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4146 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4147 This is needed for font-lock setup.")
4149 ;;; Miscellaneous options
4151 (defgroup org-completion nil
4152 "Completion in Org-mode."
4153 :tag "Org Completion"
4154 :group 'org)
4156 (defcustom org-completion-use-ido nil
4157 "Non-nil means use ido completion wherever possible.
4158 Note that `ido-mode' must be active for this variable to be relevant.
4159 If you decide to turn this variable on, you might well want to turn off
4160 `org-outline-path-complete-in-steps'.
4161 See also `org-completion-use-iswitchb'."
4162 :group 'org-completion
4163 :type 'boolean)
4165 (defcustom org-completion-use-iswitchb nil
4166 "Non-nil means use iswitchb completion wherever possible.
4167 Note that `iswitchb-mode' must be active for this variable to be relevant.
4168 If you decide to turn this variable on, you might well want to turn off
4169 `org-outline-path-complete-in-steps'.
4170 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4171 :group 'org-completion
4172 :type 'boolean)
4174 (defcustom org-completion-fallback-command 'hippie-expand
4175 "The expansion command called by \\[pcomplete] in normal context.
4176 Normal means, no org-mode-specific context."
4177 :group 'org-completion
4178 :type 'function)
4180 ;;; Functions and variables from their packages
4181 ;; Declared here to avoid compiler warnings
4183 ;; XEmacs only
4184 (defvar outline-mode-menu-heading)
4185 (defvar outline-mode-menu-show)
4186 (defvar outline-mode-menu-hide)
4187 (defvar zmacs-regions) ; XEmacs regions
4189 ;; Emacs only
4190 (defvar mark-active)
4192 ;; Various packages
4193 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4194 (declare-function calendar-forward-day "cal-move" (arg))
4195 (declare-function calendar-goto-date "cal-move" (date))
4196 (declare-function calendar-goto-today "cal-move" ())
4197 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4198 (defvar calc-embedded-close-formula)
4199 (defvar calc-embedded-open-formula)
4200 (declare-function cdlatex-tab "ext:cdlatex" ())
4201 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4202 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4203 (defvar font-lock-unfontify-region-function)
4204 (declare-function iswitchb-read-buffer "iswitchb"
4205 (prompt &optional default require-match start matches-set))
4206 (defvar iswitchb-temp-buflist)
4207 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4208 (defvar org-agenda-tags-todo-honor-ignore-options)
4209 (declare-function org-agenda-skip "org-agenda" ())
4210 (declare-function
4211 org-agenda-format-item "org-agenda"
4212 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4213 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4214 (declare-function org-agenda-change-all-lines "org-agenda"
4215 (newhead hdmarker &optional fixface just-this))
4216 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4217 (declare-function org-agenda-maybe-redo "org-agenda" ())
4218 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4219 (beg end))
4220 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4221 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4222 "org-agenda" (&optional end))
4223 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4224 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4225 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4226 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4227 (declare-function org-indent-mode "org-indent" (&optional arg))
4228 (declare-function parse-time-string "parse-time" (string))
4229 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4230 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4231 (defvar remember-data-file)
4232 (defvar texmathp-why)
4233 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4234 (declare-function table--at-cell-p "table" (position &optional object at-column))
4236 (defvar org-latex-regexps)
4238 ;;; Autoload and prepare some org modules
4240 ;; Some table stuff that needs to be defined here, because it is used
4241 ;; by the functions setting up org-mode or checking for table context.
4243 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4244 "Detect an org-type or table-type table.")
4245 (defconst org-table-line-regexp "^[ \t]*|"
4246 "Detect an org-type table line.")
4247 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4248 "Detect an org-type table line.")
4249 (defconst org-table-hline-regexp "^[ \t]*|-"
4250 "Detect an org-type table hline.")
4251 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4252 "Detect a table-type table hline.")
4253 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4254 "Detect the first line outside a table when searching from within it.
4255 This works for both table types.")
4257 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
4258 "Detect a #+TBLFM line.")
4260 ;;;###autoload
4261 (defun turn-on-orgtbl ()
4262 "Unconditionally turn on `orgtbl-mode'."
4263 (require 'org-table)
4264 (orgtbl-mode 1))
4266 (defun org-at-table-p (&optional table-type)
4267 "Return t if the cursor is inside an org-type table.
4268 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4269 (if org-enable-table-editor
4270 (save-excursion
4271 (beginning-of-line 1)
4272 (looking-at (if table-type org-table-any-line-regexp
4273 org-table-line-regexp)))
4274 nil))
4275 (defsubst org-table-p () (org-at-table-p))
4277 (defun org-at-table.el-p ()
4278 "Return t if and only if we are at a table.el table."
4279 (and (org-at-table-p 'any)
4280 (save-excursion
4281 (goto-char (org-table-begin 'any))
4282 (looking-at org-table1-hline-regexp))))
4284 (defun org-table-recognize-table.el ()
4285 "If there is a table.el table nearby, recognize it and move into it."
4286 (if org-table-tab-recognizes-table.el
4287 (if (org-at-table.el-p)
4288 (progn
4289 (beginning-of-line 1)
4290 (if (looking-at org-table-dataline-regexp)
4292 (if (looking-at org-table1-hline-regexp)
4293 (progn
4294 (beginning-of-line 2)
4295 (if (looking-at org-table-any-border-regexp)
4296 (beginning-of-line -1)))))
4297 (if (re-search-forward "|" (org-table-end t) t)
4298 (progn
4299 (require 'table)
4300 (if (table--at-cell-p (point))
4302 (message "recognizing table.el table...")
4303 (table-recognize-table)
4304 (message "recognizing table.el table...done")))
4305 (error "This should not happen"))
4307 nil)
4308 nil))
4310 (defun org-at-table-hline-p ()
4311 "Return t if the cursor is inside a hline in a table."
4312 (if org-enable-table-editor
4313 (save-excursion
4314 (beginning-of-line 1)
4315 (looking-at org-table-hline-regexp))
4316 nil))
4318 (defun org-table-map-tables (function &optional quietly)
4319 "Apply FUNCTION to the start of all tables in the buffer."
4320 (save-excursion
4321 (save-restriction
4322 (widen)
4323 (goto-char (point-min))
4324 (while (re-search-forward org-table-any-line-regexp nil t)
4325 (unless quietly
4326 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4327 (beginning-of-line 1)
4328 (when (and (looking-at org-table-line-regexp)
4329 ;; Exclude tables in src/example/verbatim/clocktable blocks
4330 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4331 (save-excursion (funcall function))
4332 (or (looking-at org-table-line-regexp)
4333 (forward-char 1)))
4334 (re-search-forward org-table-any-border-regexp nil 1))))
4335 (unless quietly (message "Mapping tables: done")))
4337 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4338 (declare-function org-clock-update-mode-line "org-clock" ())
4339 (declare-function org-resolve-clocks "org-clock"
4340 (&optional also-non-dangling-p prompt last-valid))
4342 (defun org-at-TBLFM-p (&optional pos)
4343 "Return t when point (or POS) is in #+TBLFM line."
4344 (save-excursion
4345 (let ((pos pos)))
4346 (goto-char (or pos (point)))
4347 (beginning-of-line 1)
4348 (looking-at org-TBLFM-regexp)))
4350 (defvar org-clock-start-time)
4351 (defvar org-clock-marker (make-marker)
4352 "Marker recording the last clock-in.")
4353 (defvar org-clock-hd-marker (make-marker)
4354 "Marker recording the last clock-in, but the headline position.")
4355 (defvar org-clock-heading ""
4356 "The heading of the current clock entry.")
4357 (defun org-clock-is-active ()
4358 "Return the buffer where the clock is currently running.
4359 Return nil if no clock is running."
4360 (marker-buffer org-clock-marker))
4362 (defun org-check-running-clock ()
4363 "Check if the current buffer contains the running clock.
4364 If yes, offer to stop it and to save the buffer with the changes."
4365 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4366 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4367 (buffer-name))))
4368 (org-clock-out)
4369 (when (y-or-n-p "Save changed buffer?")
4370 (save-buffer))))
4372 (defun org-clocktable-try-shift (dir n)
4373 "Check if this line starts a clock table, if yes, shift the time block."
4374 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4375 (org-clocktable-shift dir n)))
4377 ;;;###autoload
4378 (defun org-clock-persistence-insinuate ()
4379 "Set up hooks for clock persistence."
4380 (require 'org-clock)
4381 (add-hook 'org-mode-hook 'org-clock-load)
4382 (add-hook 'kill-emacs-hook 'org-clock-save))
4384 ;; Define the variable already here, to make sure we have it.
4385 (defvar org-indent-mode nil
4386 "Non-nil if Org-Indent mode is enabled.
4387 Use the command `org-indent-mode' to change this variable.")
4389 ;; Autoload archiving code
4390 ;; The stuff that is needed for cycling and tags has to be defined here.
4392 (defgroup org-archive nil
4393 "Options concerning archiving in Org-mode."
4394 :tag "Org Archive"
4395 :group 'org-structure)
4397 (defcustom org-archive-location "%s_archive::"
4398 "The location where subtrees should be archived.
4400 The value of this variable is a string, consisting of two parts,
4401 separated by a double-colon. The first part is a filename and
4402 the second part is a headline.
4404 When the filename is omitted, archiving happens in the same file.
4405 %s in the filename will be replaced by the current file
4406 name (without the directory part). Archiving to a different file
4407 is useful to keep archived entries from contributing to the
4408 Org-mode Agenda.
4410 The archived entries will be filed as subtrees of the specified
4411 headline. When the headline is omitted, the subtrees are simply
4412 filed away at the end of the file, as top-level entries. Also in
4413 the heading you can use %s to represent the file name, this can be
4414 useful when using the same archive for a number of different files.
4416 Here are a few examples:
4417 \"%s_archive::\"
4418 If the current file is Projects.org, archive in file
4419 Projects.org_archive, as top-level trees. This is the default.
4421 \"::* Archived Tasks\"
4422 Archive in the current file, under the top-level headline
4423 \"* Archived Tasks\".
4425 \"~/org/archive.org::\"
4426 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4428 \"~/org/archive.org::* From %s\"
4429 Archive in file ~/org/archive.org (absolute path), under headlines
4430 \"From FILENAME\" where file name is the current file name.
4432 \"~/org/datetree.org::datetree/* Finished Tasks\"
4433 The \"datetree/\" string is special, signifying to archive
4434 items to the datetree. Items are placed in either the CLOSED
4435 date of the item, or the current date if there is no CLOSED date.
4436 The heading will be a subentry to the current date. There doesn't
4437 need to be a heading, but there always needs to be a slash after
4438 datetree. For example, to store archived items directly in the
4439 datetree, use \"~/org/datetree.org::datetree/\".
4441 \"basement::** Finished Tasks\"
4442 Archive in file ./basement (relative path), as level 3 trees
4443 below the level 2 heading \"** Finished Tasks\".
4445 You may set this option on a per-file basis by adding to the buffer a
4446 line like
4448 #+ARCHIVE: basement::** Finished Tasks
4450 You may also define it locally for a subtree by setting an ARCHIVE property
4451 in the entry. If such a property is found in an entry, or anywhere up
4452 the hierarchy, it will be used."
4453 :group 'org-archive
4454 :type 'string)
4456 (defcustom org-archive-tag "ARCHIVE"
4457 "The tag that marks a subtree as archived.
4458 An archived subtree does not open during visibility cycling, and does
4459 not contribute to the agenda listings.
4460 After changing this, font-lock must be restarted in the relevant buffers to
4461 get the proper fontification."
4462 :group 'org-archive
4463 :group 'org-keywords
4464 :type 'string)
4466 (defcustom org-agenda-skip-archived-trees t
4467 "Non-nil means the agenda will skip any items located in archived trees.
4468 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4469 variable is no longer recommended, you should leave it at the value t.
4470 Instead, use the key `v' to cycle the archives-mode in the agenda."
4471 :group 'org-archive
4472 :group 'org-agenda-skip
4473 :type 'boolean)
4475 (defcustom org-columns-skip-archived-trees t
4476 "Non-nil means ignore archived trees when creating column view."
4477 :group 'org-archive
4478 :group 'org-properties
4479 :type 'boolean)
4481 (defcustom org-cycle-open-archived-trees nil
4482 "Non-nil means `org-cycle' will open archived trees.
4483 An archived tree is a tree marked with the tag ARCHIVE.
4484 When nil, archived trees will stay folded. You can still open them with
4485 normal outline commands like `show-all', but not with the cycling commands."
4486 :group 'org-archive
4487 :group 'org-cycle
4488 :type 'boolean)
4490 (defcustom org-sparse-tree-open-archived-trees nil
4491 "Non-nil means sparse tree construction shows matches in archived trees.
4492 When nil, matches in these trees are highlighted, but the trees are kept in
4493 collapsed state."
4494 :group 'org-archive
4495 :group 'org-sparse-trees
4496 :type 'boolean)
4498 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4499 "The default date type when building a sparse tree.
4500 When this is nil, a date is a scheduled or a deadline timestamp.
4501 Otherwise, these types are allowed:
4503 all: all timestamps
4504 active: only active timestamps (<...>)
4505 inactive: only inactive timestamps (<...)
4506 scheduled: only scheduled timestamps
4507 deadline: only deadline timestamps"
4508 :type '(choice (const :tag "Scheduled or deadline" scheduled-or-deadline)
4509 (const :tag "All timestamps" all)
4510 (const :tag "Only active timestamps" active)
4511 (const :tag "Only inactive timestamps" inactive)
4512 (const :tag "Only scheduled timestamps" scheduled)
4513 (const :tag "Only deadline timestamps" deadline)
4514 (const :tag "Only closed timestamps" closed))
4515 :version "24.3"
4516 :group 'org-sparse-trees)
4518 (defun org-cycle-hide-archived-subtrees (state)
4519 "Re-hide all archived subtrees after a visibility state change."
4520 (when (and (not org-cycle-open-archived-trees)
4521 (not (memq state '(overview folded))))
4522 (save-excursion
4523 (let* ((globalp (memq state '(contents all)))
4524 (beg (if globalp (point-min) (point)))
4525 (end (if globalp (point-max) (org-end-of-subtree t))))
4526 (org-hide-archived-subtrees beg end)
4527 (goto-char beg)
4528 (if (looking-at (concat ".*:" org-archive-tag ":"))
4529 (message "%s" (substitute-command-keys
4530 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4532 (defun org-force-cycle-archived ()
4533 "Cycle subtree even if it is archived."
4534 (interactive)
4535 (setq this-command 'org-cycle)
4536 (let ((org-cycle-open-archived-trees t))
4537 (call-interactively 'org-cycle)))
4539 (defun org-hide-archived-subtrees (beg end)
4540 "Re-hide all archived subtrees after a visibility state change."
4541 (save-excursion
4542 (let* ((re (concat ":" org-archive-tag ":")))
4543 (goto-char beg)
4544 (while (re-search-forward re end t)
4545 (when (org-at-heading-p)
4546 (org-flag-subtree t)
4547 (org-end-of-subtree t))))))
4549 (declare-function outline-end-of-heading "outline" ())
4550 (declare-function outline-flag-region "outline" (from to flag))
4551 (defun org-flag-subtree (flag)
4552 (save-excursion
4553 (org-back-to-heading t)
4554 (outline-end-of-heading)
4555 (outline-flag-region (point)
4556 (progn (org-end-of-subtree t) (point))
4557 flag)))
4559 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4561 ;; Declare Column View Code
4563 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4564 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4565 (declare-function org-columns-compute "org-colview" (property))
4567 ;; Declare ID code
4569 (declare-function org-id-store-link "org-id")
4570 (declare-function org-id-locations-load "org-id")
4571 (declare-function org-id-locations-save "org-id")
4572 (defvar org-id-track-globally)
4574 ;;; Variables for pre-computed regular expressions, all buffer local
4576 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4577 "Matches first line of a hidden block.")
4578 (make-variable-buffer-local 'org-drawer-regexp)
4579 (defvar org-todo-regexp nil
4580 "Matches any of the TODO state keywords.")
4581 (make-variable-buffer-local 'org-todo-regexp)
4582 (defvar org-not-done-regexp nil
4583 "Matches any of the TODO state keywords except the last one.")
4584 (make-variable-buffer-local 'org-not-done-regexp)
4585 (defvar org-not-done-heading-regexp nil
4586 "Matches a TODO headline that is not done.")
4587 (make-variable-buffer-local 'org-not-done-regexp)
4588 (defvar org-todo-line-regexp nil
4589 "Matches a headline and puts TODO state into group 2 if present.")
4590 (make-variable-buffer-local 'org-todo-line-regexp)
4591 (defvar org-complex-heading-regexp nil
4592 "Matches a headline and puts everything into groups:
4593 group 1: the stars
4594 group 2: The todo keyword, maybe
4595 group 3: Priority cookie
4596 group 4: True headline
4597 group 5: Tags")
4598 (make-variable-buffer-local 'org-complex-heading-regexp)
4599 (defvar org-complex-heading-regexp-format nil
4600 "Printf format to make regexp to match an exact headline.
4601 This regexp will match the headline of any node which has the
4602 exact headline text that is put into the format, but may have any
4603 TODO state, priority and tags.")
4604 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4605 (defvar org-todo-line-tags-regexp nil
4606 "Matches a headline and puts TODO state into group 2 if present.
4607 Also put tags into group 4 if tags are present.")
4608 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4609 (defvar org-ds-keyword-length 12
4610 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4611 (make-variable-buffer-local 'org-ds-keyword-length)
4612 (defvar org-deadline-regexp nil
4613 "Matches the DEADLINE keyword.")
4614 (make-variable-buffer-local 'org-deadline-regexp)
4615 (defvar org-deadline-time-regexp nil
4616 "Matches the DEADLINE keyword together with a time stamp.")
4617 (make-variable-buffer-local 'org-deadline-time-regexp)
4618 (defvar org-deadline-time-hour-regexp nil
4619 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4620 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4621 (defvar org-deadline-line-regexp nil
4622 "Matches the DEADLINE keyword and the rest of the line.")
4623 (make-variable-buffer-local 'org-deadline-line-regexp)
4624 (defvar org-scheduled-regexp nil
4625 "Matches the SCHEDULED keyword.")
4626 (make-variable-buffer-local 'org-scheduled-regexp)
4627 (defvar org-scheduled-time-regexp nil
4628 "Matches the SCHEDULED keyword together with a time stamp.")
4629 (make-variable-buffer-local 'org-scheduled-time-regexp)
4630 (defvar org-scheduled-time-hour-regexp nil
4631 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4632 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4633 (defvar org-closed-time-regexp nil
4634 "Matches the CLOSED keyword together with a time stamp.")
4635 (make-variable-buffer-local 'org-closed-time-regexp)
4637 (defvar org-keyword-time-regexp nil
4638 "Matches any of the 4 keywords, together with the time stamp.")
4639 (make-variable-buffer-local 'org-keyword-time-regexp)
4640 (defvar org-keyword-time-not-clock-regexp nil
4641 "Matches any of the 3 keywords, together with the time stamp.")
4642 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4643 (defvar org-maybe-keyword-time-regexp nil
4644 "Matches a timestamp, possibly preceded by a keyword.")
4645 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4646 (defvar org-all-time-keywords nil
4647 "List of time keywords.")
4648 (make-variable-buffer-local 'org-all-time-keywords)
4650 (defconst org-plain-time-of-day-regexp
4651 (concat
4652 "\\(\\<[012]?[0-9]"
4653 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4654 "\\(--?"
4655 "\\(\\<[012]?[0-9]"
4656 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4657 "\\)?")
4658 "Regular expression to match a plain time or time range.
4659 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4660 groups carry important information:
4661 0 the full match
4662 1 the first time, range or not
4663 8 the second time, if it is a range.")
4665 (defconst org-plain-time-extension-regexp
4666 (concat
4667 "\\(\\<[012]?[0-9]"
4668 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4669 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4670 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4671 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4672 groups carry important information:
4673 0 the full match
4674 7 hours of duration
4675 9 minutes of duration")
4677 (defconst org-stamp-time-of-day-regexp
4678 (concat
4679 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4680 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4681 "\\(--?"
4682 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4683 "Regular expression to match a timestamp time or time range.
4684 After a match, the following groups carry important information:
4685 0 the full match
4686 1 date plus weekday, for back referencing to make sure both times are on the same day
4687 2 the first time, range or not
4688 4 the second time, if it is a range.")
4690 (defconst org-startup-options
4691 '(("fold" org-startup-folded t)
4692 ("overview" org-startup-folded t)
4693 ("nofold" org-startup-folded nil)
4694 ("showall" org-startup-folded nil)
4695 ("showeverything" org-startup-folded showeverything)
4696 ("content" org-startup-folded content)
4697 ("indent" org-startup-indented t)
4698 ("noindent" org-startup-indented nil)
4699 ("hidestars" org-hide-leading-stars t)
4700 ("showstars" org-hide-leading-stars nil)
4701 ("odd" org-odd-levels-only t)
4702 ("oddeven" org-odd-levels-only nil)
4703 ("align" org-startup-align-all-tables t)
4704 ("noalign" org-startup-align-all-tables nil)
4705 ("inlineimages" org-startup-with-inline-images t)
4706 ("noinlineimages" org-startup-with-inline-images nil)
4707 ("latexpreview" org-startup-with-latex-preview t)
4708 ("nolatexpreview" org-startup-with-latex-preview nil)
4709 ("customtime" org-display-custom-times t)
4710 ("logdone" org-log-done time)
4711 ("lognotedone" org-log-done note)
4712 ("nologdone" org-log-done nil)
4713 ("lognoteclock-out" org-log-note-clock-out t)
4714 ("nolognoteclock-out" org-log-note-clock-out nil)
4715 ("logrepeat" org-log-repeat state)
4716 ("lognoterepeat" org-log-repeat note)
4717 ("logdrawer" org-log-into-drawer t)
4718 ("nologdrawer" org-log-into-drawer nil)
4719 ("logstatesreversed" org-log-states-order-reversed t)
4720 ("nologstatesreversed" org-log-states-order-reversed nil)
4721 ("nologrepeat" org-log-repeat nil)
4722 ("logreschedule" org-log-reschedule time)
4723 ("lognotereschedule" org-log-reschedule note)
4724 ("nologreschedule" org-log-reschedule nil)
4725 ("logredeadline" org-log-redeadline time)
4726 ("lognoteredeadline" org-log-redeadline note)
4727 ("nologredeadline" org-log-redeadline nil)
4728 ("logrefile" org-log-refile time)
4729 ("lognoterefile" org-log-refile note)
4730 ("nologrefile" org-log-refile nil)
4731 ("fninline" org-footnote-define-inline t)
4732 ("nofninline" org-footnote-define-inline nil)
4733 ("fnlocal" org-footnote-section nil)
4734 ("fnauto" org-footnote-auto-label t)
4735 ("fnprompt" org-footnote-auto-label nil)
4736 ("fnconfirm" org-footnote-auto-label confirm)
4737 ("fnplain" org-footnote-auto-label plain)
4738 ("fnadjust" org-footnote-auto-adjust t)
4739 ("nofnadjust" org-footnote-auto-adjust nil)
4740 ("constcgs" constants-unit-system cgs)
4741 ("constSI" constants-unit-system SI)
4742 ("noptag" org-tag-persistent-alist nil)
4743 ("hideblocks" org-hide-block-startup t)
4744 ("nohideblocks" org-hide-block-startup nil)
4745 ("beamer" org-startup-with-beamer-mode t)
4746 ("entitiespretty" org-pretty-entities t)
4747 ("entitiesplain" org-pretty-entities nil))
4748 "Variable associated with STARTUP options for org-mode.
4749 Each element is a list of three items: the startup options (as written
4750 in the #+STARTUP line), the corresponding variable, and the value to set
4751 this variable to if the option is found. An optional forth element PUSH
4752 means to push this value onto the list in the variable.")
4754 (defun org-update-property-plist (key val props)
4755 "Update PROPS with KEY and VAL."
4756 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4757 (key (if appending (substring key 0 (- (length key) 1)) key))
4758 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4759 (previous (cdr (assoc key props))))
4760 (if appending
4761 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4762 (cons (cons key val) remainder))))
4764 (defconst org-block-regexp
4765 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4766 "Regular expression for hiding blocks.")
4767 (defconst org-heading-keyword-regexp-format
4768 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4769 "Printf format for a regexp matching a headline with some keyword.
4770 This regexp will match the headline of any node which has the
4771 exact keyword that is put into the format. The keyword isn't in
4772 any group by default, but the stars and the body are.")
4773 (defconst org-heading-keyword-maybe-regexp-format
4774 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4775 "Printf format for a regexp matching a headline, possibly with some keyword.
4776 This regexp can match any headline with the specified keyword, or
4777 without a keyword. The keyword isn't in any group by default,
4778 but the stars and the body are.")
4780 (defcustom org-group-tags t
4781 "When non-nil (the default), use group tags.
4782 This can be turned on/off through `org-toggle-tags-groups'."
4783 :group 'org-tags
4784 :group 'org-startup
4785 :type 'boolean)
4787 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4789 (defun org-toggle-tags-groups ()
4790 "Toggle support for group tags.
4791 Support for group tags is controlled by the option
4792 `org-group-tags', which is non-nil by default."
4793 (interactive)
4794 (setq org-group-tags (not org-group-tags))
4795 (cond ((and (derived-mode-p 'org-agenda-mode)
4796 org-group-tags)
4797 (org-agenda-redo))
4798 ((derived-mode-p 'org-mode)
4799 (let ((org-inhibit-startup t)) (org-mode))))
4800 (message "Groups tags support has been turned %s"
4801 (if org-group-tags "on" "off")))
4803 (defun org-set-regexps-and-options-for-tags ()
4804 "Precompute variables used for tags."
4805 (when (derived-mode-p 'org-mode)
4806 (org-set-local 'org-file-tags nil)
4807 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4808 (splitre "[ \t]+")
4809 (start 0)
4810 tags ftags key value)
4811 (save-excursion
4812 (save-restriction
4813 (widen)
4814 (goto-char (point-min))
4815 (while (re-search-forward re nil t)
4816 (setq key (upcase (org-match-string-no-properties 1))
4817 value (org-match-string-no-properties 2))
4818 (if (stringp value) (setq value (org-trim value)))
4819 (cond
4820 ((equal key "TAGS")
4821 (setq tags (append tags (if tags '("\\n") nil)
4822 (org-split-string value splitre))))
4823 ((equal key "FILETAGS")
4824 (when (string-match "\\S-" value)
4825 (setq ftags
4826 (append
4827 ftags
4828 (apply 'append
4829 (mapcar (lambda (x) (org-split-string x ":"))
4830 (org-split-string value)))))))))))
4831 ;; Process the file tags.
4832 (and ftags (org-set-local 'org-file-tags
4833 (mapcar 'org-add-prop-inherited ftags)))
4834 (org-set-local 'org-tag-groups-alist nil)
4835 ;; Process the tags.
4836 (when (and (not tags) org-tag-alist)
4837 (setq tags
4838 (mapcar
4839 (lambda (tg) (cond ((eq (car tg) :startgroup) "{")
4840 ((eq (car tg) :endgroup) "}")
4841 ((eq (car tg) :grouptags) ":")
4842 ((eq (car tg) :newline) "\n")
4843 (t (concat (car tg)
4844 (if (characterp (cdr tg))
4845 (format "(%s)" (char-to-string (cdr tg))) "")))))
4846 org-tag-alist)))
4847 (let (e tgs g)
4848 (while (setq e (pop tags))
4849 (cond
4850 ((equal e "{")
4851 (progn (push '(:startgroup) tgs)
4852 (when (equal (nth 1 tags) ":")
4853 (push (list (replace-regexp-in-string
4854 "(.+)$" "" (nth 0 tags)))
4855 org-tag-groups-alist)
4856 (setq g 0))))
4857 ((equal e ":") (push '(:grouptags) tgs))
4858 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4859 ((equal e "\\n") (push '(:newline) tgs))
4860 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4861 (push (cons (match-string 1 e)
4862 (string-to-char (match-string 2 e))) tgs)
4863 (if (and g (> g 0))
4864 (setcar org-tag-groups-alist
4865 (append (car org-tag-groups-alist)
4866 (list (match-string 1 e)))))
4867 (if g (setq g (1+ g))))
4868 (t (push (list e) tgs)
4869 (if (and g (> g 0))
4870 (setcar org-tag-groups-alist
4871 (append (car org-tag-groups-alist) (list e))))
4872 (if g (setq g (1+ g))))))
4873 (org-set-local 'org-tag-alist nil)
4874 (while (setq e (pop tgs))
4875 (or (and (stringp (car e))
4876 (assoc (car e) org-tag-alist))
4877 (push e org-tag-alist)))
4878 ;; Return a list with tag variables
4879 (list org-file-tags org-tag-alist org-tag-groups-alist)))))
4881 (defvar org-ota nil)
4882 (defun org-set-regexps-and-options ()
4883 "Precompute regular expressions used in the current buffer."
4884 (when (derived-mode-p 'org-mode)
4885 (org-set-local 'org-todo-kwd-alist nil)
4886 (org-set-local 'org-todo-key-alist nil)
4887 (org-set-local 'org-todo-key-trigger nil)
4888 (org-set-local 'org-todo-keywords-1 nil)
4889 (org-set-local 'org-done-keywords nil)
4890 (org-set-local 'org-todo-heads nil)
4891 (org-set-local 'org-todo-sets nil)
4892 (org-set-local 'org-todo-log-states nil)
4893 (org-set-local 'org-file-properties nil)
4894 (let ((re (org-make-options-regexp
4895 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
4896 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4897 "SETUPFILE" "OPTIONS")
4898 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4899 (splitre "[ \t]+")
4900 (scripts org-use-sub-superscripts)
4901 kwds kws0 kwsa key log value cat arch const links hw dws
4902 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
4903 (start 0))
4904 (save-excursion
4905 (save-restriction
4906 (widen)
4907 (goto-char (point-min))
4908 (while
4909 (or (and
4910 ext-setup-or-nil
4911 (not org-ota)
4912 (let (ret)
4913 (with-temp-buffer
4914 (insert ext-setup-or-nil)
4915 (let ((major-mode 'org-mode) org-ota)
4916 (setq ret (save-match-data
4917 (org-set-regexps-and-options-for-tags)))))
4918 ;; Append setupfile tags to existing tags
4919 (setq org-ota t)
4920 (setq org-file-tags
4921 (delq nil (append org-file-tags (nth 0 ret)))
4922 org-tag-alist
4923 (delq nil (append org-tag-alist (nth 1 ret)))
4924 org-tag-groups-alist
4925 (delq nil (append org-tag-groups-alist (nth 2 ret))))))
4926 (and ext-setup-or-nil
4927 (string-match re ext-setup-or-nil start)
4928 (setq start (match-end 0)))
4929 (and (setq ext-setup-or-nil nil start 0)
4930 (re-search-forward re nil t)))
4931 (setq key (upcase (match-string 1 ext-setup-or-nil))
4932 value (org-match-string-no-properties 2 ext-setup-or-nil))
4933 (if (stringp value) (setq value (org-trim value)))
4934 (cond
4935 ((equal key "CATEGORY")
4936 (setq cat value))
4937 ((member key '("SEQ_TODO" "TODO"))
4938 (push (cons 'sequence (org-split-string value splitre)) kwds))
4939 ((equal key "TYP_TODO")
4940 (push (cons 'type (org-split-string value splitre)) kwds))
4941 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4942 ;; general TODO-like setup
4943 (push (cons (intern (downcase (match-string 1 key)))
4944 (org-split-string value splitre)) kwds))
4945 ((equal key "COLUMNS")
4946 (org-set-local 'org-columns-default-format value))
4947 ((equal key "LINK")
4948 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4949 (push (cons (match-string 1 value)
4950 (org-trim (match-string 2 value)))
4951 links)))
4952 ((equal key "PRIORITIES")
4953 (setq prio (org-split-string value " +")))
4954 ((equal key "PROPERTY")
4955 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4956 (setq props (org-update-property-plist (match-string 1 value)
4957 (match-string 2 value)
4958 props))))
4959 ((equal key "DRAWERS")
4960 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4961 ((equal key "CONSTANTS")
4962 (org-table-set-constants))
4963 ((equal key "STARTUP")
4964 (let ((opts (org-split-string value splitre))
4965 l var val)
4966 (while (setq l (pop opts))
4967 (when (setq l (assoc l org-startup-options))
4968 (setq var (nth 1 l) val (nth 2 l))
4969 (if (not (nth 3 l))
4970 (set (make-local-variable var) val)
4971 (if (not (listp (symbol-value var)))
4972 (set (make-local-variable var) nil))
4973 (set (make-local-variable var) (symbol-value var))
4974 (add-to-list var val))))))
4975 ((equal key "ARCHIVE")
4976 (setq arch value)
4977 (remove-text-properties 0 (length arch)
4978 '(face t fontified t) arch))
4979 ((equal key "OPTIONS")
4980 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4981 (setq scripts (read (match-string 2 value)))))
4982 ((and (equal key "SETUPFILE")
4983 ;; Prevent checking in Gnus messages
4984 (not buffer-read-only))
4985 (setq setup-contents (org-file-contents
4986 (expand-file-name
4987 (org-remove-double-quotes value))
4988 'noerror))
4989 (if (not ext-setup-or-nil)
4990 (setq ext-setup-or-nil setup-contents start 0)
4991 (setq ext-setup-or-nil
4992 (concat (substring ext-setup-or-nil 0 start)
4993 "\n" setup-contents "\n"
4994 (substring ext-setup-or-nil start)))))))
4995 ;; search for property blocks
4996 (goto-char (point-min))
4997 (while (re-search-forward org-block-regexp nil t)
4998 (when (equal "PROPERTY" (upcase (match-string 1)))
4999 (setq value (replace-regexp-in-string
5000 "[\n\r]" " " (match-string 4)))
5001 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
5002 (setq props (org-update-property-plist (match-string 1 value)
5003 (match-string 2 value)
5004 props)))))))
5005 (org-set-local 'org-use-sub-superscripts scripts)
5006 (when cat
5007 (org-set-local 'org-category (intern cat))
5008 (push (cons "CATEGORY" cat) props))
5009 (when prio
5010 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
5011 (setq prio (mapcar 'string-to-char prio))
5012 (org-set-local 'org-highest-priority (nth 0 prio))
5013 (org-set-local 'org-lowest-priority (nth 1 prio))
5014 (org-set-local 'org-default-priority (nth 2 prio)))
5015 (and props (org-set-local 'org-file-properties (nreverse props)))
5016 (and drawers (org-set-local 'org-drawers drawers))
5017 (and arch (org-set-local 'org-archive-location arch))
5018 (and links (setq org-link-abbrev-alist-local (nreverse links)))
5019 ;; Process the TODO keywords
5020 (unless kwds
5021 ;; Use the global values as if they had been given locally.
5022 (setq kwds (default-value 'org-todo-keywords))
5023 (if (stringp (car kwds))
5024 (setq kwds (list (cons org-todo-interpretation
5025 (default-value 'org-todo-keywords)))))
5026 (setq kwds (reverse kwds)))
5027 (setq kwds (nreverse kwds))
5028 (let (inter kws kw)
5029 (while (setq kws (pop kwds))
5030 (let ((kws (or
5031 (run-hook-with-args-until-success
5032 'org-todo-setup-filter-hook kws)
5033 kws)))
5034 (setq inter (pop kws) sep (member "|" kws)
5035 kws0 (delete "|" (copy-sequence kws))
5036 kwsa nil
5037 kws1 (mapcar
5038 (lambda (x)
5039 ;; 1 2
5040 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
5041 (progn
5042 (setq kw (match-string 1 x)
5043 key (and (match-end 2) (match-string 2 x))
5044 log (org-extract-log-state-settings x))
5045 (push (cons kw (and key (string-to-char key))) kwsa)
5046 (and log (push log org-todo-log-states))
5048 (error "Invalid TODO keyword %s" x)))
5049 kws0)
5050 kwsa (if kwsa (append '((:startgroup))
5051 (nreverse kwsa)
5052 '((:endgroup))))
5053 hw (car kws1)
5054 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
5055 tail (list inter hw (car dws) (org-last dws))))
5056 (add-to-list 'org-todo-heads hw 'append)
5057 (push kws1 org-todo-sets)
5058 (setq org-done-keywords (append org-done-keywords dws nil))
5059 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
5060 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
5061 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
5062 (setq org-todo-sets (nreverse org-todo-sets)
5063 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5064 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
5065 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
5066 ;; Compute the regular expressions and other local variables.
5067 ;; Using `org-outline-regexp-bol' would complicate them much,
5068 ;; because of the fixed white space at the end of that string.
5069 (if (not org-done-keywords)
5070 (setq org-done-keywords (and org-todo-keywords-1
5071 (list (org-last org-todo-keywords-1)))))
5072 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5073 (length org-scheduled-string)
5074 (length org-clock-string)
5075 (length org-closed-string)))
5076 org-drawer-regexp
5077 (concat "^[ \t]*:\\("
5078 (mapconcat 'regexp-quote org-drawers "\\|")
5079 "\\):[ \t]*$")
5080 org-not-done-keywords
5081 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5082 org-todo-regexp
5083 (concat "\\("
5084 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5085 "\\)")
5086 org-not-done-regexp
5087 (concat "\\("
5088 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5089 "\\)")
5090 org-not-done-heading-regexp
5091 (format org-heading-keyword-regexp-format org-not-done-regexp)
5092 org-todo-line-regexp
5093 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5094 org-complex-heading-regexp
5095 (concat "^\\(\\*+\\)"
5096 "\\(?: +" org-todo-regexp "\\)?"
5097 "\\(?: +\\(\\[#.\\]\\)\\)?"
5098 "\\(?: +\\(.*?\\)\\)??"
5099 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5100 "[ \t]*$")
5101 org-complex-heading-regexp-format
5102 (concat "^\\(\\*+\\)"
5103 "\\(?: +" org-todo-regexp "\\)?"
5104 "\\(?: +\\(\\[#.\\]\\)\\)?"
5105 "\\(?: +"
5106 ;; Stats cookies can be stuck to body.
5107 "\\(?:\\[[0-9%%/]+\\] *\\)?"
5108 "\\(%s\\)"
5109 "\\(?: *\\[[0-9%%/]+\\]\\)?"
5110 "\\)"
5111 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5112 "[ \t]*$")
5113 org-todo-line-tags-regexp
5114 (concat "^\\(\\*+\\)"
5115 "\\(?: +" org-todo-regexp "\\)?"
5116 "\\(?: +\\(.*?\\)\\)??"
5117 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5118 "[ \t]*$")
5119 org-deadline-regexp (concat "\\<" org-deadline-string)
5120 org-deadline-time-regexp
5121 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5122 org-deadline-time-hour-regexp
5123 (concat "\\<" org-deadline-string
5124 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5125 org-deadline-line-regexp
5126 (concat "\\<\\(" org-deadline-string "\\).*")
5127 org-scheduled-regexp
5128 (concat "\\<" org-scheduled-string)
5129 org-scheduled-time-regexp
5130 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5131 org-scheduled-time-hour-regexp
5132 (concat "\\<" org-scheduled-string
5133 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5134 org-closed-time-regexp
5135 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5136 org-keyword-time-regexp
5137 (concat "\\<\\(" org-scheduled-string
5138 "\\|" org-deadline-string
5139 "\\|" org-closed-string
5140 "\\|" org-clock-string "\\)"
5141 " *[[<]\\([^]>]+\\)[]>]")
5142 org-keyword-time-not-clock-regexp
5143 (concat "\\<\\(" org-scheduled-string
5144 "\\|" org-deadline-string
5145 "\\|" org-closed-string
5146 "\\)"
5147 " *[[<]\\([^]>]+\\)[]>]")
5148 org-maybe-keyword-time-regexp
5149 (concat "\\(\\<\\(" org-scheduled-string
5150 "\\|" org-deadline-string
5151 "\\|" org-closed-string
5152 "\\|" org-clock-string "\\)\\)?"
5153 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5154 org-all-time-keywords
5155 (mapcar (lambda (w) (substring w 0 -1))
5156 (list org-scheduled-string org-deadline-string
5157 org-clock-string org-closed-string)))
5158 (setq org-ota nil)
5159 (org-compute-latex-and-related-regexp))))
5161 (defun org-file-contents (file &optional noerror)
5162 "Return the contents of FILE, as a string."
5163 (if (or (not file)
5164 (not (file-readable-p file)))
5165 (if noerror
5166 (message "Cannot read file \"%s\"" file)
5167 (error "Cannot read file \"%s\"" file))
5168 (with-temp-buffer
5169 (insert-file-contents file)
5170 (buffer-string))))
5172 (defun org-extract-log-state-settings (x)
5173 "Extract the log state setting from a TODO keyword string.
5174 This will extract info from a string like \"WAIT(w@/!)\"."
5175 (let (kw key log1 log2)
5176 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5177 (setq kw (match-string 1 x)
5178 key (and (match-end 2) (match-string 2 x))
5179 log1 (and (match-end 3) (match-string 3 x))
5180 log2 (and (match-end 4) (match-string 4 x)))
5181 (and (or log1 log2)
5182 (list kw
5183 (and log1 (if (equal log1 "!") 'time 'note))
5184 (and log2 (if (equal log2 "!") 'time 'note)))))))
5186 (defun org-remove-keyword-keys (list)
5187 "Remove a pair of parenthesis at the end of each string in LIST."
5188 (mapcar (lambda (x)
5189 (if (string-match "(.*)$" x)
5190 (substring x 0 (match-beginning 0))
5192 list))
5194 (defun org-assign-fast-keys (alist)
5195 "Assign fast keys to a keyword-key alist.
5196 Respect keys that are already there."
5197 (let (new e (alt ?0))
5198 (while (setq e (pop alist))
5199 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5200 (cdr e)) ;; Key already assigned.
5201 (push e new)
5202 (let ((clist (string-to-list (downcase (car e))))
5203 (used (append new alist)))
5204 (when (= (car clist) ?@)
5205 (pop clist))
5206 (while (and clist (rassoc (car clist) used))
5207 (pop clist))
5208 (unless clist
5209 (while (rassoc alt used)
5210 (incf alt)))
5211 (push (cons (car e) (or (car clist) alt)) new))))
5212 (nreverse new)))
5214 ;;; Some variables used in various places
5216 (defvar org-window-configuration nil
5217 "Used in various places to store a window configuration.")
5218 (defvar org-selected-window nil
5219 "Used in various places to store a window configuration.")
5220 (defvar org-finish-function nil
5221 "Function to be called when `C-c C-c' is used.
5222 This is for getting out of special buffers like capture.")
5225 ;; FIXME: Occasionally check by commenting these, to make sure
5226 ;; no other functions uses these, forgetting to let-bind them.
5227 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5228 (defvar org-last-state)
5229 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5231 ;; Defined somewhere in this file, but used before definition.
5232 (defvar org-entities) ;; defined in org-entities.el
5233 (defvar org-struct-menu)
5234 (defvar org-org-menu)
5235 (defvar org-tbl-menu)
5237 ;;;; Define the Org-mode
5239 ;; We use a before-change function to check if a table might need
5240 ;; an update.
5241 (defvar org-table-may-need-update t
5242 "Indicates that a table might need an update.
5243 This variable is set by `org-before-change-function'.
5244 `org-table-align' sets it back to nil.")
5245 (defun org-before-change-function (beg end)
5246 "Every change indicates that a table might need an update."
5247 (setq org-table-may-need-update t))
5248 (defvar org-mode-map)
5249 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5250 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5251 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5252 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5253 (defvar org-table-buffer-is-an nil)
5255 (defvar bidi-paragraph-direction)
5256 (defvar buffer-face-mode-face)
5258 (require 'outline)
5259 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5260 (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"))
5261 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5263 ;; Other stuff we need.
5264 (require 'time-date)
5265 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5266 (require 'easymenu)
5267 (require 'overlay)
5269 ;; (require 'org-macs) moved higher up in the file before it is first used
5270 (require 'org-entities)
5271 ;; (require 'org-compat) moved higher up in the file before it is first used
5272 (require 'org-faces)
5273 (require 'org-list)
5274 (require 'org-pcomplete)
5275 (require 'org-src)
5276 (require 'org-footnote)
5277 (require 'org-macro)
5279 ;; babel
5280 (require 'ob)
5282 ;;;###autoload
5283 (define-derived-mode org-mode outline-mode "Org"
5284 "Outline-based notes management and organizer, alias
5285 \"Carsten's outline-mode for keeping track of everything.\"
5287 Org-mode develops organizational tasks around a NOTES file which
5288 contains information about projects as plain text. Org-mode is
5289 implemented on top of outline-mode, which is ideal to keep the content
5290 of large files well structured. It supports ToDo items, deadlines and
5291 time stamps, which magically appear in the diary listing of the Emacs
5292 calendar. Tables are easily created with a built-in table editor.
5293 Plain text URL-like links connect to websites, emails (VM), Usenet
5294 messages (Gnus), BBDB entries, and any files related to the project.
5295 For printing and sharing of notes, an Org-mode file (or a part of it)
5296 can be exported as a structured ASCII or HTML file.
5298 The following commands are available:
5300 \\{org-mode-map}"
5302 ;; Get rid of Outline menus, they are not needed
5303 ;; Need to do this here because define-derived-mode sets up
5304 ;; the keymap so late. Still, it is a waste to call this each time
5305 ;; we switch another buffer into org-mode.
5306 (if (featurep 'xemacs)
5307 (when (boundp 'outline-mode-menu-heading)
5308 ;; Assume this is Greg's port, it uses easymenu
5309 (easy-menu-remove outline-mode-menu-heading)
5310 (easy-menu-remove outline-mode-menu-show)
5311 (easy-menu-remove outline-mode-menu-hide))
5312 (define-key org-mode-map [menu-bar headings] 'undefined)
5313 (define-key org-mode-map [menu-bar hide] 'undefined)
5314 (define-key org-mode-map [menu-bar show] 'undefined))
5316 (org-load-modules-maybe)
5317 (easy-menu-add org-org-menu)
5318 (easy-menu-add org-tbl-menu)
5319 (org-install-agenda-files-menu)
5320 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5321 (add-to-invisibility-spec '(org-cwidth))
5322 (add-to-invisibility-spec '(org-hide-block . t))
5323 (when (featurep 'xemacs)
5324 (org-set-local 'line-move-ignore-invisible t))
5325 (org-set-local 'outline-regexp org-outline-regexp)
5326 (org-set-local 'outline-level 'org-outline-level)
5327 (setq bidi-paragraph-direction 'left-to-right)
5328 (when (and org-ellipsis
5329 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5330 (fboundp 'make-glyph-code))
5331 (unless org-display-table
5332 (setq org-display-table (make-display-table)))
5333 (set-display-table-slot
5334 org-display-table 4
5335 (vconcat (mapcar
5336 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5337 org-ellipsis)))
5338 (if (stringp org-ellipsis) org-ellipsis "..."))))
5339 (setq buffer-display-table org-display-table))
5340 (org-set-regexps-and-options-for-tags)
5341 (org-set-regexps-and-options)
5342 (org-set-font-lock-defaults)
5343 (when (and org-tag-faces (not org-tags-special-faces-re))
5344 ;; tag faces set outside customize.... force initialization.
5345 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5346 ;; Calc embedded
5347 (org-set-local 'calc-embedded-open-mode "# ")
5348 ;; Modify a few syntax entries
5349 (modify-syntax-entry ?@ "w")
5350 (modify-syntax-entry ?\" "\"")
5351 (if org-startup-truncated (setq truncate-lines t))
5352 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5353 (org-set-local 'font-lock-unfontify-region-function
5354 'org-unfontify-region)
5355 ;; Activate before-change-function
5356 (org-set-local 'org-table-may-need-update t)
5357 (org-add-hook 'before-change-functions 'org-before-change-function nil
5358 'local)
5359 ;; Check for running clock before killing a buffer
5360 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5361 ;; Initialize macros templates.
5362 (org-macro-initialize-templates)
5363 ;; Initialize radio targets.
5364 (org-update-radio-target-regexp)
5365 ;; Indentation.
5366 (org-set-local 'indent-line-function 'org-indent-line)
5367 (org-set-local 'indent-region-function 'org-indent-region)
5368 ;; Filling and auto-filling.
5369 (org-setup-filling)
5370 ;; Comments.
5371 (org-setup-comments-handling)
5372 ;; Beginning/end of defun
5373 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5374 (org-set-local 'end-of-defun-function 'org-forward-element)
5375 ;; Next error for sparse trees
5376 (org-set-local 'next-error-function 'org-occur-next-match)
5377 ;; Make sure dependence stuff works reliably, even for users who set it
5378 ;; too late :-(
5379 (if org-enforce-todo-dependencies
5380 (add-hook 'org-blocker-hook
5381 'org-block-todo-from-children-or-siblings-or-parent)
5382 (remove-hook 'org-blocker-hook
5383 'org-block-todo-from-children-or-siblings-or-parent))
5384 (if org-enforce-todo-checkbox-dependencies
5385 (add-hook 'org-blocker-hook
5386 'org-block-todo-from-checkboxes)
5387 (remove-hook 'org-blocker-hook
5388 'org-block-todo-from-checkboxes))
5390 ;; Align options lines
5391 (org-set-local
5392 'align-mode-rules-list
5393 '((org-in-buffer-settings
5394 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5395 (modes . '(org-mode)))))
5397 ;; Imenu
5398 (org-set-local 'imenu-create-index-function
5399 'org-imenu-get-tree)
5401 ;; Make isearch reveal context
5402 (if (or (featurep 'xemacs)
5403 (not (boundp 'outline-isearch-open-invisible-function)))
5404 ;; Emacs 21 and XEmacs make use of the hook
5405 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5406 ;; Emacs 22 deals with this through a special variable
5407 (org-set-local 'outline-isearch-open-invisible-function
5408 (lambda (&rest ignore) (org-show-context 'isearch)))
5409 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5411 ;; Setup the pcomplete hooks
5412 (set (make-local-variable 'pcomplete-command-completion-function)
5413 'org-pcomplete-initial)
5414 (set (make-local-variable 'pcomplete-command-name-function)
5415 'org-command-at-point)
5416 (set (make-local-variable 'pcomplete-default-completion-function)
5417 'ignore)
5418 (set (make-local-variable 'pcomplete-parse-arguments-function)
5419 'org-parse-arguments)
5420 (set (make-local-variable 'pcomplete-termination-string) "")
5421 (when (>= emacs-major-version 23)
5422 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5424 ;; If empty file that did not turn on org-mode automatically, make it to.
5425 (if (and org-insert-mode-line-in-empty-file
5426 (org-called-interactively-p 'any)
5427 (= (point-min) (point-max)))
5428 (insert "# -*- mode: org -*-\n\n"))
5429 (unless org-inhibit-startup
5430 (org-unmodified
5431 (and org-startup-with-beamer-mode (org-beamer-mode))
5432 (when org-startup-align-all-tables
5433 (org-table-map-tables 'org-table-align 'quietly))
5434 (when org-startup-with-inline-images
5435 (org-display-inline-images))
5436 (when org-startup-with-latex-preview
5437 (org-preview-latex-fragment))
5438 (unless org-inhibit-startup-visibility-stuff
5439 (org-set-startup-visibility))))
5440 ;; Try to set org-hide correctly
5441 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5443 ;; Update `customize-package-emacs-version-alist'
5444 (add-to-list 'customize-package-emacs-version-alist
5445 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5446 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5447 ("8.0" . "24.4")))
5449 (defvar org-mode-transpose-word-syntax-table
5450 (let ((st (make-syntax-table)))
5451 (mapc (lambda(c) (modify-syntax-entry
5452 (string-to-char (car c)) "w p" st))
5453 org-emphasis-alist)
5454 st))
5456 (when (fboundp 'abbrev-table-put)
5457 (abbrev-table-put org-mode-abbrev-table
5458 :parents (list text-mode-abbrev-table)))
5460 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5462 (defsubst org-fix-ellipsis-at-bol ()
5463 (save-excursion (goto-char (window-start)) (recenter 0)))
5465 (defun org-find-invisible-foreground ()
5466 (let ((candidates (remove
5467 "unspecified-bg"
5468 (nconc
5469 (list (face-background 'default)
5470 (face-background 'org-default))
5471 (mapcar
5472 (lambda (alist)
5473 (when (boundp alist)
5474 (cdr (assoc 'background-color (symbol-value alist)))))
5475 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5476 (list (face-foreground 'org-hide))))))
5477 (car (remove nil candidates))))
5479 (defun org-current-time (&optional rounding-minutes past)
5480 "Current time, possibly rounded to ROUNDING-MINUTES.
5481 When ROUNDING-MINUTES is not an integer, fall back on the car of
5482 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5483 the rounding returns a past time."
5484 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5485 (car org-time-stamp-rounding-minutes)))
5486 (time (decode-time)) res)
5487 (if (< r 1)
5488 (current-time)
5489 (setq res
5490 (apply 'encode-time
5491 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5492 (nthcdr 2 time))))
5493 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5494 (seconds-to-time (- (org-float-time res) (* r 60)))
5495 res))))
5497 (defun org-today ()
5498 "Return today date, considering `org-extend-today-until'."
5499 (time-to-days
5500 (time-subtract (current-time)
5501 (list 0 (* 3600 org-extend-today-until) 0))))
5503 ;;;; Font-Lock stuff, including the activators
5505 (defvar org-mouse-map (make-sparse-keymap))
5506 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5507 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5508 (when org-mouse-1-follows-link
5509 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5510 (when org-tab-follows-link
5511 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5512 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5514 (require 'font-lock)
5516 (defconst org-non-link-chars "]\t\n\r<>")
5517 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5518 "shell" "elisp" "doi" "message"))
5519 (defvar org-link-types-re nil
5520 "Matches a link that has a url-like prefix like \"http:\"")
5521 (defvar org-link-re-with-space nil
5522 "Matches a link with spaces, optional angular brackets around it.")
5523 (defvar org-link-re-with-space2 nil
5524 "Matches a link with spaces, optional angular brackets around it.")
5525 (defvar org-link-re-with-space3 nil
5526 "Matches a link with spaces, only for internal part in bracket links.")
5527 (defvar org-angle-link-re nil
5528 "Matches link with angular brackets, spaces are allowed.")
5529 (defvar org-plain-link-re nil
5530 "Matches plain link, without spaces.")
5531 (defvar org-bracket-link-regexp nil
5532 "Matches a link in double brackets.")
5533 (defvar org-bracket-link-analytic-regexp nil
5534 "Regular expression used to analyze links.
5535 Here is what the match groups contain after a match:
5536 1: http:
5537 2: http
5538 3: path
5539 4: [desc]
5540 5: desc")
5541 (defvar org-bracket-link-analytic-regexp++ nil
5542 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5543 (defvar org-any-link-re nil
5544 "Regular expression matching any link.")
5546 (defconst org-match-sexp-depth 3
5547 "Number of stacked braces for sub/superscript matching.")
5549 (defun org-create-multibrace-regexp (left right n)
5550 "Create a regular expression which will match a balanced sexp.
5551 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5552 as single character strings.
5553 The regexp returned will match the entire expression including the
5554 delimiters. It will also define a single group which contains the
5555 match except for the outermost delimiters. The maximum depth of
5556 stacked delimiters is N. Escaping delimiters is not possible."
5557 (let* ((nothing (concat "[^" left right "]*?"))
5558 (or "\\|")
5559 (re nothing)
5560 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5561 (while (> n 1)
5562 (setq n (1- n)
5563 re (concat re or next)
5564 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5565 (concat left "\\(" re "\\)" right)))
5567 (defvar org-match-substring-regexp
5568 (concat
5569 "\\(\\S-\\)\\([_^]\\)\\("
5570 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5571 "\\|"
5572 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5573 "\\|"
5574 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5575 "The regular expression matching a sub- or superscript.")
5577 (defvar org-match-substring-with-braces-regexp
5578 (concat
5579 "\\(\\S-\\)\\([_^]\\)\\("
5580 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5581 "\\)")
5582 "The regular expression matching a sub- or superscript, forcing braces.")
5584 (defun org-make-link-regexps ()
5585 "Update the link regular expressions.
5586 This should be called after the variable `org-link-types' has changed."
5587 (setq org-link-types-re
5588 (concat
5589 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5590 org-link-re-with-space
5591 (concat
5592 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5593 "\\([^" org-non-link-chars " ]"
5594 "[^" org-non-link-chars "]*"
5595 "[^" org-non-link-chars " ]\\)>?")
5596 org-link-re-with-space2
5597 (concat
5598 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5599 "\\([^" org-non-link-chars " ]"
5600 "[^\t\n\r]*"
5601 "[^" org-non-link-chars " ]\\)>?")
5602 org-link-re-with-space3
5603 (concat
5604 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5605 "\\([^" org-non-link-chars " ]"
5606 "[^\t\n\r]*\\)")
5607 org-angle-link-re
5608 (concat
5609 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5610 "\\([^" org-non-link-chars " ]"
5611 "[^" org-non-link-chars "]*"
5612 "\\)>")
5613 org-plain-link-re
5614 (concat
5615 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5616 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5617 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5618 org-bracket-link-regexp
5619 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5620 org-bracket-link-analytic-regexp
5621 (concat
5622 "\\[\\["
5623 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5624 "\\([^]]+\\)"
5625 "\\]"
5626 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5627 "\\]")
5628 org-bracket-link-analytic-regexp++
5629 (concat
5630 "\\[\\["
5631 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5632 "\\([^]]+\\)"
5633 "\\]"
5634 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5635 "\\]")
5636 org-any-link-re
5637 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5638 org-angle-link-re "\\)\\|\\("
5639 org-plain-link-re "\\)")))
5641 (org-make-link-regexps)
5643 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5644 "Regular expression for fast time stamp matching.")
5645 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5646 "Regular expression for fast time stamp matching.")
5647 (defconst org-ts-regexp0
5648 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5649 "Regular expression matching time strings for analysis.
5650 This one does not require the space after the date, so it can be used
5651 on a string that terminates immediately after the date.")
5652 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5653 "Regular expression matching time strings for analysis.")
5654 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5655 "Regular expression matching time stamps, with groups.")
5656 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5657 "Regular expression matching time stamps (also [..]), with groups.")
5658 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5659 "Regular expression matching a time stamp range.")
5660 (defconst org-tr-regexp-both
5661 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5662 "Regular expression matching a time stamp range.")
5663 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5664 org-ts-regexp "\\)?")
5665 "Regular expression matching a time stamp or time stamp range.")
5666 (defconst org-tsr-regexp-both
5667 (concat org-ts-regexp-both "\\(--?-?"
5668 org-ts-regexp-both "\\)?")
5669 "Regular expression matching a time stamp or time stamp range.
5670 The time stamps may be either active or inactive.")
5672 (defvar org-emph-face nil)
5674 (defun org-do-emphasis-faces (limit)
5675 "Run through the buffer and add overlays to emphasized strings."
5676 (let (rtn a)
5677 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5678 (if (not (= (char-after (match-beginning 3))
5679 (char-after (match-beginning 4))))
5680 (progn
5681 (setq rtn t)
5682 (setq a (assoc (match-string 3) org-emphasis-alist))
5683 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5684 'face
5685 (nth 1 a))
5686 (and (nth 2 a)
5687 (org-remove-flyspell-overlays-in
5688 (match-beginning 0) (match-end 0)))
5689 (add-text-properties (match-beginning 2) (match-end 2)
5690 '(font-lock-multiline t org-emphasis t))
5691 (when org-hide-emphasis-markers
5692 (add-text-properties (match-end 4) (match-beginning 5)
5693 '(invisible org-link))
5694 (add-text-properties (match-beginning 3) (match-end 3)
5695 '(invisible org-link)))))
5696 (backward-char 1))
5697 rtn))
5699 (defun org-emphasize (&optional char)
5700 "Insert or change an emphasis, i.e. a font like bold or italic.
5701 If there is an active region, change that region to a new emphasis.
5702 If there is no region, just insert the marker characters and position
5703 the cursor between them.
5704 CHAR should be the marker character. If it is a space, it means to
5705 remove the emphasis of the selected region.
5706 If CHAR is not given (for example in an interactive call) it will be
5707 prompted for."
5708 (interactive)
5709 (let ((erc org-emphasis-regexp-components)
5710 (prompt "")
5711 (string "") beg end move c s)
5712 (if (org-region-active-p)
5713 (setq beg (region-beginning) end (region-end)
5714 string (buffer-substring beg end))
5715 (setq move t))
5717 (unless char
5718 (message "Emphasis marker or tag: [%s]"
5719 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5720 (setq char (read-char-exclusive)))
5721 (if (equal char ?\ )
5722 (setq s "" move nil)
5723 (unless (assoc (char-to-string char) org-emphasis-alist)
5724 (user-error "No such emphasis marker: \"%c\"" char))
5725 (setq s (char-to-string char)))
5726 (while (and (> (length string) 1)
5727 (equal (substring string 0 1) (substring string -1))
5728 (assoc (substring string 0 1) org-emphasis-alist))
5729 (setq string (substring string 1 -1)))
5730 (setq string (concat s string s))
5731 (if beg (delete-region beg end))
5732 (unless (or (bolp)
5733 (string-match (concat "[" (nth 0 erc) "\n]")
5734 (char-to-string (char-before (point)))))
5735 (insert " "))
5736 (unless (or (eobp)
5737 (string-match (concat "[" (nth 1 erc) "\n]")
5738 (char-to-string (char-after (point)))))
5739 (insert " ") (backward-char 1))
5740 (insert string)
5741 (and move (backward-char 1))))
5743 (defconst org-nonsticky-props
5744 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5746 (defsubst org-rear-nonsticky-at (pos)
5747 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5749 (defun org-activate-plain-links (limit)
5750 "Run through the buffer and add overlays to links."
5751 (let (f hl)
5752 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5753 (not (org-in-src-block-p)))
5754 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5755 (setq f (get-text-property (match-beginning 0) 'face))
5756 (setq hl (org-match-string-no-properties 0))
5757 (if (or (eq f 'org-tag)
5758 (and (listp f) (memq 'org-tag f)))
5760 (add-text-properties (match-beginning 0) (match-end 0)
5761 (list 'mouse-face 'highlight
5762 'face 'org-link
5763 'htmlize-link `(:uri ,hl)
5764 'keymap org-mouse-map))
5765 (org-rear-nonsticky-at (match-end 0)))
5766 t)))
5768 (defun org-activate-code (limit)
5769 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5770 (progn
5771 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5772 (remove-text-properties (match-beginning 0) (match-end 0)
5773 '(display t invisible t intangible t))
5774 t)))
5776 (defcustom org-src-fontify-natively nil
5777 "When non-nil, fontify code in code blocks."
5778 :type 'boolean
5779 :version "24.1"
5780 :group 'org-appearance
5781 :group 'org-babel)
5783 (defcustom org-allow-promoting-top-level-subtree nil
5784 "When non-nil, allow promoting a top level subtree.
5785 The leading star of the top level headline will be replaced
5786 by a #."
5787 :type 'boolean
5788 :version "24.1"
5789 :group 'org-appearance)
5791 (defun org-fontify-meta-lines-and-blocks (limit)
5792 (condition-case nil
5793 (org-fontify-meta-lines-and-blocks-1 limit)
5794 (error (message "org-mode fontification error"))))
5796 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5797 "Fontify #+ lines and blocks."
5798 (let ((case-fold-search t))
5799 (if (re-search-forward
5800 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5801 limit t)
5802 (let ((beg (match-beginning 0))
5803 (block-start (match-end 0))
5804 (block-end nil)
5805 (lang (match-string 7))
5806 (beg1 (line-beginning-position 2))
5807 (dc1 (downcase (match-string 2)))
5808 (dc3 (downcase (match-string 3)))
5809 end end1 quoting block-type ovl)
5810 (cond
5811 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5812 ;; a single line of backend-specific content
5813 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5814 (remove-text-properties (match-beginning 0) (match-end 0)
5815 '(display t invisible t intangible t))
5816 (add-text-properties (match-beginning 1) (match-end 3)
5817 '(font-lock-fontified t face org-meta-line))
5818 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5819 '(font-lock-fontified t face org-block))
5820 ; for backend-specific code
5822 ((and (match-end 4) (equal dc3 "+begin"))
5823 ;; Truly a block
5824 (setq block-type (downcase (match-string 5))
5825 quoting (member block-type org-protecting-blocks))
5826 (when (re-search-forward
5827 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5828 nil t) ;; on purpose, we look further than LIMIT
5829 (setq end (min (point-max) (match-end 0))
5830 end1 (min (point-max) (1- (match-beginning 0))))
5831 (setq block-end (match-beginning 0))
5832 (when quoting
5833 (remove-text-properties beg end
5834 '(display t invisible t intangible t)))
5835 (add-text-properties
5836 beg end
5837 '(font-lock-fontified t font-lock-multiline t))
5838 (add-text-properties beg beg1 '(face org-meta-line))
5839 (add-text-properties end1 (min (point-max) (1+ end))
5840 '(face org-meta-line)) ; for end_src
5841 (cond
5842 ((and lang (not (string= lang "")) org-src-fontify-natively)
5843 (org-src-font-lock-fontify-block lang block-start block-end)
5844 ;; remove old background overlays
5845 (mapc (lambda (ov)
5846 (if (eq (overlay-get ov 'face) 'org-block-background)
5847 (delete-overlay ov)))
5848 (overlays-at (/ (+ beg1 block-end) 2)))
5849 ;; add a background overlay
5850 (setq ovl (make-overlay beg1 block-end))
5851 (overlay-put ovl 'face 'org-block-background)
5852 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5853 (quoting
5854 (add-text-properties beg1 (min (point-max) (1+ end1))
5855 '(face org-block))) ; end of source block
5856 ((not org-fontify-quote-and-verse-blocks))
5857 ((string= block-type "quote")
5858 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5859 ((string= block-type "verse")
5860 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5861 (add-text-properties beg beg1 '(face org-block-begin-line))
5862 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5863 '(face org-block-end-line))
5865 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5866 (add-text-properties
5867 beg (match-end 3)
5868 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5869 '(font-lock-fontified t invisible t)
5870 '(font-lock-fontified t face org-document-info-keyword)))
5871 (add-text-properties
5872 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5873 (if (string-equal dc1 "+title:")
5874 '(font-lock-fontified t face org-document-title)
5875 '(font-lock-fontified t face org-document-info))))
5876 ((or (equal dc1 "+results")
5877 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5878 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5879 "+call:" "+header:" "+headers:" "+name:"))
5880 (and (match-end 4) (equal dc3 "+attr")))
5881 (add-text-properties
5882 beg (match-end 0)
5883 '(font-lock-fontified t face org-meta-line))
5885 ((member dc3 '(" " ""))
5886 (add-text-properties
5887 beg (match-end 0)
5888 '(font-lock-fontified t face font-lock-comment-face)))
5889 ((not (member (char-after beg) '(?\ ?\t)))
5890 ;; just any other in-buffer setting, but not indented
5891 (add-text-properties
5892 beg (match-end 0)
5893 '(font-lock-fontified t face org-meta-line))
5895 (t nil))))))
5897 (defun org-activate-angle-links (limit)
5898 "Run through the buffer and add overlays to links."
5899 (if (and (re-search-forward org-angle-link-re limit t)
5900 (not (org-in-src-block-p)))
5901 (progn
5902 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5903 (add-text-properties (match-beginning 0) (match-end 0)
5904 (list 'mouse-face 'highlight
5905 'keymap org-mouse-map))
5906 (org-rear-nonsticky-at (match-end 0))
5907 t)))
5909 (defun org-activate-footnote-links (limit)
5910 "Run through the buffer and add overlays to footnotes."
5911 (let ((fn (org-footnote-next-reference-or-definition limit)))
5912 (when fn
5913 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5914 (org-remove-flyspell-overlays-in beg end)
5915 (add-text-properties beg end
5916 (list 'mouse-face 'highlight
5917 'keymap org-mouse-map
5918 'help-echo
5919 (if (= (point-at-bol) beg)
5920 "Footnote definition"
5921 "Footnote reference")
5922 'font-lock-fontified t
5923 'font-lock-multiline t
5924 'face 'org-footnote))))))
5926 (defun org-activate-bracket-links (limit)
5927 "Run through the buffer and add overlays to bracketed links."
5928 (if (and (re-search-forward org-bracket-link-regexp limit t)
5929 (not (org-in-src-block-p)))
5930 (let* ((hl (org-match-string-no-properties 1))
5931 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
5932 (ip (org-maybe-intangible
5933 (list 'invisible 'org-link
5934 'keymap org-mouse-map 'mouse-face 'highlight
5935 'font-lock-multiline t 'help-echo help
5936 'htmlize-link `(:uri ,hl))))
5937 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5938 'font-lock-multiline t 'help-echo help
5939 'htmlize-link `(:uri ,hl))))
5940 ;; We need to remove the invisible property here. Table narrowing
5941 ;; may have made some of this invisible.
5942 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5943 (remove-text-properties (match-beginning 0) (match-end 0)
5944 '(invisible nil))
5945 (if (match-end 3)
5946 (progn
5947 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5948 (org-rear-nonsticky-at (match-beginning 3))
5949 (add-text-properties (match-beginning 3) (match-end 3) vp)
5950 (org-rear-nonsticky-at (match-end 3))
5951 (add-text-properties (match-end 3) (match-end 0) ip)
5952 (org-rear-nonsticky-at (match-end 0)))
5953 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5954 (org-rear-nonsticky-at (match-beginning 1))
5955 (add-text-properties (match-beginning 1) (match-end 1) vp)
5956 (org-rear-nonsticky-at (match-end 1))
5957 (add-text-properties (match-end 1) (match-end 0) ip)
5958 (org-rear-nonsticky-at (match-end 0)))
5959 t)))
5961 (defun org-activate-dates (limit)
5962 "Run through the buffer and add overlays to dates."
5963 (if (and (re-search-forward org-tsr-regexp-both limit t)
5964 (not (equal (char-before (match-beginning 0)) 91)))
5965 (progn
5966 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5967 (add-text-properties (match-beginning 0) (match-end 0)
5968 (list 'mouse-face 'highlight
5969 'keymap org-mouse-map))
5970 (org-rear-nonsticky-at (match-end 0))
5971 (when org-display-custom-times
5972 (if (match-end 3)
5973 (org-display-custom-time (match-beginning 3) (match-end 3)))
5974 (org-display-custom-time (match-beginning 1) (match-end 1)))
5975 t)))
5977 (defvar org-target-link-regexp nil
5978 "Regular expression matching radio targets in plain text.")
5979 (make-variable-buffer-local 'org-target-link-regexp)
5980 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5981 "Regular expression matching a link target.")
5982 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5983 "Regular expression matching a radio target.")
5984 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5985 "Regular expression matching any target.")
5987 (defun org-activate-target-links (limit)
5988 "Run through the buffer and add overlays to target matches."
5989 (when org-target-link-regexp
5990 (let ((case-fold-search t))
5991 (if (re-search-forward org-target-link-regexp limit t)
5992 (progn
5993 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5994 (add-text-properties (match-beginning 0) (match-end 0)
5995 (list 'mouse-face 'highlight
5996 'keymap org-mouse-map
5997 'help-echo "Radio target link"
5998 'org-linked-text t))
5999 (org-rear-nonsticky-at (match-end 0))
6000 t)))))
6002 (defun org-update-radio-target-regexp ()
6003 "Find all radio targets in this file and update the regular expression."
6004 (interactive)
6005 (when (memq 'radio org-activate-links)
6006 (setq org-target-link-regexp
6007 (org-make-target-link-regexp (org-all-targets 'radio)))
6008 (org-restart-font-lock)))
6010 (defun org-hide-wide-columns (limit)
6011 (let (s e)
6012 (setq s (text-property-any (point) (or limit (point-max))
6013 'org-cwidth t))
6014 (when s
6015 (setq e (next-single-property-change s 'org-cwidth))
6016 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6017 (goto-char e)
6018 t)))
6020 (defvar org-latex-and-related-regexp nil
6021 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6022 (defvar org-match-substring-regexp)
6023 (defvar org-match-substring-with-braces-regexp)
6025 (defun org-compute-latex-and-related-regexp ()
6026 "Compute regular expression for LaTeX, entities and sub/superscript.
6027 Result depends on variable `org-highlight-latex-and-related'."
6028 (org-set-local
6029 'org-latex-and-related-regexp
6030 (let* ((re-sub
6031 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6032 ((eq org-use-sub-superscripts '{})
6033 (list org-match-substring-with-braces-regexp))
6034 (org-use-sub-superscripts (list org-match-substring-regexp))))
6035 (re-latex
6036 (when (memq 'latex org-highlight-latex-and-related)
6037 (let ((matchers (plist-get org-format-latex-options :matchers)))
6038 (delq nil
6039 (mapcar (lambda (x)
6040 (and (member (car x) matchers) (nth 1 x)))
6041 org-latex-regexps)))))
6042 (re-entities
6043 (when (memq 'entities org-highlight-latex-and-related)
6044 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6045 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6047 (defun org-do-latex-and-related (limit)
6048 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6049 LIMIT bounds the search for syntax to highlight. Stop at first
6050 highlighted object, if any. Return t if some highlighting was
6051 done, nil otherwise."
6052 (when (org-string-nw-p org-latex-and-related-regexp)
6053 (catch 'found
6054 (while (re-search-forward org-latex-and-related-regexp limit t)
6055 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6056 'face))
6057 '(org-code org-verbatim underline))
6058 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6059 '(?_ ?^))
6061 0)))
6062 (font-lock-prepend-text-property
6063 (+ offset (match-beginning 0)) (match-end 0)
6064 'face 'org-latex-and-related)
6065 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6066 '(font-lock-multiline t)))
6067 (throw 'found t)))
6068 nil)))
6070 (defun org-restart-font-lock ()
6071 "Restart `font-lock-mode', to force refontification."
6072 (when (and (boundp 'font-lock-mode) font-lock-mode)
6073 (font-lock-mode -1)
6074 (font-lock-mode 1)))
6076 (defun org-all-targets (&optional radio)
6077 "Return a list of all targets in this file.
6078 When optional argument RADIO is non-nil, only find radio
6079 targets."
6080 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
6081 (save-excursion
6082 (goto-char (point-min))
6083 (while (re-search-forward re nil t)
6084 ;; Make sure point is really within the object.
6085 (backward-char)
6086 (let ((obj (org-element-context)))
6087 (when (memq (org-element-type obj) '(radio-target target))
6088 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
6089 rtn)))
6091 (defun org-make-target-link-regexp (targets)
6092 "Make regular expression matching all strings in TARGETS.
6093 The regular expression finds the targets also if there is a line break
6094 between words."
6095 (and targets
6096 (concat
6097 "\\<\\("
6098 (mapconcat
6099 (lambda (x)
6100 (setq x (regexp-quote x))
6101 (while (string-match " +" x)
6102 (setq x (replace-match "\\s-+" t t x)))
6104 targets
6105 "\\|")
6106 "\\)\\>")))
6108 (defun org-activate-tags (limit)
6109 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6110 (progn
6111 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6112 (add-text-properties (match-beginning 1) (match-end 1)
6113 (list 'mouse-face 'highlight
6114 'keymap org-mouse-map))
6115 (org-rear-nonsticky-at (match-end 1))
6116 t)))
6118 (defun org-outline-level ()
6119 "Compute the outline level of the heading at point.
6120 If this is called at a normal headline, the level is the number of stars.
6121 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6122 (save-excursion
6123 (if (not (condition-case nil
6124 (org-back-to-heading t)
6125 (error nil)))
6127 (looking-at org-outline-regexp)
6128 (1- (- (match-end 0) (match-beginning 0))))))
6130 (defvar org-font-lock-keywords nil)
6132 (defsubst org-re-property (property &optional literal)
6133 "Return a regexp matching a PROPERTY line.
6134 Match group 3 will be set to the value if it exists."
6135 (concat "^\\(?4:[ \t]*\\)\\(?1::\\(?2:"
6136 (if literal property (regexp-quote property))
6137 "\\):\\)[ \t]+\\(?3:[^ \t\r\n].*?\\)\\(?5:[ \t]*\\)$"))
6139 (defconst org-property-re
6140 (org-re-property ".*?" 'literal)
6141 "Regular expression matching a property line.
6142 There are four matching groups:
6143 1: :PROPKEY: including the leading and trailing colon,
6144 2: PROPKEY without the leading and trailing colon,
6145 3: PROPVAL without leading or trailing spaces,
6146 4: the indentation of the current line,
6147 5: trailing whitespace.")
6149 (defvar org-font-lock-hook nil
6150 "Functions to be called for special font lock stuff.")
6152 (defvar org-font-lock-set-keywords-hook nil
6153 "Functions that can manipulate `org-font-lock-extra-keywords'.
6154 This is called after `org-font-lock-extra-keywords' is defined, but before
6155 it is installed to be used by font lock. This can be useful if something
6156 needs to be inserted at a specific position in the font-lock sequence.")
6158 (defun org-font-lock-hook (limit)
6159 "Run `org-font-lock-hook' within LIMIT."
6160 (run-hook-with-args 'org-font-lock-hook limit))
6162 (defun org-set-font-lock-defaults ()
6163 "Set font lock defaults for the current buffer."
6164 (let* ((em org-fontify-emphasized-text)
6165 (lk org-activate-links)
6166 (org-font-lock-extra-keywords
6167 (list
6168 ;; Call the hook
6169 '(org-font-lock-hook)
6170 ;; Headlines
6171 `(,(if org-fontify-whole-heading-line
6172 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6173 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6174 (1 (org-get-level-face 1))
6175 (2 (org-get-level-face 2))
6176 (3 (org-get-level-face 3)))
6177 ;; Table lines
6178 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6179 (1 'org-table t))
6180 ;; Table internals
6181 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6182 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6183 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6184 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6185 ;; Drawers
6186 (list org-drawer-regexp '(0 'org-special-keyword t))
6187 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
6188 ;; Properties
6189 (list org-property-re
6190 '(1 'org-special-keyword t)
6191 '(3 'org-property-value t))
6192 ;; Links
6193 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6194 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6195 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6196 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6197 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6198 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6199 (if (memq 'footnote lk) '(org-activate-footnote-links))
6200 ;; Targets.
6201 (list org-any-target-regexp '(0 'org-target t))
6202 ;; Diary sexps.
6203 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6204 ;; Macro
6205 '("{{{.+}}}" (0 'org-macro t))
6206 '(org-hide-wide-columns (0 nil append))
6207 ;; TODO keyword
6208 (list (format org-heading-keyword-regexp-format
6209 org-todo-regexp)
6210 '(2 (org-get-todo-face 2) t))
6211 ;; DONE
6212 (if org-fontify-done-headline
6213 (list (format org-heading-keyword-regexp-format
6214 (concat
6215 "\\(?:"
6216 (mapconcat 'regexp-quote org-done-keywords "\\|")
6217 "\\)"))
6218 '(2 'org-headline-done t))
6219 nil)
6220 ;; Priorities
6221 '(org-font-lock-add-priority-faces)
6222 ;; Tags
6223 '(org-font-lock-add-tag-faces)
6224 ;; Tags groups
6225 (if (and org-group-tags org-tag-groups-alist)
6226 (list (concat org-outline-regexp-bol ".+\\(:"
6227 (regexp-opt (mapcar 'car org-tag-groups-alist))
6228 ":\\).*$")
6229 '(1 'org-tag-group prepend)))
6230 ;; Special keywords
6231 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6232 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6233 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6234 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6235 ;; Emphasis
6236 (if em
6237 (if (featurep 'xemacs)
6238 '(org-do-emphasis-faces (0 nil append))
6239 '(org-do-emphasis-faces)))
6240 ;; Checkboxes
6241 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6242 1 'org-checkbox prepend)
6243 (if (cdr (assq 'checkbox org-list-automatic-rules))
6244 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6245 (0 (org-get-checkbox-statistics-face) t)))
6246 ;; Description list items
6247 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6248 1 'org-list-dt prepend)
6249 ;; ARCHIVEd headings
6250 (list (concat
6251 org-outline-regexp-bol
6252 "\\(.*:" org-archive-tag ":.*\\)")
6253 '(1 'org-archived prepend))
6254 ;; Specials
6255 '(org-do-latex-and-related)
6256 '(org-fontify-entities)
6257 '(org-raise-scripts)
6258 ;; Code
6259 '(org-activate-code (1 'org-code t))
6260 ;; COMMENT
6261 (list (format org-heading-keyword-regexp-format
6262 (concat "\\("
6263 org-comment-string "\\|" org-quote-string
6264 "\\)"))
6265 '(2 'org-special-keyword t))
6266 ;; Blocks and meta lines
6267 '(org-fontify-meta-lines-and-blocks))))
6268 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6269 (run-hooks 'org-font-lock-set-keywords-hook)
6270 ;; Now set the full font-lock-keywords
6271 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6272 (org-set-local 'font-lock-defaults
6273 '(org-font-lock-keywords t nil nil backward-paragraph))
6274 (kill-local-variable 'font-lock-keywords) nil))
6276 (defun org-toggle-pretty-entities ()
6277 "Toggle the composition display of entities as UTF8 characters."
6278 (interactive)
6279 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6280 (org-restart-font-lock)
6281 (if org-pretty-entities
6282 (message "Entities are now displayed as UTF8 characters")
6283 (save-restriction
6284 (widen)
6285 (org-decompose-region (point-min) (point-max))
6286 (message "Entities are now displayed as plain text"))))
6288 (defvar org-custom-properties-overlays nil
6289 "List of overlays used for custom properties.")
6290 (make-variable-buffer-local 'org-custom-properties-overlays)
6292 (defun org-toggle-custom-properties-visibility ()
6293 "Display or hide properties in `org-custom-properties'."
6294 (interactive)
6295 (if org-custom-properties-overlays
6296 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6297 (setq org-custom-properties-overlays nil))
6298 (unless (not org-custom-properties)
6299 (save-excursion
6300 (save-restriction
6301 (widen)
6302 (goto-char (point-min))
6303 (while (re-search-forward org-property-re nil t)
6304 (mapc (lambda(p)
6305 (when (equal p (substring (match-string 1) 1 -1))
6306 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6307 (overlay-put o 'invisible t)
6308 (overlay-put o 'org-custom-property t)
6309 (push o org-custom-properties-overlays))))
6310 org-custom-properties)))))))
6312 (defun org-fontify-entities (limit)
6313 "Find an entity to fontify."
6314 (let (ee)
6315 (when org-pretty-entities
6316 (catch 'match
6317 (while (re-search-forward
6318 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6319 limit t)
6320 (if (and (not (org-in-indented-comment-line))
6321 (setq ee (org-entity-get (match-string 1)))
6322 (= (length (nth 6 ee)) 1))
6323 (let*
6324 ((end (if (equal (match-string 2) "{}")
6325 (match-end 2)
6326 (match-end 1))))
6327 (add-text-properties
6328 (match-beginning 0) end
6329 (list 'font-lock-fontified t))
6330 (compose-region (match-beginning 0) end
6331 (nth 6 ee) nil)
6332 (backward-char 1)
6333 (throw 'match t))))
6334 nil))))
6336 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6337 "Fontify string S like in Org-mode."
6338 (with-temp-buffer
6339 (insert s)
6340 (let ((org-odd-levels-only odd-levels))
6341 (org-mode)
6342 (font-lock-fontify-buffer)
6343 (buffer-string))))
6345 (defvar org-m nil)
6346 (defvar org-l nil)
6347 (defvar org-f nil)
6348 (defun org-get-level-face (n)
6349 "Get the right face for match N in font-lock matching of headlines."
6350 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6351 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6352 (if org-cycle-level-faces
6353 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6354 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6355 (cond
6356 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6357 ((eq n 2) org-f)
6358 (t (if org-level-color-stars-only nil org-f))))
6361 (defun org-get-todo-face (kwd)
6362 "Get the right face for a TODO keyword KWD.
6363 If KWD is a number, get the corresponding match group."
6364 (if (numberp kwd) (setq kwd (match-string kwd)))
6365 (or (org-face-from-face-or-color
6366 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6367 (and (member kwd org-done-keywords) 'org-done)
6368 'org-todo))
6370 (defun org-face-from-face-or-color (context inherit face-or-color)
6371 "Create a face list that inherits INHERIT, but sets the foreground color.
6372 When FACE-OR-COLOR is not a string, just return it."
6373 (if (stringp face-or-color)
6374 (list :inherit inherit
6375 (cdr (assoc context org-faces-easy-properties))
6376 face-or-color)
6377 face-or-color))
6379 (defun org-font-lock-add-tag-faces (limit)
6380 "Add the special tag faces."
6381 (when (and org-tag-faces org-tags-special-faces-re)
6382 (while (re-search-forward org-tags-special-faces-re limit t)
6383 (add-text-properties (match-beginning 1) (match-end 1)
6384 (list 'face (org-get-tag-face 1)
6385 'font-lock-fontified t))
6386 (backward-char 1))))
6388 (defun org-font-lock-add-priority-faces (limit)
6389 "Add the special priority faces."
6390 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6391 (when (save-match-data (org-at-heading-p))
6392 (add-text-properties
6393 (match-beginning 0) (match-end 0)
6394 (list 'face (or (org-face-from-face-or-color
6395 'priority 'org-priority
6396 (cdr (assoc (char-after (match-beginning 1))
6397 org-priority-faces)))
6398 'org-priority)
6399 'font-lock-fontified t)))))
6401 (defun org-get-tag-face (kwd)
6402 "Get the right face for a TODO keyword KWD.
6403 If KWD is a number, get the corresponding match group."
6404 (if (numberp kwd) (setq kwd (match-string kwd)))
6405 (or (org-face-from-face-or-color
6406 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6407 'org-tag))
6409 (defun org-unfontify-region (beg end &optional maybe_loudly)
6410 "Remove fontification and activation overlays from links."
6411 (font-lock-default-unfontify-region beg end)
6412 (let* ((buffer-undo-list t)
6413 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6414 (inhibit-modification-hooks t)
6415 deactivate-mark buffer-file-name buffer-file-truename)
6416 (org-decompose-region beg end)
6417 (remove-text-properties beg end
6418 '(mouse-face t keymap t org-linked-text t
6419 invisible t intangible t
6420 org-no-flyspell t org-emphasis t))
6421 (org-remove-font-lock-display-properties beg end)))
6423 (defconst org-script-display '(((raise -0.3) (height 0.7))
6424 ((raise 0.3) (height 0.7))
6425 ((raise -0.5))
6426 ((raise 0.5)))
6427 "Display properties for showing superscripts and subscripts.")
6429 (defun org-remove-font-lock-display-properties (beg end)
6430 "Remove specific display properties that have been added by font lock.
6431 The will remove the raise properties that are used to show superscripts
6432 and subscripts."
6433 (let (next prop)
6434 (while (< beg end)
6435 (setq next (next-single-property-change beg 'display nil end)
6436 prop (get-text-property beg 'display))
6437 (if (member prop org-script-display)
6438 (put-text-property beg next 'display nil))
6439 (setq beg next))))
6441 (defun org-raise-scripts (limit)
6442 "Add raise properties to sub/superscripts."
6443 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6444 (if (re-search-forward
6445 (if (eq org-use-sub-superscripts t)
6446 org-match-substring-regexp
6447 org-match-substring-with-braces-regexp)
6448 limit t)
6449 (let* ((pos (point)) table-p comment-p
6450 (mpos (match-beginning 3))
6451 (emph-p (get-text-property mpos 'org-emphasis))
6452 (link-p (get-text-property mpos 'mouse-face))
6453 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6454 (goto-char (point-at-bol))
6455 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6456 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6457 (goto-char pos)
6458 ;; Handle a_b^c
6459 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6460 (if (or comment-p emph-p link-p keyw-p)
6462 (put-text-property (match-beginning 3) (match-end 0)
6463 'display
6464 (if (equal (char-after (match-beginning 2)) ?^)
6465 (nth (if table-p 3 1) org-script-display)
6466 (nth (if table-p 2 0) org-script-display)))
6467 (add-text-properties (match-beginning 2) (match-end 2)
6468 (list 'invisible t
6469 'org-dwidth t 'org-dwidth-n 1))
6470 (if (and (eq (char-after (match-beginning 3)) ?{)
6471 (eq (char-before (match-end 3)) ?}))
6472 (progn
6473 (add-text-properties
6474 (match-beginning 3) (1+ (match-beginning 3))
6475 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6476 (add-text-properties
6477 (1- (match-end 3)) (match-end 3)
6478 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6479 t)))))
6481 ;;;; Visibility cycling, including org-goto and indirect buffer
6483 ;;; Cycling
6485 (defvar org-cycle-global-status nil)
6486 (make-variable-buffer-local 'org-cycle-global-status)
6487 (put 'org-cycle-global-status 'org-state t)
6488 (defvar org-cycle-subtree-status nil)
6489 (make-variable-buffer-local 'org-cycle-subtree-status)
6490 (put 'org-cycle-subtree-status 'org-state t)
6492 (defvar org-inlinetask-min-level)
6494 (defun org-unlogged-message (&rest args)
6495 "Display a message, but avoid logging it in the *Messages* buffer."
6496 (let ((message-log-max nil))
6497 (apply 'message args)))
6499 ;;;###autoload
6500 (defun org-cycle (&optional arg)
6501 "TAB-action and visibility cycling for Org-mode.
6503 This is the command invoked in Org-mode by the TAB key. Its main purpose
6504 is outline visibility cycling, but it also invokes other actions
6505 in special contexts.
6507 - When this function is called with a prefix argument, rotate the entire
6508 buffer through 3 states (global cycling)
6509 1. OVERVIEW: Show only top-level headlines.
6510 2. CONTENTS: Show all headlines of all levels, but no body text.
6511 3. SHOW ALL: Show everything.
6512 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6513 determined by the variable `org-startup-folded', and by any VISIBILITY
6514 properties in the buffer.
6515 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6516 including any drawers.
6518 - When inside a table, re-align the table and move to the next field.
6520 - When point is at the beginning of a headline, rotate the subtree started
6521 by this line through 3 different states (local cycling)
6522 1. FOLDED: Only the main headline is shown.
6523 2. CHILDREN: The main headline and the direct children are shown.
6524 From this state, you can move to one of the children
6525 and zoom in further.
6526 3. SUBTREE: Show the entire subtree, including body text.
6527 If there is no subtree, switch directly from CHILDREN to FOLDED.
6529 - When point is at the beginning of an empty headline and the variable
6530 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6531 of the headline by demoting and promoting it to likely levels. This
6532 speeds up creation document structure by pressing TAB once or several
6533 times right after creating a new headline.
6535 - When there is a numeric prefix, go up to a heading with level ARG, do
6536 a `show-subtree' and return to the previous cursor position. If ARG
6537 is negative, go up that many levels.
6539 - When point is not at the beginning of a headline, execute the global
6540 binding for TAB, which is re-indenting the line. See the option
6541 `org-cycle-emulate-tab' for details.
6543 - Special case: if point is at the beginning of the buffer and there is
6544 no headline in line 1, this function will act as if called with prefix arg
6545 (C-u TAB, same as S-TAB) also when called without prefix arg.
6546 But only if also the variable `org-cycle-global-at-bob' is t."
6547 (interactive "P")
6548 (org-load-modules-maybe)
6549 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6550 (and org-cycle-level-after-item/entry-creation
6551 (or (org-cycle-level)
6552 (org-cycle-item-indentation))))
6553 (let* ((limit-level
6554 (or org-cycle-max-level
6555 (and (boundp 'org-inlinetask-min-level)
6556 org-inlinetask-min-level
6557 (1- org-inlinetask-min-level))))
6558 (nstars (and limit-level
6559 (if org-odd-levels-only
6560 (and limit-level (1- (* limit-level 2)))
6561 limit-level)))
6562 (org-outline-regexp
6563 (if (not (derived-mode-p 'org-mode))
6564 outline-regexp
6565 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6566 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6567 (not (looking-at org-outline-regexp))))
6568 (org-cycle-hook
6569 (if bob-special
6570 (delq 'org-optimize-window-after-visibility-change
6571 (copy-sequence org-cycle-hook))
6572 org-cycle-hook))
6573 (pos (point)))
6575 (if (or bob-special (equal arg '(4)))
6576 ;; special case: use global cycling
6577 (setq arg t))
6579 (cond
6581 ((equal arg '(16))
6582 (setq last-command 'dummy)
6583 (org-set-startup-visibility)
6584 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6586 ((equal arg '(64))
6587 (show-all)
6588 (org-unlogged-message "Entire buffer visible, including drawers"))
6590 ;; Table: enter it or move to the next field.
6591 ((org-at-table-p 'any)
6592 (if (org-at-table.el-p)
6593 (message "Use C-c ' to edit table.el tables")
6594 (if arg (org-table-edit-field t)
6595 (org-table-justify-field-maybe)
6596 (call-interactively 'org-table-next-field))))
6598 ((run-hook-with-args-until-success
6599 'org-tab-after-check-for-table-hook))
6601 ;; Global cycling: delegate to `org-cycle-internal-global'.
6602 ((eq arg t) (org-cycle-internal-global))
6604 ;; Drawers: delegate to `org-flag-drawer'.
6605 ((and org-drawers org-drawer-regexp
6606 (save-excursion
6607 (beginning-of-line 1)
6608 (looking-at org-drawer-regexp)))
6609 (org-flag-drawer ; toggle block visibility
6610 (not (get-char-property (match-end 0) 'invisible))))
6612 ;; Show-subtree, ARG levels up from here.
6613 ((integerp arg)
6614 (save-excursion
6615 (org-back-to-heading)
6616 (outline-up-heading (if (< arg 0) (- arg)
6617 (- (funcall outline-level) arg)))
6618 (org-show-subtree)))
6620 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6621 ((and (featurep 'org-inlinetask)
6622 (org-inlinetask-at-task-p)
6623 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6624 (org-inlinetask-toggle-visibility))
6626 ((org-try-cdlatex-tab))
6628 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6629 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6630 (save-excursion (beginning-of-line 1)
6631 (looking-at org-outline-regexp)))
6632 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6633 (org-cycle-internal-local))
6635 ;; From there: TAB emulation and template completion.
6636 (buffer-read-only (org-back-to-heading))
6638 ((run-hook-with-args-until-success
6639 'org-tab-after-check-for-cycling-hook))
6641 ((org-try-structure-completion))
6643 ((run-hook-with-args-until-success
6644 'org-tab-before-tab-emulation-hook))
6646 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6647 (or (not (bolp))
6648 (not (looking-at org-outline-regexp))))
6649 (call-interactively (global-key-binding "\t")))
6651 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6652 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6653 (or (and (eq org-cycle-emulate-tab 'white)
6654 (= (match-end 0) (point-at-eol)))
6655 (and (eq org-cycle-emulate-tab 'whitestart)
6656 (>= (match-end 0) pos))))
6658 (eq org-cycle-emulate-tab t))
6659 (call-interactively (global-key-binding "\t")))
6661 (t (save-excursion
6662 (org-back-to-heading)
6663 (org-cycle)))))))
6665 (defun org-cycle-internal-global ()
6666 "Do the global cycling action."
6667 ;; Hack to avoid display of messages for .org attachments in Gnus
6668 (let ((ga (string-match "\\*fontification" (buffer-name))))
6669 (cond
6670 ((and (eq last-command this-command)
6671 (eq org-cycle-global-status 'overview))
6672 ;; We just created the overview - now do table of contents
6673 ;; This can be slow in very large buffers, so indicate action
6674 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6675 (unless ga (org-unlogged-message "CONTENTS..."))
6676 (org-content)
6677 (unless ga (org-unlogged-message "CONTENTS...done"))
6678 (setq org-cycle-global-status 'contents)
6679 (run-hook-with-args 'org-cycle-hook 'contents))
6681 ((and (eq last-command this-command)
6682 (eq org-cycle-global-status 'contents))
6683 ;; We just showed the table of contents - now show everything
6684 (run-hook-with-args 'org-pre-cycle-hook 'all)
6685 (show-all)
6686 (unless ga (org-unlogged-message "SHOW ALL"))
6687 (setq org-cycle-global-status 'all)
6688 (run-hook-with-args 'org-cycle-hook 'all))
6691 ;; Default action: go to overview
6692 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6693 (org-overview)
6694 (unless ga (org-unlogged-message "OVERVIEW"))
6695 (setq org-cycle-global-status 'overview)
6696 (run-hook-with-args 'org-cycle-hook 'overview)))))
6698 (defvar org-called-with-limited-levels);Dyn-bound in ̀org-with-limited-levels'.
6700 (defun org-cycle-internal-local ()
6701 "Do the local cycling action."
6702 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6703 ;; First, determine end of headline (EOH), end of subtree or item
6704 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6705 (save-excursion
6706 (if (org-at-item-p)
6707 (progn
6708 (beginning-of-line)
6709 (setq struct (org-list-struct))
6710 (setq eoh (point-at-eol))
6711 (setq eos (org-list-get-item-end-before-blank (point) struct))
6712 (setq has-children (org-list-has-child-p (point) struct)))
6713 (org-back-to-heading)
6714 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6715 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6716 (setq has-children
6717 (or (save-excursion
6718 (let ((level (funcall outline-level)))
6719 (outline-next-heading)
6720 (and (org-at-heading-p t)
6721 (> (funcall outline-level) level))))
6722 (save-excursion
6723 (org-list-search-forward (org-item-beginning-re) eos t)))))
6724 ;; Determine end invisible part of buffer (EOL)
6725 (beginning-of-line 2)
6726 ;; XEmacs doesn't have `next-single-char-property-change'
6727 (if (featurep 'xemacs)
6728 (while (and (not (eobp)) ;; this is like `next-line'
6729 (get-char-property (1- (point)) 'invisible))
6730 (beginning-of-line 2))
6731 (while (and (not (eobp)) ;; this is like `next-line'
6732 (get-char-property (1- (point)) 'invisible))
6733 (goto-char (next-single-char-property-change (point) 'invisible))
6734 (and (eolp) (beginning-of-line 2))))
6735 (setq eol (point)))
6736 ;; Find out what to do next and set `this-command'
6737 (cond
6738 ((= eos eoh)
6739 ;; Nothing is hidden behind this heading
6740 (unless (org-before-first-heading-p)
6741 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6742 (org-unlogged-message "EMPTY ENTRY")
6743 (setq org-cycle-subtree-status nil)
6744 (save-excursion
6745 (goto-char eos)
6746 (outline-next-heading)
6747 (if (outline-invisible-p) (org-flag-heading nil))))
6748 ((and (or (>= eol eos)
6749 (not (string-match "\\S-" (buffer-substring eol eos))))
6750 (or has-children
6751 (not (setq children-skipped
6752 org-cycle-skip-children-state-if-no-children))))
6753 ;; Entire subtree is hidden in one line: children view
6754 (unless (org-before-first-heading-p)
6755 (run-hook-with-args 'org-pre-cycle-hook 'children))
6756 (if (org-at-item-p)
6757 (org-list-set-item-visibility (point-at-bol) struct 'children)
6758 (org-show-entry)
6759 (org-with-limited-levels (show-children))
6760 ;; FIXME: This slows down the func way too much.
6761 ;; How keep drawers hidden in subtree anyway?
6762 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6763 ;; (org-cycle-hide-drawers 'subtree))
6765 ;; Fold every list in subtree to top-level items.
6766 (when (eq org-cycle-include-plain-lists 'integrate)
6767 (save-excursion
6768 (org-back-to-heading)
6769 (while (org-list-search-forward (org-item-beginning-re) eos t)
6770 (beginning-of-line 1)
6771 (let* ((struct (org-list-struct))
6772 (prevs (org-list-prevs-alist struct))
6773 (end (org-list-get-bottom-point struct)))
6774 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6775 (org-list-get-all-items (point) struct prevs))
6776 (goto-char (if (< end eos) end eos)))))))
6777 (org-unlogged-message "CHILDREN")
6778 (save-excursion
6779 (goto-char eos)
6780 (outline-next-heading)
6781 (if (outline-invisible-p) (org-flag-heading nil)))
6782 (setq org-cycle-subtree-status 'children)
6783 (unless (org-before-first-heading-p)
6784 (run-hook-with-args 'org-cycle-hook 'children)))
6785 ((or children-skipped
6786 (and (eq last-command this-command)
6787 (eq org-cycle-subtree-status 'children)))
6788 ;; We just showed the children, or no children are there,
6789 ;; now show everything.
6790 (unless (org-before-first-heading-p)
6791 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6792 (outline-flag-region eoh eos nil)
6793 (org-unlogged-message
6794 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6795 (setq org-cycle-subtree-status 'subtree)
6796 (unless (org-before-first-heading-p)
6797 (run-hook-with-args 'org-cycle-hook 'subtree)))
6799 ;; Default action: hide the subtree.
6800 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6801 (outline-flag-region eoh eos t)
6802 (org-unlogged-message "FOLDED")
6803 (setq org-cycle-subtree-status 'folded)
6804 (unless (org-before-first-heading-p)
6805 (run-hook-with-args 'org-cycle-hook 'folded))))))
6807 ;;;###autoload
6808 (defun org-global-cycle (&optional arg)
6809 "Cycle the global visibility. For details see `org-cycle'.
6810 With \\[universal-argument] prefix arg, switch to startup visibility.
6811 With a numeric prefix, show all headlines up to that level."
6812 (interactive "P")
6813 (let ((org-cycle-include-plain-lists
6814 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6815 (cond
6816 ((integerp arg)
6817 (show-all)
6818 (hide-sublevels arg)
6819 (setq org-cycle-global-status 'contents))
6820 ((equal arg '(4))
6821 (org-set-startup-visibility)
6822 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6824 (org-cycle '(4))))))
6826 (defun org-set-startup-visibility ()
6827 "Set the visibility required by startup options and properties."
6828 (cond
6829 ((eq org-startup-folded t)
6830 (org-cycle '(4)))
6831 ((eq org-startup-folded 'content)
6832 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6833 (org-cycle '(4)) (org-cycle '(4)))))
6834 (unless (eq org-startup-folded 'showeverything)
6835 (if org-hide-block-startup (org-hide-block-all))
6836 (org-set-visibility-according-to-property 'no-cleanup)
6837 (org-cycle-hide-archived-subtrees 'all)
6838 (org-cycle-hide-drawers 'all)
6839 (org-cycle-show-empty-lines t)))
6841 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6842 "Switch subtree visibilities according to :VISIBILITY: property."
6843 (interactive)
6844 (let (org-show-entry-below state)
6845 (save-excursion
6846 (goto-char (point-min))
6847 (while (re-search-forward
6848 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6849 nil t)
6850 (setq state (match-string 1))
6851 (save-excursion
6852 (org-back-to-heading t)
6853 (hide-subtree)
6854 (org-reveal)
6855 (cond
6856 ((equal state '("fold" "folded"))
6857 (hide-subtree))
6858 ((equal state "children")
6859 (org-show-hidden-entry)
6860 (show-children))
6861 ((equal state "content")
6862 (save-excursion
6863 (save-restriction
6864 (org-narrow-to-subtree)
6865 (org-content))))
6866 ((member state '("all" "showall"))
6867 (show-subtree)))))
6868 (unless no-cleanup
6869 (org-cycle-hide-archived-subtrees 'all)
6870 (org-cycle-hide-drawers 'all)
6871 (org-cycle-show-empty-lines 'all)))))
6873 ;; This function uses outline-regexp instead of the more fundamental
6874 ;; org-outline-regexp so that org-cycle-global works outside of Org
6875 ;; buffers, where outline-regexp is needed.
6876 (defun org-overview ()
6877 "Switch to overview mode, showing only top-level headlines.
6878 Really, this shows all headlines with level equal or greater than the level
6879 of the first headline in the buffer. This is important, because if the
6880 first headline is not level one, then (hide-sublevels 1) gives confusing
6881 results."
6882 (interactive)
6883 (let ((pos (point))
6884 (level (save-excursion
6885 (goto-char (point-min))
6886 (if (re-search-forward (concat "^" outline-regexp) nil t)
6887 (progn
6888 (goto-char (match-beginning 0))
6889 (funcall outline-level))))))
6890 (and level (hide-sublevels level))
6891 (recenter '(4))
6892 (goto-char pos)))
6894 (defun org-content (&optional arg)
6895 "Show all headlines in the buffer, like a table of contents.
6896 With numerical argument N, show content up to level N."
6897 (interactive "P")
6898 (save-excursion
6899 ;; Visit all headings and show their offspring
6900 (and (integerp arg) (org-overview))
6901 (goto-char (point-max))
6902 (catch 'exit
6903 (while (and (progn (condition-case nil
6904 (outline-previous-visible-heading 1)
6905 (error (goto-char (point-min))))
6907 (looking-at org-outline-regexp))
6908 (if (integerp arg)
6909 (show-children (1- arg))
6910 (show-branches))
6911 (if (bobp) (throw 'exit nil))))))
6914 (defun org-optimize-window-after-visibility-change (state)
6915 "Adjust the window after a change in outline visibility.
6916 This function is the default value of the hook `org-cycle-hook'."
6917 (when (get-buffer-window (current-buffer))
6918 (cond
6919 ((eq state 'content) nil)
6920 ((eq state 'all) nil)
6921 ((eq state 'folded) nil)
6922 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6923 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6925 (defun org-remove-empty-overlays-at (pos)
6926 "Remove outline overlays that do not contain non-white stuff."
6927 (mapc
6928 (lambda (o)
6929 (and (eq 'outline (overlay-get o 'invisible))
6930 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6931 (overlay-end o))))
6932 (delete-overlay o)))
6933 (overlays-at pos)))
6935 (defun org-clean-visibility-after-subtree-move ()
6936 "Fix visibility issues after moving a subtree."
6937 ;; First, find a reasonable region to look at:
6938 ;; Start two siblings above, end three below
6939 (let* ((beg (save-excursion
6940 (and (org-get-last-sibling)
6941 (org-get-last-sibling))
6942 (point)))
6943 (end (save-excursion
6944 (and (org-get-next-sibling)
6945 (org-get-next-sibling)
6946 (org-get-next-sibling))
6947 (if (org-at-heading-p)
6948 (point-at-eol)
6949 (point))))
6950 (level (looking-at "\\*+"))
6951 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6952 (save-excursion
6953 (save-restriction
6954 (narrow-to-region beg end)
6955 (when re
6956 ;; Properly fold already folded siblings
6957 (goto-char (point-min))
6958 (while (re-search-forward re nil t)
6959 (if (and (not (outline-invisible-p))
6960 (save-excursion
6961 (goto-char (point-at-eol)) (outline-invisible-p)))
6962 (hide-entry))))
6963 (org-cycle-show-empty-lines 'overview)
6964 (org-cycle-hide-drawers 'overview)))))
6966 (defun org-cycle-show-empty-lines (state)
6967 "Show empty lines above all visible headlines.
6968 The region to be covered depends on STATE when called through
6969 `org-cycle-hook'. Lisp program can use t for STATE to get the
6970 entire buffer covered. Note that an empty line is only shown if there
6971 are at least `org-cycle-separator-lines' empty lines before the headline."
6972 (when (not (= org-cycle-separator-lines 0))
6973 (save-excursion
6974 (let* ((n (abs org-cycle-separator-lines))
6975 (re (cond
6976 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6977 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6978 (t (let ((ns (number-to-string (- n 2))))
6979 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6980 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6981 beg end b e)
6982 (cond
6983 ((memq state '(overview contents t))
6984 (setq beg (point-min) end (point-max)))
6985 ((memq state '(children folded))
6986 (setq beg (point) end (progn (org-end-of-subtree t t)
6987 (beginning-of-line 2)
6988 (point)))))
6989 (when beg
6990 (goto-char beg)
6991 (while (re-search-forward re end t)
6992 (unless (get-char-property (match-end 1) 'invisible)
6993 (setq e (match-end 1))
6994 (if (< org-cycle-separator-lines 0)
6995 (setq b (save-excursion
6996 (goto-char (match-beginning 0))
6997 (org-back-over-empty-lines)
6998 (if (save-excursion
6999 (goto-char (max (point-min) (1- (point))))
7000 (org-at-heading-p))
7001 (1- (point))
7002 (point))))
7003 (setq b (match-beginning 1)))
7004 (outline-flag-region b e nil)))))))
7005 ;; Never hide empty lines at the end of the file.
7006 (save-excursion
7007 (goto-char (point-max))
7008 (outline-previous-heading)
7009 (outline-end-of-heading)
7010 (if (and (looking-at "[ \t\n]+")
7011 (= (match-end 0) (point-max)))
7012 (outline-flag-region (point) (match-end 0) nil))))
7014 (defun org-show-empty-lines-in-parent ()
7015 "Move to the parent and re-show empty lines before visible headlines."
7016 (save-excursion
7017 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7018 (org-cycle-show-empty-lines context))))
7020 (defun org-files-list ()
7021 "Return `org-agenda-files' list, plus all open org-mode files.
7022 This is useful for operations that need to scan all of a user's
7023 open and agenda-wise Org files."
7024 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7025 (dolist (buf (buffer-list))
7026 (with-current-buffer buf
7027 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7028 (let ((file (expand-file-name (buffer-file-name))))
7029 (unless (member file files)
7030 (push file files))))))
7031 files))
7033 (defsubst org-entry-beginning-position ()
7034 "Return the beginning position of the current entry."
7035 (save-excursion (outline-back-to-heading t) (point)))
7037 (defsubst org-entry-end-position ()
7038 "Return the end position of the current entry."
7039 (save-excursion (outline-next-heading) (point)))
7041 (defun org-cycle-hide-drawers (state)
7042 "Re-hide all drawers after a visibility state change."
7043 (when (and (derived-mode-p 'org-mode)
7044 (not (memq state '(overview folded contents))))
7045 (save-excursion
7046 (let* ((globalp (memq state '(contents all)))
7047 (beg (if globalp (point-min) (point)))
7048 (end (if globalp (point-max)
7049 (if (eq state 'children)
7050 (save-excursion (outline-next-heading) (point))
7051 (org-end-of-subtree t)))))
7052 (goto-char beg)
7053 (while (re-search-forward org-drawer-regexp end t)
7054 (org-flag-drawer t))))))
7056 (defun org-cycle-hide-inline-tasks (state)
7057 "Re-hide inline tasks when switching to 'contents or 'children
7058 visibility state."
7059 (case state
7060 (contents
7061 (when (org-bound-and-true-p org-inlinetask-min-level)
7062 (hide-sublevels (1- org-inlinetask-min-level))))
7063 (children
7064 (when (featurep 'org-inlinetask)
7065 (save-excursion
7066 (while (and (outline-next-heading)
7067 (org-inlinetask-at-task-p))
7068 (org-inlinetask-toggle-visibility)
7069 (org-inlinetask-goto-end)))))))
7071 (defun org-flag-drawer (flag)
7072 "When FLAG is non-nil, hide the drawer we are within.
7073 Otherwise make it visible."
7074 (save-excursion
7075 (beginning-of-line 1)
7076 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
7077 (let ((b (match-end 0)))
7078 (if (re-search-forward
7079 "^[ \t]*:END:"
7080 (save-excursion (outline-next-heading) (point)) t)
7081 (outline-flag-region b (point-at-eol) flag)
7082 (user-error ":END: line missing at position %s" b))))))
7084 (defun org-subtree-end-visible-p ()
7085 "Is the end of the current subtree visible?"
7086 (pos-visible-in-window-p
7087 (save-excursion (org-end-of-subtree t) (point))))
7089 (defun org-first-headline-recenter (&optional N)
7090 "Move cursor to the first headline and recenter the headline.
7091 Optional argument N means put the headline into the Nth line of the window."
7092 (goto-char (point-min))
7093 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7094 (beginning-of-line)
7095 (recenter (prefix-numeric-value N))))
7097 ;;; Saving and restoring visibility
7099 (defun org-outline-overlay-data (&optional use-markers)
7100 "Return a list of the locations of all outline overlays.
7101 These are overlays with the `invisible' property value `outline'.
7102 The return value is a list of cons cells, with start and stop
7103 positions for each overlay.
7104 If USE-MARKERS is set, return the positions as markers."
7105 (let (beg end)
7106 (save-excursion
7107 (save-restriction
7108 (widen)
7109 (delq nil
7110 (mapcar (lambda (o)
7111 (when (eq (overlay-get o 'invisible) 'outline)
7112 (setq beg (overlay-start o)
7113 end (overlay-end o))
7114 (and beg end (> end beg)
7115 (if use-markers
7116 (cons (move-marker (make-marker) beg)
7117 (move-marker (make-marker) end))
7118 (cons beg end)))))
7119 (overlays-in (point-min) (point-max))))))))
7121 (defun org-set-outline-overlay-data (data)
7122 "Create visibility overlays for all positions in DATA.
7123 DATA should have been made by `org-outline-overlay-data'."
7124 (let (o)
7125 (save-excursion
7126 (save-restriction
7127 (widen)
7128 (show-all)
7129 (mapc (lambda (c)
7130 (outline-flag-region (car c) (cdr c) t))
7131 data)))))
7133 ;;; Folding of blocks
7135 (defvar org-hide-block-overlays nil
7136 "Overlays hiding blocks.")
7137 (make-variable-buffer-local 'org-hide-block-overlays)
7139 (defun org-block-map (function &optional start end)
7140 "Call FUNCTION at the head of all source blocks in the current buffer.
7141 Optional arguments START and END can be used to limit the range."
7142 (let ((start (or start (point-min)))
7143 (end (or end (point-max))))
7144 (save-excursion
7145 (goto-char start)
7146 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7147 (save-excursion
7148 (save-match-data
7149 (goto-char (match-beginning 0))
7150 (funcall function)))))))
7152 (defun org-hide-block-toggle-all ()
7153 "Toggle the visibility of all blocks in the current buffer."
7154 (org-block-map #'org-hide-block-toggle))
7156 (defun org-hide-block-all ()
7157 "Fold all blocks in the current buffer."
7158 (interactive)
7159 (org-show-block-all)
7160 (org-block-map #'org-hide-block-toggle-maybe))
7162 (defun org-show-block-all ()
7163 "Unfold all blocks in the current buffer."
7164 (interactive)
7165 (mapc 'delete-overlay org-hide-block-overlays)
7166 (setq org-hide-block-overlays nil))
7168 (defun org-hide-block-toggle-maybe ()
7169 "Toggle visibility of block at point."
7170 (interactive)
7171 (let ((case-fold-search t))
7172 (if (save-excursion
7173 (beginning-of-line 1)
7174 (looking-at org-block-regexp))
7175 (progn (org-hide-block-toggle)
7176 t) ;; to signal that we took action
7177 nil))) ;; to signal that we did not
7179 (defun org-hide-block-toggle (&optional force)
7180 "Toggle the visibility of the current block."
7181 (interactive)
7182 (save-excursion
7183 (beginning-of-line)
7184 (if (re-search-forward org-block-regexp nil t)
7185 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7186 (end (match-end 0)) ;; end of entire body
7188 (if (memq t (mapcar (lambda (overlay)
7189 (eq (overlay-get overlay 'invisible)
7190 'org-hide-block))
7191 (overlays-at start)))
7192 (if (or (not force) (eq force 'off))
7193 (mapc (lambda (ov)
7194 (when (member ov org-hide-block-overlays)
7195 (setq org-hide-block-overlays
7196 (delq ov org-hide-block-overlays)))
7197 (when (eq (overlay-get ov 'invisible)
7198 'org-hide-block)
7199 (delete-overlay ov)))
7200 (overlays-at start)))
7201 (setq ov (make-overlay start end))
7202 (overlay-put ov 'invisible 'org-hide-block)
7203 ;; make the block accessible to isearch
7204 (overlay-put
7205 ov 'isearch-open-invisible
7206 (lambda (ov)
7207 (when (member ov org-hide-block-overlays)
7208 (setq org-hide-block-overlays
7209 (delq ov org-hide-block-overlays)))
7210 (when (eq (overlay-get ov 'invisible)
7211 'org-hide-block)
7212 (delete-overlay ov))))
7213 (push ov org-hide-block-overlays)))
7214 (user-error "Not looking at a source block"))))
7216 ;; org-tab-after-check-for-cycling-hook
7217 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7218 ;; Remove overlays when changing major mode
7219 (add-hook 'org-mode-hook
7220 (lambda () (org-add-hook 'change-major-mode-hook
7221 'org-show-block-all 'append 'local)))
7223 ;;; Org-goto
7225 (defvar org-goto-window-configuration nil)
7226 (defvar org-goto-marker nil)
7227 (defvar org-goto-map)
7228 (defun org-goto-map ()
7229 "Set the keymap `org-goto'."
7230 (setq org-goto-map
7231 (let ((map (make-sparse-keymap)))
7232 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7233 mouse-drag-region universal-argument org-occur))
7234 cmd)
7235 (while (setq cmd (pop cmds))
7236 (substitute-key-definition cmd cmd map global-map)))
7237 (suppress-keymap map)
7238 (org-defkey map "\C-m" 'org-goto-ret)
7239 (org-defkey map [(return)] 'org-goto-ret)
7240 (org-defkey map [(left)] 'org-goto-left)
7241 (org-defkey map [(right)] 'org-goto-right)
7242 (org-defkey map [(control ?g)] 'org-goto-quit)
7243 (org-defkey map "\C-i" 'org-cycle)
7244 (org-defkey map [(tab)] 'org-cycle)
7245 (org-defkey map [(down)] 'outline-next-visible-heading)
7246 (org-defkey map [(up)] 'outline-previous-visible-heading)
7247 (if org-goto-auto-isearch
7248 (if (fboundp 'define-key-after)
7249 (define-key-after map [t] 'org-goto-local-auto-isearch)
7250 nil)
7251 (org-defkey map "q" 'org-goto-quit)
7252 (org-defkey map "n" 'outline-next-visible-heading)
7253 (org-defkey map "p" 'outline-previous-visible-heading)
7254 (org-defkey map "f" 'outline-forward-same-level)
7255 (org-defkey map "b" 'outline-backward-same-level)
7256 (org-defkey map "u" 'outline-up-heading))
7257 (org-defkey map "/" 'org-occur)
7258 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7259 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7260 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7261 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7262 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7263 map)))
7265 (defconst org-goto-help
7266 "Browse buffer copy, to find location or copy text.%s
7267 RET=jump to location C-g=quit and return to previous location
7268 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7270 (defvar org-goto-start-pos) ; dynamically scoped parameter
7272 (defun org-goto (&optional alternative-interface)
7273 "Look up a different location in the current file, keeping current visibility.
7275 When you want look-up or go to a different location in a
7276 document, the fastest way is often to fold the entire buffer and
7277 then dive into the tree. This method has the disadvantage, that
7278 the previous location will be folded, which may not be what you
7279 want.
7281 This command works around this by showing a copy of the current
7282 buffer in an indirect buffer, in overview mode. You can dive
7283 into the tree in that copy, use org-occur and incremental search
7284 to find a location. When pressing RET or `Q', the command
7285 returns to the original buffer in which the visibility is still
7286 unchanged. After RET it will also jump to the location selected
7287 in the indirect buffer and expose the headline hierarchy above.
7289 With a prefix argument, use the alternative interface: e.g. if
7290 `org-goto-interface' is 'outline use 'outline-path-completion."
7291 (interactive "P")
7292 (org-goto-map)
7293 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7294 (org-refile-use-outline-path t)
7295 (org-refile-target-verify-function nil)
7296 (interface
7297 (if (not alternative-interface)
7298 org-goto-interface
7299 (if (eq org-goto-interface 'outline)
7300 'outline-path-completion
7301 'outline)))
7302 (org-goto-start-pos (point))
7303 (selected-point
7304 (if (eq interface 'outline)
7305 (car (org-get-location (current-buffer) org-goto-help))
7306 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7307 (org-refile-check-position pa)
7308 (nth 3 pa)))))
7309 (if selected-point
7310 (progn
7311 (org-mark-ring-push org-goto-start-pos)
7312 (goto-char selected-point)
7313 (if (or (outline-invisible-p) (org-invisible-p2))
7314 (org-show-context 'org-goto)))
7315 (message "Quit"))))
7317 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7318 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7319 (defvar org-goto-local-auto-isearch-map) ; defined below
7321 (defun org-get-location (buf help)
7322 "Let the user select a location in the Org-mode buffer BUF.
7323 This function uses a recursive edit. It returns the selected position
7324 or nil."
7325 (org-no-popups
7326 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7327 (isearch-hide-immediately nil)
7328 (isearch-search-fun-function
7329 (lambda () 'org-goto-local-search-headings))
7330 (org-goto-selected-point org-goto-exit-command))
7331 (save-excursion
7332 (save-window-excursion
7333 (delete-other-windows)
7334 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7335 (org-pop-to-buffer-same-window
7336 (condition-case nil
7337 (make-indirect-buffer (current-buffer) "*org-goto*")
7338 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7339 (with-output-to-temp-buffer "*Org Help*"
7340 (princ (format help (if org-goto-auto-isearch
7341 " Just type for auto-isearch."
7342 " n/p/f/b/u to navigate, q to quit."))))
7343 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7344 (setq buffer-read-only nil)
7345 (let ((org-startup-truncated t)
7346 (org-startup-folded nil)
7347 (org-startup-align-all-tables nil))
7348 (org-mode)
7349 (org-overview))
7350 (setq buffer-read-only t)
7351 (if (and (boundp 'org-goto-start-pos)
7352 (integer-or-marker-p org-goto-start-pos))
7353 (let ((org-show-hierarchy-above t)
7354 (org-show-siblings t)
7355 (org-show-following-heading t))
7356 (goto-char org-goto-start-pos)
7357 (and (outline-invisible-p) (org-show-context)))
7358 (goto-char (point-min)))
7359 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7360 (message "Select location and press RET")
7361 (use-local-map org-goto-map)
7362 (recursive-edit)))
7363 (kill-buffer "*org-goto*")
7364 (cons org-goto-selected-point org-goto-exit-command))))
7366 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7367 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7368 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7369 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7371 (defun org-goto-local-search-headings (string bound noerror)
7372 "Search and make sure that any matches are in headlines."
7373 (catch 'return
7374 (while (if isearch-forward
7375 (search-forward string bound noerror)
7376 (search-backward string bound noerror))
7377 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7378 (and (member :headline context)
7379 (not (member :tags context))))
7380 (throw 'return (point))))))
7382 (defun org-goto-local-auto-isearch ()
7383 "Start isearch."
7384 (interactive)
7385 (goto-char (point-min))
7386 (let ((keys (this-command-keys)))
7387 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7388 (isearch-mode t)
7389 (isearch-process-search-char (string-to-char keys)))))
7391 (defun org-goto-ret (&optional arg)
7392 "Finish `org-goto' by going to the new location."
7393 (interactive "P")
7394 (setq org-goto-selected-point (point)
7395 org-goto-exit-command 'return)
7396 (throw 'exit nil))
7398 (defun org-goto-left ()
7399 "Finish `org-goto' by going to the new location."
7400 (interactive)
7401 (if (org-at-heading-p)
7402 (progn
7403 (beginning-of-line 1)
7404 (setq org-goto-selected-point (point)
7405 org-goto-exit-command 'left)
7406 (throw 'exit nil))
7407 (user-error "Not on a heading")))
7409 (defun org-goto-right ()
7410 "Finish `org-goto' by going to the new location."
7411 (interactive)
7412 (if (org-at-heading-p)
7413 (progn
7414 (setq org-goto-selected-point (point)
7415 org-goto-exit-command 'right)
7416 (throw 'exit nil))
7417 (user-error "Not on a heading")))
7419 (defun org-goto-quit ()
7420 "Finish `org-goto' without cursor motion."
7421 (interactive)
7422 (setq org-goto-selected-point nil)
7423 (setq org-goto-exit-command 'quit)
7424 (throw 'exit nil))
7426 ;;; Indirect buffer display of subtrees
7428 (defvar org-indirect-dedicated-frame nil
7429 "This is the frame being used for indirect tree display.")
7430 (defvar org-last-indirect-buffer nil)
7432 (defun org-tree-to-indirect-buffer (&optional arg)
7433 "Create indirect buffer and narrow it to current subtree.
7434 With a numerical prefix ARG, go up to this level and then take that tree.
7435 If ARG is negative, go up that many levels.
7437 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7438 indirect buffer previously made with this command, to avoid proliferation of
7439 indirect buffers. However, when you call the command with a \
7440 \\[universal-argument] prefix, or
7441 when `org-indirect-buffer-display' is `new-frame', the last buffer
7442 is kept so that you can work with several indirect buffers at the same time.
7443 If `org-indirect-buffer-display' is `dedicated-frame', the \
7444 \\[universal-argument] prefix also
7445 requests that a new frame be made for the new buffer, so that the dedicated
7446 frame is not changed."
7447 (interactive "P")
7448 (let ((cbuf (current-buffer))
7449 (cwin (selected-window))
7450 (pos (point))
7451 beg end level heading ibuf)
7452 (save-excursion
7453 (org-back-to-heading t)
7454 (when (numberp arg)
7455 (setq level (org-outline-level))
7456 (if (< arg 0) (setq arg (+ level arg)))
7457 (while (> (setq level (org-outline-level)) arg)
7458 (org-up-heading-safe)))
7459 (setq beg (point)
7460 heading (org-get-heading))
7461 (org-end-of-subtree t t)
7462 (if (org-at-heading-p) (backward-char 1))
7463 (setq end (point)))
7464 (if (and (buffer-live-p org-last-indirect-buffer)
7465 (not (eq org-indirect-buffer-display 'new-frame))
7466 (not arg))
7467 (kill-buffer org-last-indirect-buffer))
7468 (setq ibuf (org-get-indirect-buffer cbuf)
7469 org-last-indirect-buffer ibuf)
7470 (cond
7471 ((or (eq org-indirect-buffer-display 'new-frame)
7472 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7473 (select-frame (make-frame))
7474 (delete-other-windows)
7475 (org-pop-to-buffer-same-window ibuf)
7476 (org-set-frame-title heading))
7477 ((eq org-indirect-buffer-display 'dedicated-frame)
7478 (raise-frame
7479 (select-frame (or (and org-indirect-dedicated-frame
7480 (frame-live-p org-indirect-dedicated-frame)
7481 org-indirect-dedicated-frame)
7482 (setq org-indirect-dedicated-frame (make-frame)))))
7483 (delete-other-windows)
7484 (org-pop-to-buffer-same-window ibuf)
7485 (org-set-frame-title (concat "Indirect: " heading)))
7486 ((eq org-indirect-buffer-display 'current-window)
7487 (org-pop-to-buffer-same-window ibuf))
7488 ((eq org-indirect-buffer-display 'other-window)
7489 (pop-to-buffer ibuf))
7490 (t (error "Invalid value")))
7491 (if (featurep 'xemacs)
7492 (save-excursion (org-mode) (turn-on-font-lock)))
7493 (narrow-to-region beg end)
7494 (show-all)
7495 (goto-char pos)
7496 (run-hook-with-args 'org-cycle-hook 'all)
7497 (and (window-live-p cwin) (select-window cwin))))
7499 (defun org-get-indirect-buffer (&optional buffer)
7500 (setq buffer (or buffer (current-buffer)))
7501 (let ((n 1) (base (buffer-name buffer)) bname)
7502 (while (buffer-live-p
7503 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7504 (setq n (1+ n)))
7505 (condition-case nil
7506 (make-indirect-buffer buffer bname 'clone)
7507 (error (make-indirect-buffer buffer bname)))))
7509 (defun org-set-frame-title (title)
7510 "Set the title of the current frame to the string TITLE."
7511 ;; FIXME: how to name a single frame in XEmacs???
7512 (unless (featurep 'xemacs)
7513 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7515 ;;;; Structure editing
7517 ;;; Inserting headlines
7519 (defun org-previous-line-empty-p (&optional next)
7520 "Is the previous line a blank line?
7521 When NEXT is non-nil, check the next line instead."
7522 (save-excursion
7523 (and (not (bobp))
7524 (or (beginning-of-line (if next 2 0)) t)
7525 (save-match-data
7526 (looking-at "[ \t]*$")))))
7528 (defun org-insert-heading (&optional arg invisible-ok)
7529 "Insert a new heading or item with same depth at point.
7530 If point is in a plain list and ARG is nil, create a new list item.
7531 With one universal prefix argument, insert a heading even in lists.
7532 With two universal prefix arguments, insert the heading at the end
7533 of the parent subtree.
7535 If point is at the beginning of a headline, insert a sibling before
7536 the current headline. If point is not at the beginning, split the line
7537 and create a new headline with the text in the current line after point
7538 \(see `org-M-RET-may-split-line' on how to modify this behavior).
7540 If point is at the beginning of a normal line, turn this line into
7541 a heading.
7543 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7544 This is important for non-interactive uses of the command."
7545 (interactive "P")
7546 (if (org-called-interactively-p 'any) (org-reveal))
7547 (let ((itemp (org-in-item-p))
7548 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7549 (respect-content (or org-insert-heading-respect-content
7550 (equal arg '(16))))
7551 (initial-content "")
7552 (adjust-empty-lines t))
7554 (cond
7556 ((or (= (buffer-size) 0)
7557 (and (not (save-excursion
7558 (and (ignore-errors (org-back-to-heading invisible-ok))
7559 (org-at-heading-p))))
7560 (or arg (not itemp))))
7561 ;; At beginning of buffer or so high up that only a heading
7562 ;; makes sense.
7563 (insert
7564 (if (or (bobp) (org-previous-line-empty-p)) "" "\n")
7565 (if (org-in-src-block-p) ",* " "* "))
7566 (run-hooks 'org-insert-heading-hook))
7568 ((and itemp (not (equal arg '(4))))
7569 ;; Insert an item
7570 (org-insert-item))
7573 ;; Insert a heading
7574 (save-restriction
7575 (widen)
7576 (let* ((level nil)
7577 (on-heading (org-at-heading-p))
7578 (empty-line-p (if on-heading
7579 (org-previous-line-empty-p)
7580 ;; We will decide later
7581 nil))
7582 ;; Get a level string to fall back on
7583 (fix-level
7584 (save-excursion
7585 (org-back-to-heading t)
7586 (if (org-previous-line-empty-p) (setq empty-line-p t))
7587 (looking-at org-outline-regexp)
7588 (make-string (1- (length (match-string 0))) ?*)))
7589 (stars
7590 (save-excursion
7591 (condition-case nil
7592 (progn
7593 (org-back-to-heading invisible-ok)
7594 (when (and (not on-heading)
7595 (featurep 'org-inlinetask)
7596 (integerp org-inlinetask-min-level)
7597 (>= (length (match-string 0))
7598 org-inlinetask-min-level))
7599 ;; Find a heading level before the inline task
7600 (while (and (setq level (org-up-heading-safe))
7601 (>= level org-inlinetask-min-level)))
7602 (if (org-at-heading-p)
7603 (org-back-to-heading invisible-ok)
7604 (error "This should not happen")))
7605 (unless (and (save-excursion
7606 (save-match-data
7607 (org-backward-heading-same-level
7608 1 invisible-ok))
7609 (= (point) (match-beginning 0)))
7610 (not (org-previous-line-empty-p t)))
7611 (setq empty-line-p (or empty-line-p
7612 (org-previous-line-empty-p))))
7613 (match-string 0))
7614 (error (or fix-level "* ")))))
7615 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7616 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7617 pos hide-previous previous-pos)
7619 ;; If we insert after content, move there and clean up whitespace
7620 (when respect-content
7621 (org-end-of-subtree nil t)
7622 (skip-chars-backward " \r\n")
7623 (and (looking-at "[ \t]+") (replace-match ""))
7624 (unless (eobp) (forward-char 1))
7625 (when (looking-at "^\\*")
7626 (unless (bobp) (backward-char 1))
7627 (insert "\n")))
7629 ;; If we are splitting, grab the text that should be moved to the new headline
7630 (when may-split
7631 (if (org-on-heading-p)
7632 ;; This is a heading, we split intelligently (keeping tags)
7633 (let ((pos (point)))
7634 (goto-char (point-at-bol))
7635 (unless (looking-at org-complex-heading-regexp)
7636 (error "This should not happen"))
7637 (when (and (match-beginning 4)
7638 (> pos (match-beginning 4))
7639 (< pos (match-end 4)))
7640 (setq initial-content (buffer-substring pos (match-end 4)))
7641 (goto-char pos)
7642 (delete-region (point) (match-end 4))
7643 (if (looking-at "[ \t]*$")
7644 (replace-match "")
7645 (insert (make-string (length initial-content) ?\ )))
7646 (setq initial-content (org-trim initial-content)))
7647 (goto-char pos))
7648 ;; a normal line
7649 (unless (bolp)
7650 (setq initial-content (buffer-substring (point) (point-at-eol)))
7651 (delete-region (point) (point-at-eol))
7652 (setq initial-content (org-trim initial-content)))))
7654 ;; If we are at the beginning of the line, insert before it. Else after
7655 (cond
7656 ((and (bolp) (looking-at "[ \t]*$")))
7657 ((and (bolp) (not (looking-at "[ \t]*$")))
7658 (open-line 1))
7660 (goto-char (point-at-eol))
7661 (insert "\n")))
7663 ;; Insert the new heading
7664 (insert stars)
7665 (just-one-space)
7666 (insert initial-content)
7667 (when adjust-empty-lines
7668 (if (or (not blank)
7669 (and blank (not (org-previous-line-empty-p))))
7670 (org-N-empty-lines-before-current (if blank 1 0))))
7671 (run-hooks 'org-insert-heading-hook)))))))
7673 (defun org-N-empty-lines-before-current (N)
7674 "Make the number of empty lines before current exactly N.
7675 So this will delete or add empty lines."
7676 (save-excursion
7677 (goto-char (point-at-bol))
7678 (if (looking-back "\\s-+" nil 'greedy)
7679 (replace-match ""))
7680 (or (bobp) (insert "\n"))
7681 (while (> N 0)
7682 (insert "\n")
7683 (setq N (1- N)))))
7685 (defun org-get-heading (&optional no-tags no-todo)
7686 "Return the heading of the current entry, without the stars.
7687 When NO-TAGS is non-nil, don't include tags.
7688 When NO-TODO is non-nil, don't include TODO keywords."
7689 (save-excursion
7690 (org-back-to-heading t)
7691 (cond
7692 ((and no-tags no-todo)
7693 (looking-at org-complex-heading-regexp)
7694 (match-string 4))
7695 (no-tags
7696 (looking-at (concat org-outline-regexp
7697 "\\(.*?\\)"
7698 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7699 (match-string 1))
7700 (no-todo
7701 (looking-at org-todo-line-regexp)
7702 (match-string 3))
7703 (t (looking-at org-heading-regexp)
7704 (match-string 2)))))
7706 (defvar orgstruct-mode) ; defined below
7708 (defun org-heading-components ()
7709 "Return the components of the current heading.
7710 This is a list with the following elements:
7711 - the level as an integer
7712 - the reduced level, different if `org-odd-levels-only' is set.
7713 - the TODO keyword, or nil
7714 - the priority character, like ?A, or nil if no priority is given
7715 - the headline text itself, or the tags string if no headline text
7716 - the tags string, or nil."
7717 (save-excursion
7718 (org-back-to-heading t)
7719 (if (let (case-fold-search)
7720 (looking-at
7721 (if orgstruct-mode
7722 org-heading-regexp
7723 org-complex-heading-regexp)))
7724 (if orgstruct-mode
7725 (list (length (match-string 1))
7726 (org-reduced-level (length (match-string 1)))
7729 (match-string 2)
7730 nil)
7731 (list (length (match-string 1))
7732 (org-reduced-level (length (match-string 1)))
7733 (org-match-string-no-properties 2)
7734 (and (match-end 3) (aref (match-string 3) 2))
7735 (org-match-string-no-properties 4)
7736 (org-match-string-no-properties 5))))))
7738 (defun org-get-entry ()
7739 "Get the entry text, after heading, entire subtree."
7740 (save-excursion
7741 (org-back-to-heading t)
7742 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7744 (defun org-insert-heading-after-current ()
7745 "Insert a new heading with same level as current, after current subtree."
7746 (interactive)
7747 (org-back-to-heading)
7748 (org-insert-heading)
7749 (org-move-subtree-down)
7750 (end-of-line 1))
7752 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7753 "Insert heading with `org-insert-heading-respect-content' set to t."
7754 (interactive "P")
7755 (let ((org-insert-heading-respect-content t))
7756 (org-insert-heading '(4) invisible-ok)))
7758 (defun org-insert-todo-heading-respect-content (&optional force-state)
7759 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7760 (interactive "P")
7761 (let ((org-insert-heading-respect-content t))
7762 (org-insert-todo-heading force-state '(4))))
7764 (defun org-insert-todo-heading (arg &optional force-heading)
7765 "Insert a new heading with the same level and TODO state as current heading.
7766 If the heading has no TODO state, or if the state is DONE, use the first
7767 state (TODO by default). Also one prefix arg, force first state. With two
7768 prefix args, force inserting at the end of the parent subtree."
7769 (interactive "P")
7770 (when (or force-heading (not (org-insert-item 'checkbox)))
7771 (org-insert-heading (or (and (equal arg '(16)) '(16))
7772 force-heading))
7773 (save-excursion
7774 (org-back-to-heading)
7775 (outline-previous-heading)
7776 (looking-at org-todo-line-regexp))
7777 (let*
7778 ((new-mark-x
7779 (if (or arg
7780 (not (match-beginning 2))
7781 (member (match-string 2) org-done-keywords))
7782 (car org-todo-keywords-1)
7783 (match-string 2)))
7784 (new-mark
7786 (run-hook-with-args-until-success
7787 'org-todo-get-default-hook new-mark-x nil)
7788 new-mark-x)))
7789 (beginning-of-line 1)
7790 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7791 (if org-treat-insert-todo-heading-as-state-change
7792 (org-todo new-mark)
7793 (insert new-mark " "))))
7794 (when org-provide-todo-statistics
7795 (org-update-parent-todo-statistics))))
7797 (defun org-insert-subheading (arg)
7798 "Insert a new subheading and demote it.
7799 Works for outline headings and for plain lists alike."
7800 (interactive "P")
7801 (org-insert-heading arg)
7802 (cond
7803 ((org-at-heading-p) (org-do-demote))
7804 ((org-at-item-p) (org-indent-item))))
7806 (defun org-insert-todo-subheading (arg)
7807 "Insert a new subheading with TODO keyword or checkbox and demote it.
7808 Works for outline headings and for plain lists alike."
7809 (interactive "P")
7810 (org-insert-todo-heading arg)
7811 (cond
7812 ((org-at-heading-p) (org-do-demote))
7813 ((org-at-item-p) (org-indent-item))))
7815 ;;; Promotion and Demotion
7817 (defvar org-after-demote-entry-hook nil
7818 "Hook run after an entry has been demoted.
7819 The cursor will be at the beginning of the entry.
7820 When a subtree is being demoted, the hook will be called for each node.")
7822 (defvar org-after-promote-entry-hook nil
7823 "Hook run after an entry has been promoted.
7824 The cursor will be at the beginning of the entry.
7825 When a subtree is being promoted, the hook will be called for each node.")
7827 (defun org-promote-subtree ()
7828 "Promote the entire subtree.
7829 See also `org-promote'."
7830 (interactive)
7831 (save-excursion
7832 (org-with-limited-levels (org-map-tree 'org-promote)))
7833 (org-fix-position-after-promote))
7835 (defun org-demote-subtree ()
7836 "Demote the entire subtree. See `org-demote'.
7837 See also `org-promote'."
7838 (interactive)
7839 (save-excursion
7840 (org-with-limited-levels (org-map-tree 'org-demote)))
7841 (org-fix-position-after-promote))
7844 (defun org-do-promote ()
7845 "Promote the current heading higher up the tree.
7846 If the region is active in `transient-mark-mode', promote all headings
7847 in the region."
7848 (interactive)
7849 (save-excursion
7850 (if (org-region-active-p)
7851 (org-map-region 'org-promote (region-beginning) (region-end))
7852 (org-promote)))
7853 (org-fix-position-after-promote))
7855 (defun org-do-demote ()
7856 "Demote the current heading lower down the tree.
7857 If the region is active in `transient-mark-mode', demote all headings
7858 in the region."
7859 (interactive)
7860 (save-excursion
7861 (if (org-region-active-p)
7862 (org-map-region 'org-demote (region-beginning) (region-end))
7863 (org-demote)))
7864 (org-fix-position-after-promote))
7866 (defun org-fix-position-after-promote ()
7867 "Make sure that after pro/demotion cursor position is right."
7868 (let ((pos (point)))
7869 (when (save-excursion
7870 (beginning-of-line 1)
7871 (looking-at org-todo-line-regexp)
7872 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7873 (cond ((eobp) (insert " "))
7874 ((eolp) (insert " "))
7875 ((equal (char-after) ?\ ) (forward-char 1))))))
7877 (defun org-current-level ()
7878 "Return the level of the current entry, or nil if before the first headline.
7879 The level is the number of stars at the beginning of the headline."
7880 (save-excursion
7881 (org-with-limited-levels
7882 (if (ignore-errors (org-back-to-heading t))
7883 (funcall outline-level)))))
7885 (defun org-get-previous-line-level ()
7886 "Return the outline depth of the last headline before the current line.
7887 Returns 0 for the first headline in the buffer, and nil if before the
7888 first headline."
7889 (let ((current-level (org-current-level))
7890 (prev-level (when (> (line-number-at-pos) 1)
7891 (save-excursion
7892 (beginning-of-line 0)
7893 (org-current-level)))))
7894 (cond ((null current-level) nil) ; Before first headline
7895 ((null prev-level) 0) ; At first headline
7896 (prev-level))))
7898 (defun org-reduced-level (l)
7899 "Compute the effective level of a heading.
7900 This takes into account the setting of `org-odd-levels-only'."
7901 (cond
7902 ((zerop l) 0)
7903 (org-odd-levels-only (1+ (floor (/ l 2))))
7904 (t l)))
7906 (defun org-level-increment ()
7907 "Return the number of stars that will be added or removed at a
7908 time to headlines when structure editing, based on the value of
7909 `org-odd-levels-only'."
7910 (if org-odd-levels-only 2 1))
7912 (defun org-get-valid-level (level &optional change)
7913 "Rectify a level change under the influence of `org-odd-levels-only'
7914 LEVEL is a current level, CHANGE is by how much the level should be
7915 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7916 even level numbers will become the next higher odd number."
7917 (if org-odd-levels-only
7918 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7919 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7920 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7921 (max 1 (+ level (or change 0)))))
7923 (if (boundp 'define-obsolete-function-alias)
7924 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7925 (define-obsolete-function-alias 'org-get-legal-level
7926 'org-get-valid-level)
7927 (define-obsolete-function-alias 'org-get-legal-level
7928 'org-get-valid-level "23.1")))
7930 (defun org-promote ()
7931 "Promote the current heading higher up the tree.
7932 If the region is active in `transient-mark-mode', promote all headings
7933 in the region."
7934 (org-back-to-heading t)
7935 (let* ((level (save-match-data (funcall outline-level)))
7936 (after-change-functions (remove 'flyspell-after-change-function
7937 after-change-functions))
7938 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7939 (diff (abs (- level (length up-head) -1))))
7940 (cond ((and (= level 1) org-called-with-limited-levels
7941 org-allow-promoting-top-level-subtree)
7942 (replace-match "# " nil t))
7943 ((= level 1)
7944 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
7945 (t (replace-match up-head nil t)))
7946 ;; Fixup tag positioning
7947 (unless (= level 1)
7948 (and org-auto-align-tags (org-set-tags nil t))
7949 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7950 (run-hooks 'org-after-promote-entry-hook)))
7952 (defun org-demote ()
7953 "Demote the current heading lower down the tree.
7954 If the region is active in `transient-mark-mode', demote all headings
7955 in the region."
7956 (org-back-to-heading t)
7957 (let* ((level (save-match-data (funcall outline-level)))
7958 (after-change-functions (remove 'flyspell-after-change-function
7959 after-change-functions))
7960 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7961 (diff (abs (- level (length down-head) -1))))
7962 (replace-match down-head nil t)
7963 ;; Fixup tag positioning
7964 (and org-auto-align-tags (org-set-tags nil t))
7965 (if org-adapt-indentation (org-fixup-indentation diff))
7966 (run-hooks 'org-after-demote-entry-hook)))
7968 (defun org-cycle-level ()
7969 "Cycle the level of an empty headline through possible states.
7970 This goes first to child, then to parent, level, then up the hierarchy.
7971 After top level, it switches back to sibling level."
7972 (interactive)
7973 (let ((org-adapt-indentation nil))
7974 (when (org-point-at-end-of-empty-headline)
7975 (setq this-command 'org-cycle-level) ; Only needed for caching
7976 (let ((cur-level (org-current-level))
7977 (prev-level (org-get-previous-line-level)))
7978 (cond
7979 ;; If first headline in file, promote to top-level.
7980 ((= prev-level 0)
7981 (loop repeat (/ (- cur-level 1) (org-level-increment))
7982 do (org-do-promote)))
7983 ;; If same level as prev, demote one.
7984 ((= prev-level cur-level)
7985 (org-do-demote))
7986 ;; If parent is top-level, promote to top level if not already.
7987 ((= prev-level 1)
7988 (loop repeat (/ (- cur-level 1) (org-level-increment))
7989 do (org-do-promote)))
7990 ;; If top-level, return to prev-level.
7991 ((= cur-level 1)
7992 (loop repeat (/ (- prev-level 1) (org-level-increment))
7993 do (org-do-demote)))
7994 ;; If less than prev-level, promote one.
7995 ((< cur-level prev-level)
7996 (org-do-promote))
7997 ;; If deeper than prev-level, promote until higher than
7998 ;; prev-level.
7999 ((> cur-level prev-level)
8000 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8001 do (org-do-promote))))
8002 t))))
8004 (defun org-map-tree (fun)
8005 "Call FUN for every heading underneath the current one."
8006 (org-back-to-heading)
8007 (let ((level (funcall outline-level)))
8008 (save-excursion
8009 (funcall fun)
8010 (while (and (progn
8011 (outline-next-heading)
8012 (> (funcall outline-level) level))
8013 (not (eobp)))
8014 (funcall fun)))))
8016 (defun org-map-region (fun beg end)
8017 "Call FUN for every heading between BEG and END."
8018 (let ((org-ignore-region t))
8019 (save-excursion
8020 (setq end (copy-marker end))
8021 (goto-char beg)
8022 (if (and (re-search-forward org-outline-regexp-bol nil t)
8023 (< (point) end))
8024 (funcall fun))
8025 (while (and (progn
8026 (outline-next-heading)
8027 (< (point) end))
8028 (not (eobp)))
8029 (funcall fun)))))
8031 (defvar org-property-end-re) ; silence byte-compiler
8032 (defun org-fixup-indentation (diff)
8033 "Change the indentation in the current entry by DIFF.
8034 However, if any line in the current entry has no indentation, or if it
8035 would end up with no indentation after the change, nothing at all is done."
8036 (save-excursion
8037 (let ((end (save-excursion (outline-next-heading)
8038 (point-marker)))
8039 (prohibit (if (> diff 0)
8040 "^\\S-"
8041 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8042 col)
8043 (unless (save-excursion (end-of-line 1)
8044 (re-search-forward prohibit end t))
8045 (while (and (< (point) end)
8046 (re-search-forward "^[ \t]+" end t))
8047 (goto-char (match-end 0))
8048 (setq col (current-column))
8049 (if (< diff 0) (replace-match ""))
8050 (org-indent-to-column (+ diff col))))
8051 (move-marker end nil))))
8053 (defun org-convert-to-odd-levels ()
8054 "Convert an org-mode file with all levels allowed to one with odd levels.
8055 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8056 level 5 etc."
8057 (interactive)
8058 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8059 (let ((outline-level 'org-outline-level)
8060 (org-odd-levels-only nil) n)
8061 (save-excursion
8062 (goto-char (point-min))
8063 (while (re-search-forward "^\\*\\*+ " nil t)
8064 (setq n (- (length (match-string 0)) 2))
8065 (while (>= (setq n (1- n)) 0)
8066 (org-demote))
8067 (end-of-line 1))))))
8069 (defun org-convert-to-oddeven-levels ()
8070 "Convert an org-mode file with only odd levels to one with odd/even levels.
8071 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8072 file contains a section with an even level, conversion would
8073 destroy the structure of the file. An error is signaled in this
8074 case."
8075 (interactive)
8076 (goto-char (point-min))
8077 ;; First check if there are no even levels
8078 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8079 (org-show-context t)
8080 (error "Not all levels are odd in this file. Conversion not possible"))
8081 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8082 (let ((outline-regexp org-outline-regexp)
8083 (outline-level 'org-outline-level)
8084 (org-odd-levels-only nil) n)
8085 (save-excursion
8086 (goto-char (point-min))
8087 (while (re-search-forward "^\\*\\*+ " nil t)
8088 (setq n (/ (1- (length (match-string 0))) 2))
8089 (while (>= (setq n (1- n)) 0)
8090 (org-promote))
8091 (end-of-line 1))))))
8093 (defun org-tr-level (n)
8094 "Make N odd if required."
8095 (if org-odd-levels-only (1+ (/ n 2)) n))
8097 ;;; Vertical tree motion, cutting and pasting of subtrees
8099 (defun org-move-subtree-up (&optional arg)
8100 "Move the current subtree up past ARG headlines of the same level."
8101 (interactive "p")
8102 (org-move-subtree-down (- (prefix-numeric-value arg))))
8104 (defun org-move-subtree-down (&optional arg)
8105 "Move the current subtree down past ARG headlines of the same level."
8106 (interactive "p")
8107 (setq arg (prefix-numeric-value arg))
8108 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8109 'org-get-last-sibling))
8110 (ins-point (make-marker))
8111 (cnt (abs arg))
8112 (col (current-column))
8113 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8114 ;; Select the tree
8115 (org-back-to-heading)
8116 (setq beg0 (point))
8117 (save-excursion
8118 (setq ne-beg (org-back-over-empty-lines))
8119 (setq beg (point)))
8120 (save-match-data
8121 (save-excursion (outline-end-of-heading)
8122 (setq folded (outline-invisible-p)))
8123 (outline-end-of-subtree))
8124 (outline-next-heading)
8125 (setq ne-end (org-back-over-empty-lines))
8126 (setq end (point))
8127 (goto-char beg0)
8128 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8129 ;; include less whitespace
8130 (save-excursion
8131 (goto-char beg)
8132 (forward-line (- ne-beg ne-end))
8133 (setq beg (point))))
8134 ;; Find insertion point, with error handling
8135 (while (> cnt 0)
8136 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8137 (progn (goto-char beg0)
8138 (user-error "Cannot move past superior level or buffer limit")))
8139 (setq cnt (1- cnt)))
8140 (if (> arg 0)
8141 ;; Moving forward - still need to move over subtree
8142 (progn (org-end-of-subtree t t)
8143 (save-excursion
8144 (org-back-over-empty-lines)
8145 (or (bolp) (newline)))))
8146 (setq ne-ins (org-back-over-empty-lines))
8147 (move-marker ins-point (point))
8148 (setq txt (buffer-substring beg end))
8149 (org-save-markers-in-region beg end)
8150 (delete-region beg end)
8151 (org-remove-empty-overlays-at beg)
8152 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8153 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8154 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8155 (let ((bbb (point)))
8156 (insert-before-markers txt)
8157 (org-reinstall-markers-in-region bbb)
8158 (move-marker ins-point bbb))
8159 (or (bolp) (insert "\n"))
8160 (setq ins-end (point))
8161 (goto-char ins-point)
8162 (org-skip-whitespace)
8163 (when (and (< arg 0)
8164 (org-first-sibling-p)
8165 (> ne-ins ne-beg))
8166 ;; Move whitespace back to beginning
8167 (save-excursion
8168 (goto-char ins-end)
8169 (let ((kill-whole-line t))
8170 (kill-line (- ne-ins ne-beg)) (point)))
8171 (insert (make-string (- ne-ins ne-beg) ?\n)))
8172 (move-marker ins-point nil)
8173 (if folded
8174 (hide-subtree)
8175 (org-show-entry)
8176 (show-children)
8177 (org-cycle-hide-drawers 'children))
8178 (org-clean-visibility-after-subtree-move)
8179 ;; move back to the initial column we were at
8180 (move-to-column col)))
8182 (defvar org-subtree-clip ""
8183 "Clipboard for cut and paste of subtrees.
8184 This is actually only a copy of the kill, because we use the normal kill
8185 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8187 (defvar org-subtree-clip-folded nil
8188 "Was the last copied subtree folded?
8189 This is used to fold the tree back after pasting.")
8191 (defun org-cut-subtree (&optional n)
8192 "Cut the current subtree into the clipboard.
8193 With prefix arg N, cut this many sequential subtrees.
8194 This is a short-hand for marking the subtree and then cutting it."
8195 (interactive "p")
8196 (org-copy-subtree n 'cut))
8198 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8199 "Copy the current subtree it in the clipboard.
8200 With prefix arg N, copy this many sequential subtrees.
8201 This is a short-hand for marking the subtree and then copying it.
8202 If CUT is non-nil, actually cut the subtree.
8203 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8204 of some markers in the region, even if CUT is non-nil. This is
8205 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8206 (interactive "p")
8207 (let (beg end folded (beg0 (point)))
8208 (if (org-called-interactively-p 'any)
8209 (org-back-to-heading nil) ; take what looks like a subtree
8210 (org-back-to-heading t)) ; take what is really there
8211 (setq beg (point))
8212 (skip-chars-forward " \t\r\n")
8213 (save-match-data
8214 (if nosubtrees
8215 (outline-next-heading)
8216 (save-excursion (outline-end-of-heading)
8217 (setq folded (outline-invisible-p)))
8218 (condition-case nil
8219 (org-forward-heading-same-level (1- n) t)
8220 (error nil))
8221 (org-end-of-subtree t t)))
8222 (setq end (point))
8223 (goto-char beg0)
8224 (when (> end beg)
8225 (setq org-subtree-clip-folded folded)
8226 (when (or cut force-store-markers)
8227 (org-save-markers-in-region beg end))
8228 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8229 (setq org-subtree-clip (current-kill 0))
8230 (message "%s: Subtree(s) with %d characters"
8231 (if cut "Cut" "Copied")
8232 (length org-subtree-clip)))))
8234 (defun org-paste-subtree (&optional level tree for-yank)
8235 "Paste the clipboard as a subtree, with modification of headline level.
8236 The entire subtree is promoted or demoted in order to match a new headline
8237 level.
8239 If the cursor is at the beginning of a headline, the same level as
8240 that headline is used to paste the tree.
8242 If not, the new level is derived from the *visible* headings
8243 before and after the insertion point, and taken to be the inferior headline
8244 level of the two. So if the previous visible heading is level 3 and the
8245 next is level 4 (or vice versa), level 4 will be used for insertion.
8246 This makes sure that the subtree remains an independent subtree and does
8247 not swallow low level entries.
8249 You can also force a different level, either by using a numeric prefix
8250 argument, or by inserting the heading marker by hand. For example, if the
8251 cursor is after \"*****\", then the tree will be shifted to level 5.
8253 If optional TREE is given, use this text instead of the kill ring.
8255 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8256 move back over whitespace before inserting, and move point to the end of
8257 the inserted text when done."
8258 (interactive "P")
8259 (setq tree (or tree (and kill-ring (current-kill 0))))
8260 (unless (org-kill-is-subtree-p tree)
8261 (user-error "%s"
8262 (substitute-command-keys
8263 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8264 (org-with-limited-levels
8265 (let* ((visp (not (outline-invisible-p)))
8266 (txt tree)
8267 (^re_ "\\(\\*+\\)[ \t]*")
8268 (old-level (if (string-match org-outline-regexp-bol txt)
8269 (- (match-end 0) (match-beginning 0) 1)
8270 -1))
8271 (force-level (cond (level (prefix-numeric-value level))
8272 ((and (looking-at "[ \t]*$")
8273 (string-match
8274 "^\\*+$" (buffer-substring
8275 (point-at-bol) (point))))
8276 (- (match-end 1) (match-beginning 1)))
8277 ((and (bolp)
8278 (looking-at org-outline-regexp))
8279 (- (match-end 0) (point) 1))))
8280 (previous-level (save-excursion
8281 (condition-case nil
8282 (progn
8283 (outline-previous-visible-heading 1)
8284 (if (looking-at ^re_)
8285 (- (match-end 0) (match-beginning 0) 1)
8287 (error 1))))
8288 (next-level (save-excursion
8289 (condition-case nil
8290 (progn
8291 (or (looking-at org-outline-regexp)
8292 (outline-next-visible-heading 1))
8293 (if (looking-at ^re_)
8294 (- (match-end 0) (match-beginning 0) 1)
8296 (error 1))))
8297 (new-level (or force-level (max previous-level next-level)))
8298 (shift (if (or (= old-level -1)
8299 (= new-level -1)
8300 (= old-level new-level))
8302 (- new-level old-level)))
8303 (delta (if (> shift 0) -1 1))
8304 (func (if (> shift 0) 'org-demote 'org-promote))
8305 (org-odd-levels-only nil)
8306 beg end newend)
8307 ;; Remove the forced level indicator
8308 (if force-level
8309 (delete-region (point-at-bol) (point)))
8310 ;; Paste
8311 (beginning-of-line (if (bolp) 1 2))
8312 (setq beg (point))
8313 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8314 (insert-before-markers txt)
8315 (unless (string-match "\n\\'" txt) (insert "\n"))
8316 (setq newend (point))
8317 (org-reinstall-markers-in-region beg)
8318 (setq end (point))
8319 (goto-char beg)
8320 (skip-chars-forward " \t\n\r")
8321 (setq beg (point))
8322 (if (and (outline-invisible-p) visp)
8323 (save-excursion (outline-show-heading)))
8324 ;; Shift if necessary
8325 (unless (= shift 0)
8326 (save-restriction
8327 (narrow-to-region beg end)
8328 (while (not (= shift 0))
8329 (org-map-region func (point-min) (point-max))
8330 (setq shift (+ delta shift)))
8331 (goto-char (point-min))
8332 (setq newend (point-max))))
8333 (when (or (org-called-interactively-p 'interactive) for-yank)
8334 (message "Clipboard pasted as level %d subtree" new-level))
8335 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8336 kill-ring
8337 (eq org-subtree-clip (current-kill 0))
8338 org-subtree-clip-folded)
8339 ;; The tree was folded before it was killed/copied
8340 (hide-subtree))
8341 (and for-yank (goto-char newend)))))
8343 (defun org-kill-is-subtree-p (&optional txt)
8344 "Check if the current kill is an outline subtree, or a set of trees.
8345 Returns nil if kill does not start with a headline, or if the first
8346 headline level is not the largest headline level in the tree.
8347 So this will actually accept several entries of equal levels as well,
8348 which is OK for `org-paste-subtree'.
8349 If optional TXT is given, check this string instead of the current kill."
8350 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8351 (re (org-get-limited-outline-regexp))
8352 (^re (concat "^" re))
8353 (start-level (and kill
8354 (string-match
8355 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8356 kill)
8357 (- (match-end 2) (match-beginning 2) 1)))
8358 (start (1+ (or (match-beginning 2) -1))))
8359 (if (not start-level)
8360 (progn
8361 nil) ;; does not even start with a heading
8362 (catch 'exit
8363 (while (setq start (string-match ^re kill (1+ start)))
8364 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8365 (throw 'exit nil)))
8366 t))))
8368 (defvar org-markers-to-move nil
8369 "Markers that should be moved with a cut-and-paste operation.
8370 Those markers are stored together with their positions relative to
8371 the start of the region.")
8373 (defun org-save-markers-in-region (beg end)
8374 "Check markers in region.
8375 If these markers are between BEG and END, record their position relative
8376 to BEG, so that after moving the block of text, we can put the markers back
8377 into place.
8378 This function gets called just before an entry or tree gets cut from the
8379 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8380 called immediately, to move the markers with the entries."
8381 (setq org-markers-to-move nil)
8382 (when (featurep 'org-clock)
8383 (org-clock-save-markers-for-cut-and-paste beg end))
8384 (when (featurep 'org-agenda)
8385 (org-agenda-save-markers-for-cut-and-paste beg end)))
8387 (defun org-check-and-save-marker (marker beg end)
8388 "Check if MARKER is between BEG and END.
8389 If yes, remember the marker and the distance to BEG."
8390 (when (and (marker-buffer marker)
8391 (equal (marker-buffer marker) (current-buffer)))
8392 (if (and (>= marker beg) (< marker end))
8393 (push (cons marker (- marker beg)) org-markers-to-move))))
8395 (defun org-reinstall-markers-in-region (beg)
8396 "Move all remembered markers to their position relative to BEG."
8397 (mapc (lambda (x)
8398 (move-marker (car x) (+ beg (cdr x))))
8399 org-markers-to-move)
8400 (setq org-markers-to-move nil))
8402 (defun org-narrow-to-subtree ()
8403 "Narrow buffer to the current subtree."
8404 (interactive)
8405 (save-excursion
8406 (save-match-data
8407 (org-with-limited-levels
8408 (narrow-to-region
8409 (progn (org-back-to-heading t) (point))
8410 (progn (org-end-of-subtree t t)
8411 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8412 (point)))))))
8414 (defun org-narrow-to-block ()
8415 "Narrow buffer to the current block."
8416 (interactive)
8417 (let* ((case-fold-search t)
8418 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8419 "^[ \t]*#\\+end_.*")))
8420 (if blockp
8421 (narrow-to-region (car blockp) (cdr blockp))
8422 (user-error "Not in a block"))))
8424 (eval-when-compile
8425 (defvar org-property-drawer-re))
8427 (defvar org-property-start-re) ;; defined below
8428 (defun org-clone-subtree-with-time-shift (n &optional shift)
8429 "Clone the task (subtree) at point N times.
8430 The clones will be inserted as siblings.
8432 In interactive use, the user will be prompted for the number of
8433 clones to be produced. If the entry has a timestamp, the user
8434 will also be prompted for a time shift, which may be a repeater
8435 as used in time stamps, for example `+3d'. To disable this,
8436 you can call the function with a universal prefix argument.
8438 When a valid repeater is given and the entry contains any time
8439 stamps, the clones will become a sequence in time, with time
8440 stamps in the subtree shifted for each clone produced. If SHIFT
8441 is nil or the empty string, time stamps will be left alone. The
8442 ID property of the original subtree is removed.
8444 If the original subtree did contain time stamps with a repeater,
8445 the following will happen:
8446 - the repeater will be removed in each clone
8447 - an additional clone will be produced, with the current, unshifted
8448 date(s) in the entry.
8449 - the original entry will be placed *after* all the clones, with
8450 repeater intact.
8451 - the start days in the repeater in the original entry will be shifted
8452 to past the last clone.
8453 In this way you can spell out a number of instances of a repeating task,
8454 and still retain the repeater to cover future instances of the task."
8455 (interactive "nNumber of clones to produce: ")
8456 (let ((shift
8457 (or shift
8458 (if (and (not (equal current-prefix-arg '(4)))
8459 (save-excursion
8460 (re-search-forward org-ts-regexp-both
8461 (save-excursion
8462 (org-end-of-subtree t)
8463 (point)) t)))
8464 (read-from-minibuffer
8465 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8466 ""))) ;; No time shift
8467 (n-no-remove -1)
8468 (drawer-re org-drawer-regexp)
8469 beg end template task idprop
8470 shift-n shift-what doshift nmin nmax)
8471 (if (not (and (integerp n) (> n 0)))
8472 (error "Invalid number of replications %s" n))
8473 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8474 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8475 shift)))
8476 (error "Invalid shift specification %s" shift))
8477 (when doshift
8478 (setq shift-n (string-to-number (match-string 1 shift))
8479 shift-what (cdr (assoc (match-string 2 shift)
8480 '(("d" . day) ("w" . week)
8481 ("m" . month) ("y" . year))))))
8482 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8483 (setq nmin 1 nmax n)
8484 (org-back-to-heading t)
8485 (setq beg (point))
8486 (setq idprop (org-entry-get nil "ID"))
8487 (org-end-of-subtree t t)
8488 (or (bolp) (insert "\n"))
8489 (setq end (point))
8490 (setq template (buffer-substring beg end))
8491 (when (and doshift
8492 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8493 (delete-region beg end)
8494 (setq end beg)
8495 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8496 (goto-char end)
8497 (loop for n from nmin to nmax do
8498 ;; prepare clone
8499 (with-temp-buffer
8500 (insert template)
8501 (org-mode)
8502 (goto-char (point-min))
8503 (org-show-subtree)
8504 (and idprop (if org-clone-delete-id
8505 (org-entry-delete nil "ID")
8506 (org-id-get-create t)))
8507 (unless (= n 0)
8508 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8509 (kill-whole-line))
8510 (goto-char (point-min))
8511 (while (re-search-forward drawer-re nil t)
8512 (mapc (lambda (d)
8513 (org-remove-empty-drawer-at d (point))) org-drawers)))
8514 (goto-char (point-min))
8515 (when doshift
8516 (while (re-search-forward org-ts-regexp-both nil t)
8517 (org-timestamp-change (* n shift-n) shift-what))
8518 (unless (= n n-no-remove)
8519 (goto-char (point-min))
8520 (while (re-search-forward org-ts-regexp nil t)
8521 (save-excursion
8522 (goto-char (match-beginning 0))
8523 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8524 (delete-region (match-beginning 1) (match-end 1)))))))
8525 (setq task (buffer-string)))
8526 (insert task))
8527 (goto-char beg)))
8529 ;;; Outline Sorting
8531 (defun org-sort (with-case)
8532 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8533 Optional argument WITH-CASE means sort case-sensitively."
8534 (interactive "P")
8535 (cond
8536 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8537 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8539 (org-call-with-arg 'org-sort-entries with-case))))
8541 (defun org-sort-remove-invisible (s)
8542 "Remove invisible links from string S."
8543 (remove-text-properties 0 (length s) org-rm-props s)
8544 (while (string-match org-bracket-link-regexp s)
8545 (setq s (replace-match (if (match-end 2)
8546 (match-string 3 s)
8547 (match-string 1 s)) t t s)))
8548 (let ((st (format " %s " s)))
8549 (while (string-match org-emph-re st)
8550 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8551 (setq s (substring st 1 -1)))
8554 (defvar org-priority-regexp) ; defined later in the file
8556 (defvar org-after-sorting-entries-or-items-hook nil
8557 "Hook that is run after a bunch of entries or items have been sorted.
8558 When children are sorted, the cursor is in the parent line when this
8559 hook gets called. When a region or a plain list is sorted, the cursor
8560 will be in the first entry of the sorted region/list.")
8562 (defun org-sort-entries
8563 (&optional with-case sorting-type getkey-func compare-func property)
8564 "Sort entries on a certain level of an outline tree.
8565 If there is an active region, the entries in the region are sorted.
8566 Else, if the cursor is before the first entry, sort the top-level items.
8567 Else, the children of the entry at point are sorted.
8569 Sorting can be alphabetically, numerically, by date/time as given by
8570 a time stamp, by a property, by priority order, or by a custom function.
8572 The command prompts for the sorting type unless it has been given to the
8573 function through the SORTING-TYPE argument, which needs to be a character,
8574 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8575 precise meaning of each character:
8577 n Numerically, by converting the beginning of the entry/item to a number.
8578 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8579 o By order of TODO keywords.
8580 t By date/time, either the first active time stamp in the entry, or, if
8581 none exist, by the first inactive one.
8582 s By the scheduled date/time.
8583 d By deadline date/time.
8584 c By creation time, which is assumed to be the first inactive time stamp
8585 at the beginning of a line.
8586 p By priority according to the cookie.
8587 r By the value of a property.
8589 Capital letters will reverse the sort order.
8591 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8592 called with point at the beginning of the record. It must return either
8593 a string or a number that should serve as the sorting key for that record.
8595 Comparing entries ignores case by default. However, with an optional argument
8596 WITH-CASE, the sorting considers case as well.
8598 Sorting is done against the visible part of the headlines, it ignores hidden
8599 links."
8600 (interactive "P")
8601 (let ((case-func (if with-case 'identity 'downcase))
8602 (cmstr
8603 ;; The clock marker is lost when using `sort-subr', let's
8604 ;; store the clocking string.
8605 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8606 (save-excursion
8607 (goto-char org-clock-marker)
8608 (looking-back "^.*") (match-string-no-properties 0))))
8609 start beg end stars re re2
8610 txt what tmp)
8611 ;; Find beginning and end of region to sort
8612 (cond
8613 ((org-region-active-p)
8614 ;; we will sort the region
8615 (setq end (region-end)
8616 what "region")
8617 (goto-char (region-beginning))
8618 (if (not (org-at-heading-p)) (outline-next-heading))
8619 (setq start (point)))
8620 ((or (org-at-heading-p)
8621 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8622 ;; we will sort the children of the current headline
8623 (org-back-to-heading)
8624 (setq start (point)
8625 end (progn (org-end-of-subtree t t)
8626 (or (bolp) (insert "\n"))
8627 (org-back-over-empty-lines)
8628 (point))
8629 what "children")
8630 (goto-char start)
8631 (show-subtree)
8632 (outline-next-heading))
8634 ;; we will sort the top-level entries in this file
8635 (goto-char (point-min))
8636 (or (org-at-heading-p) (outline-next-heading))
8637 (setq start (point))
8638 (goto-char (point-max))
8639 (beginning-of-line 1)
8640 (when (looking-at ".*?\\S-")
8641 ;; File ends in a non-white line
8642 (end-of-line 1)
8643 (insert "\n"))
8644 (setq end (point-max))
8645 (setq what "top-level")
8646 (goto-char start)
8647 (show-all)))
8649 (setq beg (point))
8650 (if (>= beg end) (user-error "Nothing to sort"))
8652 (looking-at "\\(\\*+\\)")
8653 (setq stars (match-string 1)
8654 re (concat "^" (regexp-quote stars) " +")
8655 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8656 txt (buffer-substring beg end))
8657 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8658 (if (and (not (equal stars "*")) (string-match re2 txt))
8659 (user-error "Region to sort contains a level above the first entry"))
8661 (unless sorting-type
8662 (message
8663 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8664 [t]ime [s]cheduled [d]eadline [c]reated
8665 A/N/P/R/O/F/T/S/D/C means reversed:"
8666 what)
8667 (setq sorting-type (read-char-exclusive))
8669 (unless getkey-func
8670 (and (= (downcase sorting-type) ?f)
8671 (setq getkey-func
8672 (org-icompleting-read "Sort using function: "
8673 obarray 'fboundp t nil nil))
8674 (setq getkey-func (intern getkey-func))))
8676 (and (= (downcase sorting-type) ?r)
8677 (not property)
8678 (setq property
8679 (org-icompleting-read "Property: "
8680 (mapcar 'list (org-buffer-property-keys t))
8681 nil t))))
8683 (message "Sorting entries...")
8685 (save-restriction
8686 (narrow-to-region start end)
8687 (let ((dcst (downcase sorting-type))
8688 (case-fold-search nil)
8689 (now (current-time)))
8690 (sort-subr
8691 (/= dcst sorting-type)
8692 ;; This function moves to the beginning character of the "record" to
8693 ;; be sorted.
8694 (lambda nil
8695 (if (re-search-forward re nil t)
8696 (goto-char (match-beginning 0))
8697 (goto-char (point-max))))
8698 ;; This function moves to the last character of the "record" being
8699 ;; sorted.
8700 (lambda nil
8701 (save-match-data
8702 (condition-case nil
8703 (outline-forward-same-level 1)
8704 (error
8705 (goto-char (point-max))))))
8706 ;; This function returns the value that gets sorted against.
8707 (lambda nil
8708 (cond
8709 ((= dcst ?n)
8710 (if (looking-at org-complex-heading-regexp)
8711 (string-to-number (org-sort-remove-invisible (match-string 4)))
8712 nil))
8713 ((= dcst ?a)
8714 (if (looking-at org-complex-heading-regexp)
8715 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8716 nil))
8717 ((= dcst ?t)
8718 (let ((end (save-excursion (outline-next-heading) (point))))
8719 (if (or (re-search-forward org-ts-regexp end t)
8720 (re-search-forward org-ts-regexp-both end t))
8721 (org-time-string-to-seconds (match-string 0))
8722 (org-float-time now))))
8723 ((= dcst ?c)
8724 (let ((end (save-excursion (outline-next-heading) (point))))
8725 (if (re-search-forward
8726 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8727 end t)
8728 (org-time-string-to-seconds (match-string 0))
8729 (org-float-time now))))
8730 ((= dcst ?s)
8731 (let ((end (save-excursion (outline-next-heading) (point))))
8732 (if (re-search-forward org-scheduled-time-regexp end t)
8733 (org-time-string-to-seconds (match-string 1))
8734 (org-float-time now))))
8735 ((= dcst ?d)
8736 (let ((end (save-excursion (outline-next-heading) (point))))
8737 (if (re-search-forward org-deadline-time-regexp end t)
8738 (org-time-string-to-seconds (match-string 1))
8739 (org-float-time now))))
8740 ((= dcst ?p)
8741 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8742 (string-to-char (match-string 2))
8743 org-default-priority))
8744 ((= dcst ?r)
8745 (or (org-entry-get nil property) ""))
8746 ((= dcst ?o)
8747 (if (looking-at org-complex-heading-regexp)
8748 (- 9999 (length (member (match-string 2)
8749 org-todo-keywords-1)))))
8750 ((= dcst ?f)
8751 (if getkey-func
8752 (progn
8753 (setq tmp (funcall getkey-func))
8754 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8755 tmp)
8756 (error "Invalid key function `%s'" getkey-func)))
8757 (t (error "Invalid sorting type `%c'" sorting-type))))
8759 (cond
8760 ((= dcst ?a) 'string<)
8761 ((= dcst ?f) compare-func)
8762 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8763 (run-hooks 'org-after-sorting-entries-or-items-hook)
8764 ;; Reset the clock marker if needed
8765 (when cmstr
8766 (save-excursion
8767 (goto-char start)
8768 (search-forward cmstr nil t)
8769 (move-marker org-clock-marker (point))))
8770 (message "Sorting entries...done")))
8772 (defun org-do-sort (table what &optional with-case sorting-type)
8773 "Sort TABLE of WHAT according to SORTING-TYPE.
8774 The user will be prompted for the SORTING-TYPE if the call to this
8775 function does not specify it. WHAT is only for the prompt, to indicate
8776 what is being sorted. The sorting key will be extracted from
8777 the car of the elements of the table.
8778 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8779 (unless sorting-type
8780 (message
8781 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8782 what)
8783 (setq sorting-type (read-char-exclusive)))
8784 (let ((dcst (downcase sorting-type))
8785 extractfun comparefun)
8786 ;; Define the appropriate functions
8787 (cond
8788 ((= dcst ?n)
8789 (setq extractfun 'string-to-number
8790 comparefun (if (= dcst sorting-type) '< '>)))
8791 ((= dcst ?a)
8792 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8793 (lambda(x) (downcase (org-sort-remove-invisible x))))
8794 comparefun (if (= dcst sorting-type)
8795 'string<
8796 (lambda (a b) (and (not (string< a b))
8797 (not (string= a b)))))))
8798 ((= dcst ?t)
8799 (setq extractfun
8800 (lambda (x)
8801 (if (or (string-match org-ts-regexp x)
8802 (string-match org-ts-regexp-both x))
8803 (org-float-time
8804 (org-time-string-to-time (match-string 0 x)))
8806 comparefun (if (= dcst sorting-type) '< '>)))
8807 (t (error "Invalid sorting type `%c'" sorting-type)))
8809 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8810 table)
8811 (lambda (a b) (funcall comparefun (car a) (car b))))))
8814 ;;; The orgstruct minor mode
8816 ;; Define a minor mode which can be used in other modes in order to
8817 ;; integrate the org-mode structure editing commands.
8819 ;; This is really a hack, because the org-mode structure commands use
8820 ;; keys which normally belong to the major mode. Here is how it
8821 ;; works: The minor mode defines all the keys necessary to operate the
8822 ;; structure commands, but wraps the commands into a function which
8823 ;; tests if the cursor is currently at a headline or a plain list
8824 ;; item. If that is the case, the structure command is used,
8825 ;; temporarily setting many Org-mode variables like regular
8826 ;; expressions for filling etc. However, when any of those keys is
8827 ;; used at a different location, function uses `key-binding' to look
8828 ;; up if the key has an associated command in another currently active
8829 ;; keymap (minor modes, major mode, global), and executes that
8830 ;; command. There might be problems if any of the keys is otherwise
8831 ;; used as a prefix key.
8833 (defcustom orgstruct-heading-prefix-regexp ""
8834 "Regexp that matches the custom prefix of Org headlines in
8835 orgstruct(++)-mode."
8836 :group 'org
8837 :version "24.4"
8838 :package-version '(Org . "8.3")
8839 :type 'regexp)
8840 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8842 (defcustom orgstruct-setup-hook nil
8843 "Hook run after orgstruct-mode-map is filled."
8844 :group 'org
8845 :version "24.4"
8846 :package-version '(Org . "8.0")
8847 :type 'hook)
8849 (defvar orgstruct-initialized nil)
8851 (defvar org-local-vars nil
8852 "List of local variables, for use by `orgstruct-mode'.")
8854 ;;;###autoload
8855 (define-minor-mode orgstruct-mode
8856 "Toggle the minor mode `orgstruct-mode'.
8857 This mode is for using Org-mode structure commands in other
8858 modes. The following keys behave as if Org-mode were active, if
8859 the cursor is on a headline, or on a plain list item (both as
8860 defined by Org-mode)."
8861 nil " OrgStruct" (make-sparse-keymap)
8862 (funcall (if orgstruct-mode
8863 'add-to-invisibility-spec
8864 'remove-from-invisibility-spec)
8865 '(outline . t))
8866 (when orgstruct-mode
8867 (org-load-modules-maybe)
8868 (unless orgstruct-initialized
8869 (orgstruct-setup)
8870 (setq orgstruct-initialized t))))
8872 ;;;###autoload
8873 (defun turn-on-orgstruct ()
8874 "Unconditionally turn on `orgstruct-mode'."
8875 (orgstruct-mode 1))
8877 (defvar org-fb-vars nil)
8878 (make-variable-buffer-local 'org-fb-vars)
8879 (defun orgstruct++-mode (&optional arg)
8880 "Toggle `orgstruct-mode', the enhanced version of it.
8881 In addition to setting orgstruct-mode, this also exports all
8882 indentation and autofilling variables from org-mode into the
8883 buffer. It will also recognize item context in multiline items."
8884 (interactive "P")
8885 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8886 (if (< arg 1)
8887 (progn (orgstruct-mode -1)
8888 (mapc (lambda(v)
8889 (org-set-local (car v)
8890 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8891 org-fb-vars))
8892 (orgstruct-mode 1)
8893 (setq org-fb-vars nil)
8894 (unless org-local-vars
8895 (setq org-local-vars (org-get-local-variables)))
8896 (let (var val)
8897 (mapc
8898 (lambda (x)
8899 (when (string-match
8900 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8901 (symbol-name (car x)))
8902 (setq var (car x) val (nth 1 x))
8903 (push (list var `(quote ,(eval var))) org-fb-vars)
8904 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8905 org-local-vars)
8906 (org-set-local 'orgstruct-is-++ t))))
8908 (defvar orgstruct-is-++ nil
8909 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8910 (make-variable-buffer-local 'orgstruct-is-++)
8912 ;;;###autoload
8913 (defun turn-on-orgstruct++ ()
8914 "Unconditionally turn on `orgstruct++-mode'."
8915 (orgstruct++-mode 1))
8917 (defun orgstruct-error ()
8918 "Error when there is no default binding for a structure key."
8919 (interactive)
8920 (funcall (if (fboundp 'user-error)
8921 'user-error
8922 'error)
8923 "This key has no function outside structure elements"))
8925 (defun orgstruct-setup ()
8926 "Setup orgstruct keymap."
8927 (dolist (cell '((org-demote . t)
8928 (org-metaleft . t)
8929 (org-metaright . t)
8930 (org-promote . t)
8931 (org-shiftmetaleft . t)
8932 (org-shiftmetaright . t)
8933 org-backward-element
8934 org-backward-heading-same-level
8935 org-ctrl-c-ret
8936 org-ctrl-c-minus
8937 org-ctrl-c-star
8938 org-cycle
8939 org-forward-heading-same-level
8940 org-insert-heading
8941 org-insert-heading-respect-content
8942 org-kill-note-or-show-branches
8943 org-mark-subtree
8944 org-meta-return
8945 org-metadown
8946 org-metaup
8947 org-narrow-to-subtree
8948 org-promote-subtree
8949 org-reveal
8950 org-shiftdown
8951 org-shiftleft
8952 org-shiftmetadown
8953 org-shiftmetaup
8954 org-shiftright
8955 org-shifttab
8956 org-shifttab
8957 org-shiftup
8958 org-show-subtree
8959 org-sort
8960 org-up-element
8961 outline-demote
8962 outline-next-visible-heading
8963 outline-previous-visible-heading
8964 outline-promote
8965 outline-up-heading
8966 show-children))
8967 (let ((f (or (car-safe cell) cell))
8968 (disable-when-heading-prefix (cdr-safe cell)))
8969 (when (fboundp f)
8970 (let ((new-bindings))
8971 (dolist (binding (nconc (where-is-internal f org-mode-map)
8972 (where-is-internal f outline-mode-map)))
8973 (push binding new-bindings)
8974 ;; TODO use local-function-key-map
8975 (dolist (rep '(("<tab>" . "TAB")
8976 ("<return>" . "RET")
8977 ("<escape>" . "ESC")
8978 ("<delete>" . "DEL")))
8979 (setq binding (read-kbd-macro
8980 (let ((case-fold-search))
8981 (replace-regexp-in-string
8982 (regexp-quote (cdr rep))
8983 (car rep)
8984 (key-description binding)))))
8985 (pushnew binding new-bindings :test 'equal)))
8986 (dolist (binding new-bindings)
8987 (let ((key (lookup-key orgstruct-mode-map binding)))
8988 (when (or (not key) (numberp key))
8989 (condition-case nil
8990 (org-defkey orgstruct-mode-map
8991 binding
8992 (orgstruct-make-binding f binding disable-when-heading-prefix))
8993 (error nil)))))))))
8994 (run-hooks 'orgstruct-setup-hook))
8996 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
8997 "Create a function for binding in the structure minor mode.
8998 FUN is the command to call inside a table. KEY is the key that
8999 should be checked in for a command to execute outside of tables.
9000 Non-nil `disable-when-heading-prefix' means to disable the command
9001 if `orgstruct-heading-prefix-regexp' is not empty."
9002 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9003 (let ((nname name)
9004 (i 0))
9005 (while (fboundp (intern nname))
9006 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9007 (setq name (intern nname)))
9008 (eval
9009 (let ((bindings '((org-heading-regexp
9010 (concat "^"
9011 orgstruct-heading-prefix-regexp
9012 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9013 (org-outline-regexp
9014 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9015 (org-outline-regexp-bol
9016 (concat "^" org-outline-regexp))
9017 (outline-regexp org-outline-regexp)
9018 (outline-heading-end-regexp "\n")
9019 (outline-level 'org-outline-level)
9020 (outline-heading-alist))))
9021 `(defun ,name (arg)
9022 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9023 "Outside of structure, run the binding of `"
9024 (key-description key) "'."
9025 (when disable-when-heading-prefix
9026 (concat
9027 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9028 "back to the default binding due to limitations of Org's implementation of\n"
9029 "`" (symbol-name fun) "'.")))
9030 (interactive "p")
9031 (let* ((disable
9032 ,(and disable-when-heading-prefix
9033 '(not (string= orgstruct-heading-prefix-regexp ""))))
9034 (fallback
9035 (or disable
9036 (not
9037 (let* ,bindings
9038 (org-context-p 'headline 'item
9039 ,(when (memq fun
9040 '(org-insert-heading
9041 org-insert-heading-respect-content
9042 org-meta-return))
9043 '(when orgstruct-is-++
9044 'item-body))))))))
9045 (if fallback
9046 (let* ((orgstruct-mode)
9047 (binding
9048 (loop with key = ,key
9049 for rep in
9050 '(nil
9051 ("<\\([^>]*\\)tab>" . "\\1TAB")
9052 ("<\\([^>]*\\)return>" . "\\1RET")
9053 ("<\\([^>]*\\)escape>" . "\\1ESC")
9054 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9056 (when rep
9057 (setq key (read-kbd-macro
9058 (let ((case-fold-search))
9059 (replace-regexp-in-string
9060 (car rep)
9061 (cdr rep)
9062 (key-description key))))))
9063 thereis (key-binding key))))
9064 (if (keymapp binding)
9065 (set-temporary-overlay-map binding)
9066 (let ((func (or binding
9067 (unless disable
9068 'orgstruct-error))))
9069 (when func
9070 (call-interactively func)))))
9071 (org-run-like-in-org-mode
9072 (lambda ()
9073 (interactive)
9074 (let* ,bindings
9075 (call-interactively ',fun)))))))))
9076 name))
9078 (defun org-contextualize-keys (alist contexts)
9079 "Return valid elements in ALIST depending on CONTEXTS.
9081 `org-agenda-custom-commands' or `org-capture-templates' are the
9082 values used for ALIST, and `org-agenda-custom-commands-contexts'
9083 or `org-capture-templates-contexts' are the associated contexts
9084 definitions."
9085 (let ((contexts
9086 ;; normalize contexts
9087 (mapcar
9088 (lambda(c) (cond ((listp (cadr c))
9089 (list (car c) (car c) (cadr c)))
9090 ((string= "" (cadr c))
9091 (list (car c) (car c) (caddr c)))
9092 (t c))) contexts))
9093 (a alist) c r s)
9094 ;; loop over all commands or templates
9095 (while (setq c (pop a))
9096 (let (vrules repl)
9097 (cond
9098 ((not (assoc (car c) contexts))
9099 (push c r))
9100 ((and (assoc (car c) contexts)
9101 (setq vrules (org-contextualize-validate-key
9102 (car c) contexts)))
9103 (mapc (lambda (vr)
9104 (when (not (equal (car vr) (cadr vr)))
9105 (setq repl vr))) vrules)
9106 (if (not repl) (push c r)
9107 (push (cadr repl) s)
9108 (push
9109 (cons (car c)
9110 (cdr (or (assoc (cadr repl) alist)
9111 (error "Undefined key `%s' as contextual replacement for `%s'"
9112 (cadr repl) (car c)))))
9113 r))))))
9114 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9115 (delq
9117 (delete-dups
9118 (mapcar (lambda (x)
9119 (let ((tpl (car x)))
9120 (when (not (delq
9122 (mapcar (lambda(y)
9123 (equal y tpl)) s))) x)))
9124 (reverse r))))))
9126 (defun org-contextualize-validate-key (key contexts)
9127 "Check CONTEXTS for agenda or capture KEY."
9128 (let (r rr res)
9129 (while (setq r (pop contexts))
9130 (mapc
9131 (lambda (rr)
9132 (when
9133 (and (equal key (car r))
9134 (if (functionp rr) (funcall rr)
9135 (or (and (eq (car rr) 'in-file)
9136 (buffer-file-name)
9137 (string-match (cdr rr) (buffer-file-name)))
9138 (and (eq (car rr) 'in-mode)
9139 (string-match (cdr rr) (symbol-name major-mode)))
9140 (and (eq (car rr) 'in-buffer)
9141 (string-match (cdr rr) (buffer-name)))
9142 (when (and (eq (car rr) 'not-in-file)
9143 (buffer-file-name))
9144 (not (string-match (cdr rr) (buffer-file-name))))
9145 (when (eq (car rr) 'not-in-mode)
9146 (not (string-match (cdr rr) (symbol-name major-mode))))
9147 (when (eq (car rr) 'not-in-buffer)
9148 (not (string-match (cdr rr) (buffer-name)))))))
9149 (push r res)))
9150 (car (last r))))
9151 (delete-dups (delq nil res))))
9153 (defun org-context-p (&rest contexts)
9154 "Check if local context is any of CONTEXTS.
9155 Possible values in the list of contexts are `table', `headline', and `item'."
9156 (let ((pos (point)))
9157 (goto-char (point-at-bol))
9158 (prog1 (or (and (memq 'table contexts)
9159 (looking-at "[ \t]*|"))
9160 (and (memq 'headline contexts)
9161 (looking-at org-outline-regexp))
9162 (and (memq 'item contexts)
9163 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9164 (and (memq 'item-body contexts)
9165 (org-in-item-p)))
9166 (goto-char pos))))
9168 (defun org-get-local-variables ()
9169 "Return a list of all local variables in an Org mode buffer."
9170 (let (varlist)
9171 (with-current-buffer (get-buffer-create "*Org tmp*")
9172 (erase-buffer)
9173 (org-mode)
9174 (setq varlist (buffer-local-variables)))
9175 (kill-buffer "*Org tmp*")
9176 (delq nil
9177 (mapcar
9178 (lambda (x)
9179 (setq x
9180 (if (symbolp x)
9181 (list x)
9182 (list (car x) (cdr x))))
9183 (if (and (not (get (car x) 'org-state))
9184 (string-match
9185 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9186 (symbol-name (car x))))
9187 x nil))
9188 varlist))))
9190 (defun org-clone-local-variables (from-buffer &optional regexp)
9191 "Clone local variables from FROM-BUFFER.
9192 Optional argument REGEXP selects variables to clone."
9193 (mapc
9194 (lambda (pair)
9195 (and (symbolp (car pair))
9196 (or (null regexp)
9197 (string-match regexp (symbol-name (car pair))))
9198 (set (make-local-variable (car pair))
9199 (cdr pair))))
9200 (buffer-local-variables from-buffer)))
9202 ;;;###autoload
9203 (defun org-run-like-in-org-mode (cmd)
9204 "Run a command, pretending that the current buffer is in Org-mode.
9205 This will temporarily bind local variables that are typically bound in
9206 Org-mode to the values they have in Org-mode, and then interactively
9207 call CMD."
9208 (org-load-modules-maybe)
9209 (unless org-local-vars
9210 (setq org-local-vars (org-get-local-variables)))
9211 (let (binds)
9212 (dolist (var org-local-vars)
9213 (when (or (not (boundp (car var)))
9214 (eq (symbol-value (car var))
9215 (default-value (car var))))
9216 (push (list (car var) `(quote ,(cadr var))) binds)))
9217 (eval `(let ,binds
9218 (call-interactively (quote ,cmd))))))
9220 ;;;; Archiving
9222 (defun org-get-category (&optional pos force-refresh)
9223 "Get the category applying to position POS."
9224 (save-match-data
9225 (if force-refresh (org-refresh-category-properties))
9226 (let ((pos (or pos (point))))
9227 (or (get-text-property pos 'org-category)
9228 (progn (org-refresh-category-properties)
9229 (get-text-property pos 'org-category))))))
9231 (defun org-refresh-category-properties ()
9232 "Refresh category text properties in the buffer."
9233 (let ((case-fold-search t)
9234 (inhibit-read-only t)
9235 (def-cat (cond
9236 ((null org-category)
9237 (if buffer-file-name
9238 (file-name-sans-extension
9239 (file-name-nondirectory buffer-file-name))
9240 "???"))
9241 ((symbolp org-category) (symbol-name org-category))
9242 (t org-category)))
9243 beg end cat pos optionp)
9244 (org-with-silent-modifications
9245 (save-excursion
9246 (save-restriction
9247 (widen)
9248 (goto-char (point-min))
9249 (put-text-property (point) (point-max) 'org-category def-cat)
9250 (while (re-search-forward
9251 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9252 (setq pos (match-end 0)
9253 optionp (equal (char-after (match-beginning 0)) ?#)
9254 cat (org-trim (match-string 2)))
9255 (if optionp
9256 (setq beg (point-at-bol) end (point-max))
9257 (org-back-to-heading t)
9258 (setq beg (point) end (org-end-of-subtree t t)))
9259 (put-text-property beg end 'org-category cat)
9260 (put-text-property beg end 'org-category-position beg)
9261 (goto-char pos)))))))
9263 (defun org-refresh-properties (dprop tprop)
9264 "Refresh buffer text properties.
9265 DPROP is the drawer property and TPROP is the corresponding text
9266 property to set."
9267 (let ((case-fold-search t)
9268 (inhibit-read-only t) p)
9269 (org-with-silent-modifications
9270 (save-excursion
9271 (save-restriction
9272 (widen)
9273 (goto-char (point-min))
9274 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9275 (setq p (org-match-string-no-properties 1))
9276 (save-excursion
9277 (org-back-to-heading t)
9278 (put-text-property
9279 (point-at-bol) (org-end-of-subtree t t) tprop p))))))))
9282 ;;;; Link Stuff
9284 ;;; Link abbreviations
9286 (defun org-link-expand-abbrev (link)
9287 "Apply replacements as defined in `org-link-abbrev-alist'."
9288 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9289 (let* ((key (match-string 1 link))
9290 (as (or (assoc key org-link-abbrev-alist-local)
9291 (assoc key org-link-abbrev-alist)))
9292 (tag (and (match-end 2) (match-string 3 link)))
9293 rpl)
9294 (if (not as)
9295 link
9296 (setq rpl (cdr as))
9297 (cond
9298 ((symbolp rpl) (funcall rpl tag))
9299 ((string-match "%(\\([^)]+\\))" rpl)
9300 (replace-match
9301 (save-match-data
9302 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9303 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9304 ((string-match "%h" rpl)
9305 (replace-match (url-hexify-string (or tag "")) t t rpl))
9306 (t (concat rpl tag)))))
9307 link))
9309 ;;; Storing and inserting links
9311 (defvar org-insert-link-history nil
9312 "Minibuffer history for links inserted with `org-insert-link'.")
9314 (defvar org-stored-links nil
9315 "Contains the links stored with `org-store-link'.")
9317 (defvar org-store-link-plist nil
9318 "Plist with info about the most recently link created with `org-store-link'.")
9320 (defvar org-link-protocols nil
9321 "Link protocols added to Org-mode using `org-add-link-type'.")
9323 (defvar org-store-link-functions nil
9324 "List of functions that are called to create and store a link.
9325 Each function will be called in turn until one returns a non-nil
9326 value. Each function should check if it is responsible for creating
9327 this link (for example by looking at the major mode).
9328 If not, it must exit and return nil.
9329 If yes, it should return a non-nil value after a calling
9330 `org-store-link-props' with a list of properties and values.
9331 Special properties are:
9333 :type The link prefix, like \"http\". This must be given.
9334 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9335 This is obligatory as well.
9336 :description Optional default description for the second pair
9337 of brackets in an Org-mode link. The user can still change
9338 this when inserting this link into an Org-mode buffer.
9340 In addition to these, any additional properties can be specified
9341 and then used in capture templates.")
9343 (defun org-add-link-type (type &optional follow export)
9344 "Add TYPE to the list of `org-link-types'.
9345 Re-compute all regular expressions depending on `org-link-types'
9347 FOLLOW and EXPORT are two functions.
9349 FOLLOW should take the link path as the single argument and do whatever
9350 is necessary to follow the link, for example find a file or display
9351 a mail message.
9353 EXPORT should format the link path for export to one of the export formats.
9354 It should be a function accepting three arguments:
9356 path the path of the link, the text after the prefix (like \"http:\")
9357 desc the description of the link, if any, or a description added by
9358 org-export-normalize-links if there is none
9359 format the export format, a symbol like `html' or `latex' or `ascii'..
9361 The function may use the FORMAT information to return different values
9362 depending on the format. The return value will be put literally into
9363 the exported file. If the return value is nil, this means Org should
9364 do what it normally does with links which do not have EXPORT defined.
9366 Org-mode has a built-in default for exporting links. If you are happy with
9367 this default, there is no need to define an export function for the link
9368 type. For a simple example of an export function, see `org-bbdb.el'."
9369 (add-to-list 'org-link-types type t)
9370 (org-make-link-regexps)
9371 (if (assoc type org-link-protocols)
9372 (setcdr (assoc type org-link-protocols) (list follow export))
9373 (push (list type follow export) org-link-protocols)))
9375 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9376 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9378 ;;;###autoload
9379 (defun org-store-link (arg)
9380 "\\<org-mode-map>Store an org-link to the current location.
9381 This link is added to `org-stored-links' and can later be inserted
9382 into an org-buffer with \\[org-insert-link].
9384 For some link types, a prefix arg is interpreted.
9385 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9386 For file links, arg negates `org-context-in-file-links'.
9388 A double prefix arg force skipping storing functions that are not
9389 part of Org's core.
9391 A triple prefix arg force storing a link for each line in the
9392 active region."
9393 (interactive "P")
9394 (org-load-modules-maybe)
9395 (if (and (equal arg '(64)) (org-region-active-p))
9396 (save-excursion
9397 (let ((end (region-end)))
9398 (goto-char (region-beginning))
9399 (set-mark (point))
9400 (while (< (point-at-eol) end)
9401 (move-end-of-line 1) (activate-mark)
9402 (let (current-prefix-arg)
9403 (call-interactively 'org-store-link))
9404 (move-beginning-of-line 2)
9405 (set-mark (point)))))
9406 (org-with-limited-levels
9407 (setq org-store-link-plist nil)
9408 (let (link cpltxt desc description search
9409 txt custom-id agenda-link sfuns sfunsn)
9410 (cond
9412 ;; Store a link using an external link type
9413 ((and (not (equal arg '(16)))
9414 (setq sfuns
9415 (delq
9416 nil (mapcar (lambda (f)
9417 (let (fs) (if (funcall f) (push f fs))))
9418 org-store-link-functions))
9419 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9420 (or (and (cdr sfuns)
9421 (funcall (intern
9422 (completing-read
9423 "Which function for creating the link? "
9424 sfunsn t (car sfunsn)))))
9425 (funcall (caar sfuns)))
9426 (setq link (plist-get org-store-link-plist :link)
9427 desc (or (plist-get org-store-link-plist
9428 :description) link))))
9430 ;; Store a link from a source code buffer
9431 ((org-src-edit-buffer-p)
9432 (let (label gc)
9433 (while (or (not label)
9434 (save-excursion
9435 (save-restriction
9436 (widen)
9437 (goto-char (point-min))
9438 (re-search-forward
9439 (regexp-quote (format org-coderef-label-format label))
9440 nil t))))
9441 (when label (message "Label exists already") (sit-for 2))
9442 (setq label (read-string "Code line label: " label)))
9443 (end-of-line 1)
9444 (setq link (format org-coderef-label-format label))
9445 (setq gc (- 79 (length link)))
9446 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9447 (insert link)
9448 (setq link (concat "(" label ")") desc nil)))
9450 ;; We are in the agenda, link to referenced location
9451 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9452 (let ((m (or (get-text-property (point) 'org-hd-marker)
9453 (get-text-property (point) 'org-marker))))
9454 (when m
9455 (org-with-point-at m
9456 (setq agenda-link
9457 (if (org-called-interactively-p 'any)
9458 (call-interactively 'org-store-link)
9459 (org-store-link nil)))))))
9461 ((eq major-mode 'calendar-mode)
9462 (let ((cd (calendar-cursor-to-date)))
9463 (setq link
9464 (format-time-string
9465 (car org-time-stamp-formats)
9466 (apply 'encode-time
9467 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9468 nil nil nil))))
9469 (org-store-link-props :type "calendar" :date cd)))
9471 ((eq major-mode 'help-mode)
9472 (setq link (concat "help:" (save-excursion
9473 (goto-char (point-min))
9474 (looking-at "^[^ ]+")
9475 (match-string 0))))
9476 (org-store-link-props :type "help"))
9478 ((eq major-mode 'w3-mode)
9479 (setq cpltxt (if (and (buffer-name)
9480 (not (string-match "Untitled" (buffer-name))))
9481 (buffer-name)
9482 (url-view-url t))
9483 link (url-view-url t))
9484 (org-store-link-props :type "w3" :url (url-view-url t)))
9486 ((eq major-mode 'image-mode)
9487 (setq cpltxt (concat "file:"
9488 (abbreviate-file-name buffer-file-name))
9489 link cpltxt)
9490 (org-store-link-props :type "image" :file buffer-file-name))
9492 ;; In dired, store a link to the file of the current line
9493 ((eq major-mode 'dired-mode)
9494 (let ((file (dired-get-filename nil t)))
9495 (setq file (if file
9496 (abbreviate-file-name
9497 (expand-file-name (dired-get-filename nil t)))
9498 ;; otherwise, no file so use current directory.
9499 default-directory))
9500 (setq cpltxt (concat "file:" file)
9501 link cpltxt)))
9503 ((setq search (run-hook-with-args-until-success
9504 'org-create-file-search-functions))
9505 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9506 "::" search))
9507 (setq cpltxt (or description link)))
9509 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9510 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9511 (cond
9512 ;; Store a link using the target at point
9513 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9514 (setq cpltxt
9515 (concat "file:"
9516 (abbreviate-file-name
9517 (buffer-file-name (buffer-base-buffer)))
9518 "::" (match-string 1))
9519 link cpltxt))
9520 ((and (featurep 'org-id)
9521 (or (eq org-id-link-to-org-use-id t)
9522 (and (org-called-interactively-p 'any)
9523 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9524 (and (eq org-id-link-to-org-use-id
9525 'create-if-interactive-and-no-custom-id)
9526 (not custom-id))))
9527 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9528 ;; Store a link using the ID at point
9529 (setq link (condition-case nil
9530 (prog1 (org-id-store-link)
9531 (setq desc (plist-get org-store-link-plist
9532 :description)))
9533 (error
9534 ;; Probably before first headline, link only to file
9535 (concat "file:"
9536 (abbreviate-file-name
9537 (buffer-file-name (buffer-base-buffer))))))))
9539 ;; Just link to current headline
9540 (setq cpltxt (concat "file:"
9541 (abbreviate-file-name
9542 (buffer-file-name (buffer-base-buffer)))))
9543 ;; Add a context search string
9544 (when (org-xor org-context-in-file-links arg)
9545 (let* ((ee (org-element-at-point))
9546 (et (org-element-type ee))
9547 (ev (plist-get (cadr ee) :value))
9548 (ek (plist-get (cadr ee) :key))
9549 (eok (and (stringp ek) (string-match "name" ek))))
9550 (setq txt (cond
9551 ((org-at-heading-p) nil)
9552 ((and (eq et 'keyword) eok) ev)
9553 ((org-region-active-p)
9554 (buffer-substring (region-beginning) (region-end)))))
9555 (when (or (null txt) (string-match "\\S-" txt))
9556 (setq cpltxt
9557 (concat cpltxt "::"
9558 (condition-case nil
9559 (org-make-org-heading-search-string txt)
9560 (error "")))
9561 desc (or (and (eq et 'keyword) eok ev)
9562 (nth 4 (ignore-errors (org-heading-components)))
9563 "NONE")))))
9564 (if (string-match "::\\'" cpltxt)
9565 (setq cpltxt (substring cpltxt 0 -2)))
9566 (setq link cpltxt))))
9568 ((buffer-file-name (buffer-base-buffer))
9569 ;; Just link to this file here.
9570 (setq cpltxt (concat "file:"
9571 (abbreviate-file-name
9572 (buffer-file-name (buffer-base-buffer)))))
9573 ;; Add a context string.
9574 (when (org-xor org-context-in-file-links arg)
9575 (setq txt (if (org-region-active-p)
9576 (buffer-substring (region-beginning) (region-end))
9577 (buffer-substring (point-at-bol) (point-at-eol))))
9578 ;; Only use search option if there is some text.
9579 (when (string-match "\\S-" txt)
9580 (setq cpltxt
9581 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9582 desc "NONE")))
9583 (setq link cpltxt))
9585 ((org-called-interactively-p 'interactive)
9586 (user-error "No method for storing a link from this buffer"))
9588 (t (setq link nil)))
9590 ;; We're done setting link and desc, clean up
9591 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9592 (setq link (or link cpltxt)
9593 desc (or desc cpltxt))
9594 (cond ((equal desc "NONE") (setq desc nil))
9595 ((string-match org-bracket-link-analytic-regexp desc)
9596 (let ((d0 (match-string 3 desc))
9597 (p0 (match-string 5 desc)))
9598 (setq desc
9599 (replace-regexp-in-string
9600 org-bracket-link-regexp
9601 (concat (or p0 d0)
9602 (if (equal (length (match-string 0 desc))
9603 (length desc)) "*" "")) desc)))))
9605 ;; Return the link
9606 (if (not (and (or (org-called-interactively-p 'any)
9607 executing-kbd-macro) link))
9608 (or agenda-link (and link (org-make-link-string link desc)))
9609 (push (list link desc) org-stored-links)
9610 (message "Stored: %s" (or desc link))
9611 (when custom-id
9612 (setq link (concat "file:" (abbreviate-file-name
9613 (buffer-file-name)) "::#" custom-id))
9614 (push (list link desc) org-stored-links)))))))
9616 (defun org-store-link-props (&rest plist)
9617 "Store link properties, extract names and addresses."
9618 (let (x adr)
9619 (when (setq x (plist-get plist :from))
9620 (setq adr (mail-extract-address-components x))
9621 (setq plist (plist-put plist :fromname (car adr)))
9622 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9623 (when (setq x (plist-get plist :to))
9624 (setq adr (mail-extract-address-components x))
9625 (setq plist (plist-put plist :toname (car adr)))
9626 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9627 (let ((from (plist-get plist :from))
9628 (to (plist-get plist :to)))
9629 (when (and from to org-from-is-user-regexp)
9630 (setq plist
9631 (plist-put plist :fromto
9632 (if (string-match org-from-is-user-regexp from)
9633 (concat "to %t")
9634 (concat "from %f"))))))
9635 (setq org-store-link-plist plist))
9637 (defun org-add-link-props (&rest plist)
9638 "Add these properties to the link property list."
9639 (let (key value)
9640 (while plist
9641 (setq key (pop plist) value (pop plist))
9642 (setq org-store-link-plist
9643 (plist-put org-store-link-plist key value)))))
9645 (defun org-email-link-description (&optional fmt)
9646 "Return the description part of an email link.
9647 This takes information from `org-store-link-plist' and formats it
9648 according to FMT (default from `org-email-link-description-format')."
9649 (setq fmt (or fmt org-email-link-description-format))
9650 (let* ((p org-store-link-plist)
9651 (to (plist-get p :toaddress))
9652 (from (plist-get p :fromaddress))
9653 (table
9654 (list
9655 (cons "%c" (plist-get p :fromto))
9656 (cons "%F" (plist-get p :from))
9657 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9658 (cons "%T" (plist-get p :to))
9659 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9660 (cons "%s" (plist-get p :subject))
9661 (cons "%d" (plist-get p :date))
9662 (cons "%m" (plist-get p :message-id)))))
9663 (when (string-match "%c" fmt)
9664 ;; Check if the user wrote this message
9665 (if (and org-from-is-user-regexp from to
9666 (save-match-data (string-match org-from-is-user-regexp from)))
9667 (setq fmt (replace-match "to %t" t t fmt))
9668 (setq fmt (replace-match "from %f" t t fmt))))
9669 (org-replace-escapes fmt table)))
9671 (defun org-make-org-heading-search-string (&optional string)
9672 "Make search string for the current headline or STRING."
9673 (let ((s (or string
9674 (and (derived-mode-p 'org-mode)
9675 (save-excursion
9676 (org-back-to-heading t)
9677 (org-element-property :raw-value (org-element-at-point))))))
9678 (lines org-context-in-file-links))
9679 (or string (setq s (concat "*" s))) ; Add * for headlines
9680 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9681 (when (and string (integerp lines) (> lines 0))
9682 (let ((slines (org-split-string s "\n")))
9683 (when (< lines (length slines))
9684 (setq s (mapconcat
9685 'identity
9686 (reverse (nthcdr (- (length slines) lines)
9687 (reverse slines))) "\n")))))
9688 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9690 (defun org-make-link-string (link &optional description)
9691 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9692 (unless (string-match "\\S-" link)
9693 (error "Empty link"))
9694 (when (and description
9695 (stringp description)
9696 (not (string-match "\\S-" description)))
9697 (setq description nil))
9698 (when (stringp description)
9699 ;; Remove brackets from the description, they are fatal.
9700 (while (string-match "\\[" description)
9701 (setq description (replace-match "{" t t description)))
9702 (while (string-match "\\]" description)
9703 (setq description (replace-match "}" t t description))))
9704 (when (equal link description)
9705 ;; No description needed, it is identical
9706 (setq description nil))
9707 (when (and (not description)
9708 (not (string-match (org-image-file-name-regexp) link))
9709 (not (equal link (org-link-escape link))))
9710 (setq description (org-extract-attributes link)))
9711 (setq link
9712 (cond ((string-match (org-image-file-name-regexp) link) link)
9713 ((string-match org-link-types-re link)
9714 (concat (match-string 1 link)
9715 (org-link-escape (substring link (match-end 1)))))
9716 (t (org-link-escape link))))
9717 (concat "[[" link "]"
9718 (if description (concat "[" description "]") "")
9719 "]"))
9721 (defconst org-link-escape-chars
9722 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9723 "List of characters that should be escaped in link.
9724 This is the list that is used for internal purposes.")
9726 (defconst org-link-escape-chars-browser
9727 '(?\ ?\")
9728 "List of escapes for characters that are problematic in links.
9729 This is the list that is used before handing over to the browser.")
9731 (defun org-link-escape (text &optional table merge)
9732 "Return percent escaped representation of TEXT.
9733 TEXT is a string with the text to escape.
9734 Optional argument TABLE is a list with characters that should be
9735 escaped. When nil, `org-link-escape-chars' is used.
9736 If optional argument MERGE is set, merge TABLE into
9737 `org-link-escape-chars'."
9738 (cond
9739 ((and table merge)
9740 (mapc (lambda (defchr)
9741 (unless (member defchr table)
9742 (setq table (cons defchr table)))) org-link-escape-chars))
9743 ((null table)
9744 (setq table org-link-escape-chars)))
9745 (mapconcat
9746 (lambda (char)
9747 (if (or (member char table)
9748 (and (or (< char 32) (= char 37) (> char 126))
9749 org-url-hexify-p))
9750 (mapconcat (lambda (sequence-element)
9751 (format "%%%.2X" sequence-element))
9752 (or (encode-coding-char char 'utf-8)
9753 (error "Unable to percent escape character: %s"
9754 (char-to-string char))) "")
9755 (char-to-string char))) text ""))
9757 (defun org-link-unescape (str)
9758 "Unhex hexified Unicode strings as returned from the JavaScript function
9759 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9760 (unless (and (null str) (string= "" str))
9761 (let ((pos 0) (case-fold-search t) unhexed)
9762 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9763 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9764 (setq str (replace-match unhexed t t str))
9765 (setq pos (+ pos (length unhexed))))))
9766 str)
9768 (defun org-link-unescape-compound (hex)
9769 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9770 Note: this function also decodes single byte encodings like
9771 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9772 (save-match-data
9773 (let* ((bytes (cdr (split-string hex "%")))
9774 (ret "")
9775 (eat 0)
9776 (sum 0))
9777 (while bytes
9778 (let* ((val (string-to-number (pop bytes) 16))
9779 (shift-xor
9780 (if (= 0 eat)
9781 (cond
9782 ((>= val 252) (cons 6 252))
9783 ((>= val 248) (cons 5 248))
9784 ((>= val 240) (cons 4 240))
9785 ((>= val 224) (cons 3 224))
9786 ((>= val 192) (cons 2 192))
9787 (t (cons 0 0)))
9788 (cons 6 128))))
9789 (if (>= val 192) (setq eat (car shift-xor)))
9790 (setq val (logxor val (cdr shift-xor)))
9791 (setq sum (+ (lsh sum (car shift-xor)) val))
9792 (if (> eat 0) (setq eat (- eat 1)))
9793 (cond
9794 ((= 0 eat) ;multi byte
9795 (setq ret (concat ret (org-char-to-string sum)))
9796 (setq sum 0))
9797 ((not bytes) ; single byte(s)
9798 (setq ret (org-link-unescape-single-byte-sequence hex))))
9799 )) ;; end (while bytes
9800 ret )))
9802 (defun org-link-unescape-single-byte-sequence (hex)
9803 "Unhexify hex-encoded single byte character sequences."
9804 (mapconcat (lambda (byte)
9805 (char-to-string (string-to-number byte 16)))
9806 (cdr (split-string hex "%")) ""))
9808 (defun org-xor (a b)
9809 "Exclusive or."
9810 (if a (not b) b))
9812 (defun org-fixup-message-id-for-http (s)
9813 "Replace special characters in a message id, so it can be used in an http query."
9814 (when (string-match "%" s)
9815 (setq s (mapconcat (lambda (c)
9816 (if (eq c ?%)
9817 "%25"
9818 (char-to-string c)))
9819 s "")))
9820 (while (string-match "<" s)
9821 (setq s (replace-match "%3C" t t s)))
9822 (while (string-match ">" s)
9823 (setq s (replace-match "%3E" t t s)))
9824 (while (string-match "@" s)
9825 (setq s (replace-match "%40" t t s)))
9828 (defun org-link-prettify (link)
9829 "Return a human-readable representation of LINK.
9830 The car of LINK must be a raw link the cdr of LINK must be either
9831 a link description or nil."
9832 (let ((desc (or (cadr link) "<no description>")))
9833 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9834 "<" (car link) ">")))
9836 ;;;###autoload
9837 (defun org-insert-link-global ()
9838 "Insert a link like Org-mode does.
9839 This command can be called in any mode to insert a link in Org-mode syntax."
9840 (interactive)
9841 (org-load-modules-maybe)
9842 (org-run-like-in-org-mode 'org-insert-link))
9844 (defun org-insert-all-links (&optional keep)
9845 "Insert all links in `org-stored-links'."
9846 (interactive "P")
9847 (let ((links (copy-sequence org-stored-links)) l)
9848 (while (setq l (if keep (pop links) (pop org-stored-links)))
9849 (insert "- ")
9850 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9851 (insert "\n"))))
9853 (defun org-link-fontify-links-to-this-file ()
9854 "Fontify links to the current file in `org-stored-links'."
9855 (let ((f (buffer-file-name)) a b)
9856 (setq a (mapcar (lambda(l)
9857 (let ((ll (car l)))
9858 (when (and (string-match "^file:\\(.+\\)::" ll)
9859 (equal f (expand-file-name (match-string 1 ll))))
9860 ll)))
9861 org-stored-links))
9862 (when (featurep 'org-id)
9863 (setq b (mapcar (lambda(l)
9864 (let ((ll (car l)))
9865 (when (and (string-match "^id:\\(.+\\)$" ll)
9866 (equal f (expand-file-name
9867 (or (org-id-find-id-file
9868 (match-string 1 ll)) ""))))
9869 ll)))
9870 org-stored-links)))
9871 (mapcar (lambda(l)
9872 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9873 (delq nil (append a b)))))
9875 (defvar org-link-links-in-this-file nil)
9876 (defun org-insert-link (&optional complete-file link-location default-description)
9877 "Insert a link. At the prompt, enter the link.
9879 Completion can be used to insert any of the link protocol prefixes like
9880 http or ftp in use.
9882 The history can be used to select a link previously stored with
9883 `org-store-link'. When the empty string is entered (i.e. if you just
9884 press RET at the prompt), the link defaults to the most recently
9885 stored link. As SPC triggers completion in the minibuffer, you need to
9886 use M-SPC or C-q SPC to force the insertion of a space character.
9888 You will also be prompted for a description, and if one is given, it will
9889 be displayed in the buffer instead of the link.
9891 If there is already a link at point, this command will allow you to edit link
9892 and description parts.
9894 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9895 be selected using completion. The path to the file will be relative to the
9896 current directory if the file is in the current directory or a subdirectory.
9897 Otherwise, the link will be the absolute path as completed in the minibuffer
9898 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9899 option `org-link-file-path-type'.
9901 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9902 the current directory or below.
9904 With three \\[universal-argument] prefixes, negate the meaning of
9905 `org-keep-stored-link-after-insertion'.
9907 If `org-make-link-description-function' is non-nil, this function will be
9908 called with the link target, and the result will be the default
9909 link description.
9911 If the LINK-LOCATION parameter is non-nil, this value will be
9912 used as the link location instead of reading one interactively.
9914 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9915 be used as the default description."
9916 (interactive "P")
9917 (let* ((wcf (current-window-configuration))
9918 (origbuf (current-buffer))
9919 (region (if (org-region-active-p)
9920 (buffer-substring (region-beginning) (region-end))))
9921 (remove (and region (list (region-beginning) (region-end))))
9922 (desc region)
9923 tmphist ; byte-compile incorrectly complains about this
9924 (link link-location)
9925 (abbrevs org-link-abbrev-alist-local)
9926 entry file all-prefixes auto-desc)
9927 (cond
9928 (link-location) ; specified by arg, just use it.
9929 ((org-in-regexp org-bracket-link-regexp 1)
9930 ;; We do have a link at point, and we are going to edit it.
9931 (setq remove (list (match-beginning 0) (match-end 0)))
9932 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9933 (setq link (read-string "Link: "
9934 (org-link-unescape
9935 (org-match-string-no-properties 1)))))
9936 ((or (org-in-regexp org-angle-link-re)
9937 (org-in-regexp org-plain-link-re))
9938 ;; Convert to bracket link
9939 (setq remove (list (match-beginning 0) (match-end 0))
9940 link (read-string "Link: "
9941 (org-remove-angle-brackets (match-string 0)))))
9942 ((member complete-file '((4) (16)))
9943 ;; Completing read for file names.
9944 (setq link (org-file-complete-link complete-file)))
9946 ;; Read link, with completion for stored links.
9947 (org-link-fontify-links-to-this-file)
9948 (org-switch-to-buffer-other-window "*Org Links*")
9949 (with-current-buffer "*Org Links*"
9950 (erase-buffer)
9951 (insert "Insert a link.
9952 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9953 (when org-stored-links
9954 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9955 (insert (mapconcat 'org-link-prettify
9956 (reverse org-stored-links) "\n")))
9957 (goto-char (point-min)))
9958 (let ((cw (selected-window)))
9959 (select-window (get-buffer-window "*Org Links*" 'visible))
9960 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9961 (unless (pos-visible-in-window-p (point-max))
9962 (org-fit-window-to-buffer))
9963 (and (window-live-p cw) (select-window cw)))
9964 ;; Fake a link history, containing the stored links.
9965 (setq tmphist (append (mapcar 'car org-stored-links)
9966 org-insert-link-history))
9967 (setq all-prefixes (append (mapcar 'car abbrevs)
9968 (mapcar 'car org-link-abbrev-alist)
9969 org-link-types))
9970 (unwind-protect
9971 (progn
9972 (setq link
9973 (org-completing-read
9974 "Link: "
9975 (append
9976 (mapcar (lambda (x) (concat x ":"))
9977 all-prefixes)
9978 (mapcar 'car org-stored-links))
9979 nil nil nil
9980 'tmphist
9981 (caar org-stored-links)))
9982 (if (not (string-match "\\S-" link))
9983 (user-error "No link selected"))
9984 (mapc (lambda(l)
9985 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9986 org-stored-links)
9987 (if (or (member link all-prefixes)
9988 (and (equal ":" (substring link -1))
9989 (member (substring link 0 -1) all-prefixes)
9990 (setq link (substring link 0 -1))))
9991 (setq link (with-current-buffer origbuf
9992 (org-link-try-special-completion link)))))
9993 (set-window-configuration wcf)
9994 (kill-buffer "*Org Links*"))
9995 (setq entry (assoc link org-stored-links))
9996 (or entry (push link org-insert-link-history))
9997 (setq desc (or desc (nth 1 entry)))))
9999 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10000 (not org-keep-stored-link-after-insertion))
10001 (setq org-stored-links (delq (assoc link org-stored-links)
10002 org-stored-links)))
10004 (if (and (string-match org-plain-link-re link)
10005 (not (string-match org-ts-regexp link)))
10006 ;; URL-like link, normalize the use of angular brackets.
10007 (setq link (org-remove-angle-brackets link)))
10009 ;; Check if we are linking to the current file with a search
10010 ;; option If yes, simplify the link by using only the search
10011 ;; option.
10012 (when (and buffer-file-name
10013 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10014 (let* ((path (match-string 1 link))
10015 (case-fold-search nil)
10016 (search (match-string 2 link)))
10017 (save-match-data
10018 (if (equal (file-truename buffer-file-name) (file-truename path))
10019 ;; We are linking to this same file, with a search option
10020 (setq link search)))))
10022 ;; Check if we can/should use a relative path. If yes, simplify the link
10023 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10024 (let* ((type (match-string 1 link))
10025 (path (match-string 2 link))
10026 (origpath path)
10027 (case-fold-search nil))
10028 (cond
10029 ((or (eq org-link-file-path-type 'absolute)
10030 (equal complete-file '(16)))
10031 (setq path (abbreviate-file-name (expand-file-name path))))
10032 ((eq org-link-file-path-type 'noabbrev)
10033 (setq path (expand-file-name path)))
10034 ((eq org-link-file-path-type 'relative)
10035 (setq path (file-relative-name path)))
10037 (save-match-data
10038 (if (string-match (concat "^" (regexp-quote
10039 (expand-file-name
10040 (file-name-as-directory
10041 default-directory))))
10042 (expand-file-name path))
10043 ;; We are linking a file with relative path name.
10044 (setq path (substring (expand-file-name path)
10045 (match-end 0)))
10046 (setq path (abbreviate-file-name (expand-file-name path)))))))
10047 (setq link (concat type path))
10048 (if (equal desc origpath)
10049 (setq desc path))))
10051 (if org-make-link-description-function
10052 (setq desc
10053 (or (condition-case nil
10054 (funcall org-make-link-description-function link desc)
10055 (error (progn (message "Can't get link description from `%s'"
10056 (symbol-name org-make-link-description-function))
10057 (sit-for 2) nil)))
10058 (read-string "Description: " default-description)))
10059 (if default-description (setq desc default-description)
10060 (setq desc (or (and auto-desc desc)
10061 (read-string "Description: " desc)))))
10063 (unless (string-match "\\S-" desc) (setq desc nil))
10064 (if remove (apply 'delete-region remove))
10065 (insert (org-make-link-string link desc))))
10067 (defun org-link-try-special-completion (type)
10068 "If there is completion support for link type TYPE, offer it."
10069 (let ((fun (intern (concat "org-" type "-complete-link"))))
10070 (if (functionp fun)
10071 (funcall fun)
10072 (read-string "Link (no completion support): " (concat type ":")))))
10074 (defun org-file-complete-link (&optional arg)
10075 "Create a file link using completion."
10076 (let (file link)
10077 (setq file (org-iread-file-name "File: "))
10078 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10079 (pwd1 (file-name-as-directory (abbreviate-file-name
10080 (expand-file-name ".")))))
10081 (cond
10082 ((equal arg '(16))
10083 (setq link (concat
10084 "file:"
10085 (abbreviate-file-name (expand-file-name file)))))
10086 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10087 (setq link (concat "file:" (match-string 1 file))))
10088 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10089 (expand-file-name file))
10090 (setq link (concat
10091 "file:" (match-string 1 (expand-file-name file)))))
10092 (t (setq link (concat "file:" file)))))
10093 link))
10095 (defun org-iread-file-name (&rest args)
10096 "Read-file-name using `ido-mode' speedup if available.
10097 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10098 See `read-file-name' for a description of parameters."
10099 (org-without-partial-completion
10100 (if (and org-completion-use-ido
10101 (fboundp 'ido-read-file-name)
10102 (boundp 'ido-mode) ido-mode
10103 (listp (second args)))
10104 (let ((ido-enter-matching-directory nil))
10105 (apply 'ido-read-file-name args))
10106 (apply 'read-file-name args))))
10108 (defun org-completing-read (&rest args)
10109 "Completing-read with SPACE being a normal character."
10110 (let ((enable-recursive-minibuffers t)
10111 (minibuffer-local-completion-map
10112 (copy-keymap minibuffer-local-completion-map)))
10113 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10114 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10115 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10116 (apply 'org-icompleting-read args)))
10118 (defun org-completing-read-no-i (&rest args)
10119 (let (org-completion-use-ido org-completion-use-iswitchb)
10120 (apply 'org-completing-read args)))
10122 (defun org-iswitchb-completing-read (prompt choices &rest args)
10123 "Use iswitch as a completing-read replacement to choose from choices.
10124 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10125 from."
10126 (let* ((iswitchb-use-virtual-buffers nil)
10127 (iswitchb-make-buflist-hook
10128 (lambda ()
10129 (setq iswitchb-temp-buflist choices))))
10130 (iswitchb-read-buffer prompt)))
10132 (defun org-icompleting-read (&rest args)
10133 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10134 (org-without-partial-completion
10135 (if (and org-completion-use-ido
10136 (fboundp 'ido-completing-read)
10137 (boundp 'ido-mode) ido-mode
10138 (listp (second args)))
10139 (let ((ido-enter-matching-directory nil))
10140 (apply 'ido-completing-read (concat (car args))
10141 (if (consp (car (nth 1 args)))
10142 (mapcar 'car (nth 1 args))
10143 (nth 1 args))
10144 (cddr args)))
10145 (if (and org-completion-use-iswitchb
10146 (boundp 'iswitchb-mode) iswitchb-mode
10147 (listp (second args)))
10148 (apply 'org-iswitchb-completing-read (concat (car args))
10149 (if (consp (car (nth 1 args)))
10150 (mapcar 'car (nth 1 args))
10151 (nth 1 args))
10152 (cddr args))
10153 (apply 'completing-read args)))))
10155 (defun org-extract-attributes (s)
10156 "Extract the attributes cookie from a string and set as text property."
10157 (let (a attr (start 0) key value)
10158 (save-match-data
10159 (when (string-match "{{\\([^}]+\\)}}$" s)
10160 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10161 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10162 (setq key (match-string 1 a) value (match-string 2 a)
10163 start (match-end 0)
10164 attr (plist-put attr (intern key) value))))
10165 (org-add-props s nil 'org-attr attr))
10168 ;;; Opening/following a link
10170 (defvar org-link-search-failed nil)
10172 (defvar org-open-link-functions nil
10173 "Hook for functions finding a plain text link.
10174 These functions must take a single argument, the link content.
10175 They will be called for links that look like [[link text][description]]
10176 when LINK TEXT does not have a protocol like \"http:\" and does not look
10177 like a filename (e.g. \"./blue.png\").
10179 These functions will be called *before* Org attempts to resolve the
10180 link by doing text searches in the current buffer - so if you want a
10181 link \"[[target]]\" to still find \"<<target>>\", your function should
10182 handle this as a special case.
10184 When the function does handle the link, it must return a non-nil value.
10185 If it decides that it is not responsible for this link, it must return
10186 nil to indicate that that Org-mode can continue with other options
10187 like exact and fuzzy text search.")
10189 (defun org-next-link (&optional search-backward)
10190 "Move forward to the next link.
10191 If the link is in hidden text, expose it."
10192 (interactive "P")
10193 (when (and org-link-search-failed (eq this-command last-command))
10194 (goto-char (point-min))
10195 (message "Link search wrapped back to beginning of buffer"))
10196 (setq org-link-search-failed nil)
10197 (let* ((pos (point))
10198 (ct (org-context))
10199 (a (assoc :link ct))
10200 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10201 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10202 ((looking-at org-any-link-re)
10203 ;; Don't stay stuck at link without an org-link face
10204 (forward-char (if search-backward -1 1))))
10205 (if (funcall srch-fun org-any-link-re nil t)
10206 (progn
10207 (goto-char (match-beginning 0))
10208 (if (outline-invisible-p) (org-show-context)))
10209 (goto-char pos)
10210 (setq org-link-search-failed t)
10211 (message "No further link found"))))
10213 (defun org-previous-link ()
10214 "Move backward to the previous link.
10215 If the link is in hidden text, expose it."
10216 (interactive)
10217 (funcall 'org-next-link t))
10219 (defun org-translate-link (s)
10220 "Translate a link string if a translation function has been defined."
10221 (if (and org-link-translation-function
10222 (fboundp org-link-translation-function)
10223 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10224 (progn
10225 (setq s (funcall org-link-translation-function
10226 (match-string 1 s) (match-string 2 s)))
10227 (concat (car s) ":" (cdr s)))
10230 (defun org-translate-link-from-planner (type path)
10231 "Translate a link from Emacs Planner syntax so that Org can follow it.
10232 This is still an experimental function, your mileage may vary."
10233 (cond
10234 ((member type '("http" "https" "news" "ftp"))
10235 ;; standard Internet links are the same.
10236 nil)
10237 ((and (equal type "irc") (string-match "^//" path))
10238 ;; Planner has two / at the beginning of an irc link, we have 1.
10239 ;; We should have zero, actually....
10240 (setq path (substring path 1)))
10241 ((and (equal type "lisp") (string-match "^/" path))
10242 ;; Planner has a slash, we do not.
10243 (setq type "elisp" path (substring path 1)))
10244 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10245 ;; A typical message link. Planner has the id after the final slash,
10246 ;; we separate it with a hash mark
10247 (setq path (concat (match-string 1 path) "#"
10248 (org-remove-angle-brackets (match-string 2 path))))))
10249 (cons type path))
10251 (defun org-find-file-at-mouse (ev)
10252 "Open file link or URL at mouse."
10253 (interactive "e")
10254 (mouse-set-point ev)
10255 (org-open-at-point 'in-emacs))
10257 (defun org-open-at-mouse (ev)
10258 "Open file link or URL at mouse.
10259 See the docstring of `org-open-file' for details."
10260 (interactive "e")
10261 (mouse-set-point ev)
10262 (if (eq major-mode 'org-agenda-mode)
10263 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10264 (org-open-at-point))
10266 (defvar org-window-config-before-follow-link nil
10267 "The window configuration before following a link.
10268 This is saved in case the need arises to restore it.")
10270 (defvar org-open-link-marker (make-marker)
10271 "Marker pointing to the location where `org-open-at-point; was called.")
10273 ;;;###autoload
10274 (defun org-open-at-point-global ()
10275 "Follow a link like Org-mode does.
10276 This command can be called in any mode to follow a link that has
10277 Org-mode syntax."
10278 (interactive)
10279 (org-run-like-in-org-mode 'org-open-at-point))
10281 ;;;###autoload
10282 (defun org-open-link-from-string (s &optional arg reference-buffer)
10283 "Open a link in the string S, as if it was in Org-mode."
10284 (interactive "sLink: \nP")
10285 (let ((reference-buffer (or reference-buffer (current-buffer))))
10286 (with-temp-buffer
10287 (let ((org-inhibit-startup (not reference-buffer)))
10288 (org-mode)
10289 (insert s)
10290 (goto-char (point-min))
10291 (when reference-buffer
10292 (setq org-link-abbrev-alist-local
10293 (with-current-buffer reference-buffer
10294 org-link-abbrev-alist-local)))
10295 (org-open-at-point arg reference-buffer)))))
10297 (defvar org-open-at-point-functions nil
10298 "Hook that is run when following a link at point.
10300 Functions in this hook must return t if they identify and follow
10301 a link at point. If they don't find anything interesting at point,
10302 they must return nil.")
10304 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10305 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10306 (defun org-open-at-point (&optional arg reference-buffer)
10307 "Open link at or after point.
10308 If there is no link at point, this function will search forward up to
10309 the end of the current line.
10310 Normally, files will be opened by an appropriate application. If the
10311 optional prefix argument ARG is non-nil, Emacs will visit the file.
10312 With a double prefix argument, try to open outside of Emacs, in the
10313 application the system uses for this file type."
10314 (interactive "P")
10315 ;; if in a code block, then open the block's results
10316 (unless (call-interactively #'org-babel-open-src-block-result)
10317 (org-load-modules-maybe)
10318 (move-marker org-open-link-marker (point))
10319 (setq org-window-config-before-follow-link (current-window-configuration))
10320 (org-remove-occur-highlights nil nil t)
10321 (cond
10322 ((and (org-at-heading-p)
10323 (not (org-at-timestamp-p t))
10324 (not (org-in-regexp
10325 (concat org-plain-link-re "\\|"
10326 org-bracket-link-regexp "\\|"
10327 org-angle-link-re "\\|"
10328 "[ \t]:[^ \t\n]+:[ \t]*$")))
10329 (not (get-text-property (point) 'org-linked-text)))
10330 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10331 (lk0 (car lkall))
10332 (lk (if (stringp lk0) (list lk0) lk0))
10333 (lkend (cdr lkall)))
10334 (mapcar (lambda(l)
10335 (search-forward l nil lkend)
10336 (goto-char (match-beginning 0))
10337 (org-open-at-point))
10338 lk))
10339 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10340 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10341 ((and (org-at-timestamp-p t)
10342 (not (org-in-regexp org-bracket-link-regexp)))
10343 (org-follow-timestamp-link))
10344 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10345 (not (org-in-regexp org-any-link-re)))
10346 (org-footnote-action))
10348 (let (type path link line search (pos (point)))
10349 (catch 'match
10350 (save-excursion
10351 (skip-chars-forward "^]\n\r")
10352 (when (org-in-regexp org-bracket-link-regexp 1)
10353 (setq link (org-extract-attributes
10354 (org-link-unescape (org-match-string-no-properties 1))))
10355 (while (string-match " *\n *" link)
10356 (setq link (replace-match " " t t link)))
10357 (setq link (org-link-expand-abbrev link))
10358 (cond
10359 ((or (file-name-absolute-p link)
10360 (string-match "^\\.\\.?/" link))
10361 (setq type "file" path link))
10362 ((string-match org-link-re-with-space3 link)
10363 (setq type (match-string 1 link) path (match-string 2 link)))
10364 ((string-match "^help:+\\(.+\\)" link)
10365 (setq type "help" path (match-string 1 link)))
10366 (t (setq type "thisfile" path link)))
10367 (throw 'match t)))
10369 (when (get-text-property (point) 'org-linked-text)
10370 (setq type "thisfile"
10371 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10372 (1+ (point)) (point))
10373 path (buffer-substring
10374 (or (previous-single-property-change pos 'org-linked-text)
10375 (point-min))
10376 (or (next-single-property-change pos 'org-linked-text)
10377 (point-max)))
10378 ;; Ensure we will search for a <<<radio>>> link, not
10379 ;; a simple reference like <<ref>>
10380 path (concat "<" path))
10381 (throw 'match t))
10383 (save-excursion
10384 (when (or (org-in-regexp org-angle-link-re)
10385 (let ((match (org-in-regexp org-plain-link-re)))
10386 ;; Check a plain link is not within a bracket link
10387 (and match
10388 (save-excursion
10389 (progn
10390 (goto-char (car match))
10391 (not (org-in-regexp org-bracket-link-regexp))))))
10392 (let ((line_ending (save-excursion (end-of-line) (point))))
10393 ;; We are in a line before a plain or bracket link
10394 (or (re-search-forward org-plain-link-re line_ending t)
10395 (re-search-forward org-bracket-link-regexp line_ending t))))
10396 (setq type (match-string 1)
10397 path (org-link-unescape (match-string 2)))
10398 (throw 'match t)))
10399 (save-excursion
10400 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10401 (setq type "tags"
10402 path (match-string 1))
10403 (while (string-match ":" path)
10404 (setq path (replace-match "+" t t path)))
10405 (throw 'match t)))
10406 (when (org-in-regexp "<\\([^><\n]+\\)>")
10407 (setq type "tree-match"
10408 path (match-string 1))
10409 (throw 'match t)))
10410 (unless path
10411 (user-error "No link found"))
10413 ;; switch back to reference buffer
10414 ;; needed when if called in a temporary buffer through
10415 ;; org-open-link-from-string
10416 (with-current-buffer (or reference-buffer (current-buffer))
10418 ;; Remove any trailing spaces in path
10419 (if (string-match " +\\'" path)
10420 (setq path (replace-match "" t t path)))
10421 (if (and org-link-translation-function
10422 (fboundp org-link-translation-function))
10423 ;; Check if we need to translate the link
10424 (let ((tmp (funcall org-link-translation-function type path)))
10425 (setq type (car tmp) path (cdr tmp))))
10427 (cond
10429 ((assoc type org-link-protocols)
10430 (funcall (nth 1 (assoc type org-link-protocols)) path))
10432 ((equal type "help")
10433 (let ((f-or-v (intern path)))
10434 (cond ((fboundp f-or-v)
10435 (describe-function f-or-v))
10436 ((boundp f-or-v)
10437 (describe-variable f-or-v))
10438 (t (error "Not a known function or variable")))))
10440 ((equal type "mailto")
10441 (let ((cmd (car org-link-mailto-program))
10442 (args (cdr org-link-mailto-program)) args1
10443 (address path) (subject "") a)
10444 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10445 (setq address (match-string 1 path)
10446 subject (org-link-escape (match-string 2 path))))
10447 (while args
10448 (cond
10449 ((not (stringp (car args))) (push (pop args) args1))
10450 (t (setq a (pop args))
10451 (if (string-match "%a" a)
10452 (setq a (replace-match address t t a)))
10453 (if (string-match "%s" a)
10454 (setq a (replace-match subject t t a)))
10455 (push a args1))))
10456 (apply cmd (nreverse args1))))
10458 ((member type '("http" "https" "ftp" "news"))
10459 (browse-url
10460 (concat type ":"
10461 (if (org-string-match-p
10462 (concat "[[:nonascii:]"
10463 org-link-escape-chars-browser "]")
10464 path)
10465 (org-link-escape path org-link-escape-chars-browser)
10466 path))))
10468 ((string= type "doi")
10469 (browse-url
10470 (concat org-doi-server-url
10471 (if (org-string-match-p
10472 (concat "[[:nonascii:]"
10473 org-link-escape-chars-browser "]")
10474 path)
10475 (org-link-escape path org-link-escape-chars-browser)
10476 path))))
10478 ((member type '("message"))
10479 (browse-url (concat type ":" path)))
10481 ((string= type "tags")
10482 (org-tags-view arg path))
10484 ((string= type "tree-match")
10485 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10487 ((string= type "file")
10488 (if (string-match "::\\([0-9]+\\)\\'" path)
10489 (setq line (string-to-number (match-string 1 path))
10490 path (substring path 0 (match-beginning 0)))
10491 (if (string-match "::\\(.+\\)\\'" path)
10492 (setq search (match-string 1 path)
10493 path (substring path 0 (match-beginning 0)))))
10494 (if (string-match "[*?{]" (file-name-nondirectory path))
10495 (dired path)
10496 (org-open-file path arg line search)))
10498 ((string= type "shell")
10499 (let ((buf (generate-new-buffer "*Org Shell Output"))
10500 (cmd path))
10501 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10502 (string-match org-confirm-shell-link-not-regexp cmd))
10503 (not org-confirm-shell-link-function)
10504 (funcall org-confirm-shell-link-function
10505 (format "Execute \"%s\" in shell? "
10506 (org-add-props cmd nil
10507 'face 'org-warning))))
10508 (progn
10509 (message "Executing %s" cmd)
10510 (shell-command cmd buf)
10511 (if (featurep 'midnight)
10512 (setq clean-buffer-list-kill-buffer-names
10513 (cons buf clean-buffer-list-kill-buffer-names))))
10514 (error "Abort"))))
10516 ((string= type "elisp")
10517 (let ((cmd path))
10518 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10519 (string-match org-confirm-elisp-link-not-regexp cmd))
10520 (not org-confirm-elisp-link-function)
10521 (funcall org-confirm-elisp-link-function
10522 (format "Execute \"%s\" as elisp? "
10523 (org-add-props cmd nil
10524 'face 'org-warning))))
10525 (message "%s => %s" cmd
10526 (if (equal (string-to-char cmd) ?\()
10527 (eval (read cmd))
10528 (call-interactively (read cmd))))
10529 (error "Abort"))))
10531 ((and (string= type "thisfile")
10532 (or (run-hook-with-args-until-success
10533 'org-open-link-functions path)
10534 (and link
10535 (string-match "^id:" link)
10536 (or (featurep 'org-id) (require 'org-id))
10537 (progn
10538 (funcall (nth 1 (assoc "id" org-link-protocols))
10539 (substring path 3))
10540 t)))))
10542 ((string= type "thisfile")
10543 (if arg
10544 (switch-to-buffer-other-window
10545 (org-get-buffer-for-internal-link (current-buffer)))
10546 (org-mark-ring-push))
10547 (let ((cmd `(org-link-search
10548 ,path
10549 ,(cond ((equal arg '(4)) ''occur)
10550 ((equal arg '(16)) ''org-occur))
10551 ,pos)))
10552 (condition-case nil (let ((org-link-search-inhibit-query t))
10553 (eval cmd))
10554 (error (progn (widen) (eval cmd))))))
10556 (t (browse-url-at-point)))))))
10557 (move-marker org-open-link-marker nil)
10558 (run-hook-with-args 'org-follow-link-hook)))
10560 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10561 "Offer links in the current entry and return the selected link.
10562 If there is only one link, return it.
10563 If NTH is an integer, return the NTH link found.
10564 If ZERO is a string, check also this string for a link, and if
10565 there is one, return it."
10566 (with-current-buffer buffer
10567 (save-excursion
10568 (save-restriction
10569 (widen)
10570 (goto-char marker)
10571 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10572 "\\(" org-angle-link-re "\\)\\|"
10573 "\\(" org-plain-link-re "\\)"))
10574 (cnt ?0)
10575 (in-emacs (if (integerp nth) nil nth))
10576 have-zero end links link c)
10577 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10578 (push (match-string 0 zero) links)
10579 (setq cnt (1- cnt) have-zero t))
10580 (save-excursion
10581 (org-back-to-heading t)
10582 (setq end (save-excursion (outline-next-heading) (point)))
10583 (while (re-search-forward re end t)
10584 (push (match-string 0) links))
10585 (setq links (org-uniquify (reverse links))))
10586 (cond
10587 ((null links)
10588 (message "No links"))
10589 ((equal (length links) 1)
10590 (setq link (car links)))
10591 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10592 (setq link (nth (if have-zero nth (1- nth)) links)))
10593 (t ; we have to select a link
10594 (save-excursion
10595 (save-window-excursion
10596 (delete-other-windows)
10597 (with-output-to-temp-buffer "*Select Link*"
10598 (mapc (lambda (l)
10599 (if (not (string-match org-bracket-link-regexp l))
10600 (princ (format "[%c] %s\n" (incf cnt)
10601 (org-remove-angle-brackets l)))
10602 (if (match-end 3)
10603 (princ (format "[%c] %s (%s)\n" (incf cnt)
10604 (match-string 3 l) (match-string 1 l)))
10605 (princ (format "[%c] %s\n" (incf cnt)
10606 (match-string 1 l))))))
10607 links))
10608 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10609 (message "Select link to open, RET to open all:")
10610 (setq c (read-char-exclusive))
10611 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10612 (when (equal c ?q) (error "Abort"))
10613 (if (equal c ?\C-m)
10614 (setq link links)
10615 (setq nth (- c ?0))
10616 (if have-zero (setq nth (1+ nth)))
10617 (unless (and (integerp nth) (>= (length links) nth))
10618 (user-error "Invalid link selection"))
10619 (setq link (nth (1- nth) links)))))
10620 (cons link end))))))
10622 ;; Add special file links that specify the way of opening
10624 (org-add-link-type "file+sys" 'org-open-file-with-system)
10625 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10626 (defun org-open-file-with-system (path)
10627 "Open file at PATH using the system way of opening it."
10628 (org-open-file path 'system))
10629 (defun org-open-file-with-emacs (path)
10630 "Open file at PATH in Emacs."
10631 (org-open-file path 'emacs))
10634 ;;; File search
10636 (defvar org-create-file-search-functions nil
10637 "List of functions to construct the right search string for a file link.
10638 These functions are called in turn with point at the location to
10639 which the link should point.
10641 A function in the hook should first test if it would like to
10642 handle this file type, for example by checking the `major-mode'
10643 or the file extension. If it decides not to handle this file, it
10644 should just return nil to give other functions a chance. If it
10645 does handle the file, it must return the search string to be used
10646 when following the link. The search string will be part of the
10647 file link, given after a double colon, and `org-open-at-point'
10648 will automatically search for it. If special measures must be
10649 taken to make the search successful, another function should be
10650 added to the companion hook `org-execute-file-search-functions',
10651 which see.
10653 A function in this hook may also use `setq' to set the variable
10654 `description' to provide a suggestion for the descriptive text to
10655 be used for this link when it gets inserted into an Org-mode
10656 buffer with \\[org-insert-link].")
10658 (defvar org-execute-file-search-functions nil
10659 "List of functions to execute a file search triggered by a link.
10661 Functions added to this hook must accept a single argument, the
10662 search string that was part of the file link, the part after the
10663 double colon. The function must first check if it would like to
10664 handle this search, for example by checking the `major-mode' or
10665 the file extension. If it decides not to handle this search, it
10666 should just return nil to give other functions a chance. If it
10667 does handle the search, it must return a non-nil value to keep
10668 other functions from trying.
10670 Each function can access the current prefix argument through the
10671 variable `current-prefix-arg'. Note that a single prefix is used
10672 to force opening a link in Emacs, so it may be good to only use a
10673 numeric or double prefix to guide the search function.
10675 In case this is needed, a function in this hook can also restore
10676 the window configuration before `org-open-at-point' was called using:
10678 (set-window-configuration org-window-config-before-follow-link)")
10680 (defun org-link-search (s &optional type avoid-pos stealth)
10681 "Search for a link search option.
10682 If S is surrounded by forward slashes, it is interpreted as a
10683 regular expression. In org-mode files, this will create an `org-occur'
10684 sparse tree. In ordinary files, `occur' will be used to list matches.
10685 If the current buffer is in `dired-mode', grep will be used to search
10686 in all files. If AVOID-POS is given, ignore matches near that position.
10688 When optional argument STEALTH is non-nil, do not modify
10689 visibility around point, thus ignoring
10690 `org-show-hierarchy-above', `org-show-following-heading' and
10691 `org-show-siblings' variables."
10692 (let ((case-fold-search t)
10693 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10694 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10695 (append '(("") (" ") ("\t") ("\n"))
10696 org-emphasis-alist)
10697 "\\|") "\\)"))
10698 (pos (point))
10699 (pre nil) (post nil)
10700 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10701 (cond
10702 ;; First check if there are any special search functions
10703 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10704 ;; Now try the builtin stuff
10705 ((and (equal (string-to-char s0) ?#)
10706 (> (length s0) 1)
10707 (save-excursion
10708 (goto-char (point-min))
10709 (and
10710 (re-search-forward
10711 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10712 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10713 (setq type 'dedicated
10714 pos (match-beginning 0))))
10715 ;; There is an exact target for this
10716 (goto-char pos)
10717 (org-back-to-heading t)))
10718 ((save-excursion
10719 (goto-char (point-min))
10720 (and
10721 (re-search-forward
10722 (concat "<<" (regexp-quote s0) ">>") nil t)
10723 (setq type 'dedicated
10724 pos (match-beginning 0))))
10725 ;; There is an exact target for this
10726 (goto-char pos))
10727 ((save-excursion
10728 (goto-char (point-min))
10729 (and
10730 (re-search-forward
10731 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10732 (setq type 'dedicated pos (match-beginning 0))))
10733 ;; Found an element with a matching #+name affiliated keyword.
10734 (goto-char pos))
10735 ((and (string-match "^(\\(.*\\))$" s0)
10736 (save-excursion
10737 (goto-char (point-min))
10738 (and
10739 (re-search-forward
10740 (concat "[^[]" (regexp-quote
10741 (format org-coderef-label-format
10742 (match-string 1 s0))))
10743 nil t)
10744 (setq type 'dedicated
10745 pos (1+ (match-beginning 0))))))
10746 ;; There is a coderef target for this
10747 (goto-char pos))
10748 ((string-match "^/\\(.*\\)/$" s)
10749 ;; A regular expression
10750 (cond
10751 ((derived-mode-p 'org-mode)
10752 (org-occur (match-string 1 s)))
10753 (t (org-do-occur (match-string 1 s)))))
10754 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10755 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10756 (goto-char (point-min))
10757 (cond
10758 ((let (case-fold-search)
10759 (re-search-forward (format org-complex-heading-regexp-format
10760 (regexp-quote s))
10761 nil t))
10762 ;; OK, found a match
10763 (setq type 'dedicated)
10764 (goto-char (match-beginning 0)))
10765 ((and (not org-link-search-inhibit-query)
10766 (eq org-link-search-must-match-exact-headline 'query-to-create)
10767 (y-or-n-p "No match - create this as a new heading? "))
10768 (goto-char (point-max))
10769 (or (bolp) (newline))
10770 (insert "* " s "\n")
10771 (beginning-of-line 0))
10773 (goto-char pos)
10774 (error "No match"))))
10776 ;; A normal search string
10777 (when (equal (string-to-char s) ?*)
10778 ;; Anchor on headlines, post may include tags.
10779 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10780 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10781 s (substring s 1)))
10782 (remove-text-properties
10783 0 (length s)
10784 '(face nil mouse-face nil keymap nil fontified nil) s)
10785 ;; Make a series of regular expressions to find a match
10786 (setq words (org-split-string s "[ \n\r\t]+")
10788 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10789 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10790 "\\)" markers)
10791 re2a_ (concat "\\(" (mapconcat 'downcase words
10792 "[ \t\r\n]+") "\\)[ \t\r\n]")
10793 re2a (concat "[ \t\r\n]" re2a_)
10794 re4_ (concat "\\(" (mapconcat 'downcase words
10795 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10796 re4 (concat "[^a-zA-Z_]" re4_)
10798 re1 (concat pre re2 post)
10799 re3 (concat pre (if pre re4_ re4) post)
10800 re5 (concat pre ".*" re4)
10801 re2 (concat pre re2)
10802 re2a (concat pre (if pre re2a_ re2a))
10803 re4 (concat pre (if pre re4_ re4))
10804 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10805 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10806 re5 "\\)"))
10807 (cond
10808 ((eq type 'org-occur) (org-occur reall))
10809 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10810 (t (goto-char (point-min))
10811 (setq type 'fuzzy)
10812 (if (or (and (org-search-not-self 1 re0 nil t)
10813 (setq type 'dedicated))
10814 (org-search-not-self 1 re1 nil t)
10815 (org-search-not-self 1 re2 nil t)
10816 (org-search-not-self 1 re2a nil t)
10817 (org-search-not-self 1 re3 nil t)
10818 (org-search-not-self 1 re4 nil t)
10819 (org-search-not-self 1 re5 nil t))
10820 (goto-char (match-beginning 1))
10821 (goto-char pos)
10822 (error "No match"))))))
10823 (and (derived-mode-p 'org-mode)
10824 (not stealth)
10825 (org-show-context 'link-search))
10826 type))
10828 (defun org-search-not-self (group &rest args)
10829 "Execute `re-search-forward', but only accept matches that do not
10830 enclose the position of `org-open-link-marker'."
10831 (let ((m org-open-link-marker))
10832 (catch 'exit
10833 (while (apply 're-search-forward args)
10834 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10835 (goto-char (match-end group))
10836 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10837 (> (match-beginning 0) (marker-position m))
10838 (< (match-end 0) (marker-position m)))
10839 (save-match-data
10840 (or (not (org-in-regexp
10841 org-bracket-link-analytic-regexp 1))
10842 (not (match-end 4)) ; no description
10843 (and (<= (match-beginning 4) (point))
10844 (>= (match-end 4) (point))))))
10845 (throw 'exit (point))))))))
10847 (defun org-get-buffer-for-internal-link (buffer)
10848 "Return a buffer to be used for displaying the link target of internal links."
10849 (cond
10850 ((not org-display-internal-link-with-indirect-buffer)
10851 buffer)
10852 ((string-match "(Clone)$" (buffer-name buffer))
10853 (message "Buffer is already a clone, not making another one")
10854 ;; we also do not modify visibility in this case
10855 buffer)
10856 (t ; make a new indirect buffer for displaying the link
10857 (let* ((bn (buffer-name buffer))
10858 (ibn (concat bn "(Clone)"))
10859 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10860 (with-current-buffer ib (org-overview))
10861 ib))))
10863 (defun org-do-occur (regexp &optional cleanup)
10864 "Call the Emacs command `occur'.
10865 If CLEANUP is non-nil, remove the printout of the regular expression
10866 in the *Occur* buffer. This is useful if the regex is long and not useful
10867 to read."
10868 (occur regexp)
10869 (when cleanup
10870 (let ((cwin (selected-window)) win beg end)
10871 (when (setq win (get-buffer-window "*Occur*"))
10872 (select-window win))
10873 (goto-char (point-min))
10874 (when (re-search-forward "match[a-z]+" nil t)
10875 (setq beg (match-end 0))
10876 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10877 (setq end (1- (match-beginning 0)))))
10878 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10879 (goto-char (point-min))
10880 (select-window cwin))))
10882 ;;; The mark ring for links jumps
10884 (defvar org-mark-ring nil
10885 "Mark ring for positions before jumps in Org-mode.")
10886 (defvar org-mark-ring-last-goto nil
10887 "Last position in the mark ring used to go back.")
10888 ;; Fill and close the ring
10889 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10890 (loop for i from 1 to org-mark-ring-length do
10891 (push (make-marker) org-mark-ring))
10892 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10893 org-mark-ring)
10895 (defun org-mark-ring-push (&optional pos buffer)
10896 "Put the current position or POS into the mark ring and rotate it."
10897 (interactive)
10898 (setq pos (or pos (point)))
10899 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10900 (move-marker (car org-mark-ring)
10901 (or pos (point))
10902 (or buffer (current-buffer)))
10903 (message "%s"
10904 (substitute-command-keys
10905 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10907 (defun org-mark-ring-goto (&optional n)
10908 "Jump to the previous position in the mark ring.
10909 With prefix arg N, jump back that many stored positions. When
10910 called several times in succession, walk through the entire ring.
10911 Org-mode commands jumping to a different position in the current file,
10912 or to another Org-mode file, automatically push the old position
10913 onto the ring."
10914 (interactive "p")
10915 (let (p m)
10916 (if (eq last-command this-command)
10917 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10918 (setq p org-mark-ring))
10919 (setq org-mark-ring-last-goto p)
10920 (setq m (car p))
10921 (org-pop-to-buffer-same-window (marker-buffer m))
10922 (goto-char m)
10923 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10925 (defun org-remove-angle-brackets (s)
10926 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10927 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10929 (defun org-add-angle-brackets (s)
10930 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10931 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10933 (defun org-remove-double-quotes (s)
10934 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10935 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10938 ;;; Following specific links
10940 (defun org-follow-timestamp-link ()
10941 "Open an agenda view for the time-stamp date/range at point."
10942 (cond
10943 ((org-at-date-range-p t)
10944 (let ((org-agenda-start-on-weekday)
10945 (t1 (match-string 1))
10946 (t2 (match-string 2)) tt1 tt2)
10947 (setq tt1 (time-to-days (org-time-string-to-time t1))
10948 tt2 (time-to-days (org-time-string-to-time t2)))
10949 (let ((org-agenda-buffer-tmp-name
10950 (format "*Org Agenda(a:%s)"
10951 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10952 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10953 ((org-at-timestamp-p t)
10954 (let ((org-agenda-buffer-tmp-name
10955 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10956 (org-agenda-list nil (time-to-days (org-time-string-to-time
10957 (substring (match-string 1) 0 10)))
10958 1)))
10959 (t (error "This should not happen"))))
10962 ;;; Following file links
10963 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10964 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10965 (declare-function mailcap-mime-info
10966 "mailcap" (string &optional request no-decode))
10967 (defvar org-wait nil)
10968 (defun org-open-file (path &optional in-emacs line search)
10969 "Open the file at PATH.
10970 First, this expands any special file name abbreviations. Then the
10971 configuration variable `org-file-apps' is checked if it contains an
10972 entry for this file type, and if yes, the corresponding command is launched.
10974 If no application is found, Emacs simply visits the file.
10976 With optional prefix argument IN-EMACS, Emacs will visit the file.
10977 With a double \\[universal-argument] \\[universal-argument] \
10978 prefix arg, Org tries to avoid opening in Emacs
10979 and to use an external application to visit the file.
10981 Optional LINE specifies a line to go to, optional SEARCH a string
10982 to search for. If LINE or SEARCH is given, the file will be
10983 opened in Emacs, unless an entry from org-file-apps that makes
10984 use of groups in a regexp matches.
10986 If you want to change the way frames are used when following a
10987 link, please customize `org-link-frame-setup'.
10989 If the file does not exist, an error is thrown."
10990 (let* ((file (if (equal path "")
10991 buffer-file-name
10992 (substitute-in-file-name (expand-file-name path))))
10993 (file-apps (append org-file-apps (org-default-apps)))
10994 (apps (org-remove-if
10995 'org-file-apps-entry-match-against-dlink-p file-apps))
10996 (apps-dlink (org-remove-if-not
10997 'org-file-apps-entry-match-against-dlink-p file-apps))
10998 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10999 (dirp (if remp nil (file-directory-p file)))
11000 (file (if (and dirp org-open-directory-means-index-dot-org)
11001 (concat (file-name-as-directory file) "index.org")
11002 file))
11003 (a-m-a-p (assq 'auto-mode apps))
11004 (dfile (downcase file))
11005 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
11006 (link (cond ((and (eq line nil)
11007 (eq search nil))
11008 file)
11009 (line
11010 (concat file "::" (number-to-string line)))
11011 (search
11012 (concat file "::" search))))
11013 (dlink (downcase link))
11014 (old-buffer (current-buffer))
11015 (old-pos (point))
11016 (old-mode major-mode)
11017 ext cmd link-match-data)
11018 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11019 (setq ext (match-string 1 dfile))
11020 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11021 (setq ext (match-string 1 dfile))))
11022 (cond
11023 ((member in-emacs '((16) system))
11024 (setq cmd (cdr (assoc 'system apps))))
11025 (in-emacs (setq cmd 'emacs))
11027 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11028 (and dirp (cdr (assoc 'directory apps)))
11029 ; first, try matching against apps-dlink
11030 ; if we get a match here, store the match data for later
11031 (let ((match (assoc-default dlink apps-dlink
11032 'string-match)))
11033 (if match
11034 (progn (setq link-match-data (match-data))
11035 match)
11036 (progn (setq in-emacs (or in-emacs line search))
11037 nil))) ; if we have no match in apps-dlink,
11038 ; always open the file in emacs if line or search
11039 ; is given (for backwards compatibility)
11040 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11041 'string-match)
11042 (cdr (assoc ext apps))
11043 (cdr (assoc t apps))))))
11044 (when (eq cmd 'system)
11045 (setq cmd (cdr (assoc 'system apps))))
11046 (when (eq cmd 'default)
11047 (setq cmd (cdr (assoc t apps))))
11048 (when (eq cmd 'mailcap)
11049 (require 'mailcap)
11050 (mailcap-parse-mailcaps)
11051 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11052 (command (mailcap-mime-info mime-type)))
11053 (if (stringp command)
11054 (setq cmd command)
11055 (setq cmd 'emacs))))
11056 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11057 (not (file-exists-p file))
11058 (not org-open-non-existing-files))
11059 (user-error "No such file: %s" file))
11060 (cond
11061 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11062 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11063 (while (string-match "['\"]%s['\"]" cmd)
11064 (setq cmd (replace-match "%s" t t cmd)))
11065 (while (string-match "%s" cmd)
11066 (setq cmd (replace-match
11067 (save-match-data
11068 (shell-quote-argument
11069 (convert-standard-filename file)))
11070 t t cmd)))
11072 ;; Replace "%1", "%2" etc. in command with group matches from regex
11073 (save-match-data
11074 (let ((match-index 1)
11075 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11076 (set-match-data link-match-data)
11077 (while (<= match-index number-of-groups)
11078 (let ((regex (concat "%" (number-to-string match-index)))
11079 (replace-with (match-string match-index dlink)))
11080 (while (string-match regex cmd)
11081 (setq cmd (replace-match replace-with t t cmd))))
11082 (setq match-index (+ match-index 1)))))
11084 (save-window-excursion
11085 (message "Running %s...done" cmd)
11086 (start-process-shell-command cmd nil cmd)
11087 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11088 ((or (stringp cmd)
11089 (eq cmd 'emacs))
11090 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11091 (widen)
11092 (if line (org-goto-line line)
11093 (if search (org-link-search search))))
11094 ((consp cmd)
11095 (let ((file (convert-standard-filename file)))
11096 (save-match-data
11097 (set-match-data link-match-data)
11098 (eval cmd))))
11099 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11100 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11101 (or (not (equal old-buffer (current-buffer)))
11102 (not (equal old-pos (point))))
11103 (org-mark-ring-push old-pos old-buffer))))
11105 (defun org-file-apps-entry-match-against-dlink-p (entry)
11106 "This function returns non-nil if `entry' uses a regular
11107 expression which should be matched against the whole link by
11108 org-open-file.
11110 It assumes that is the case when the entry uses a regular
11111 expression which has at least one grouping construct and the
11112 action is either a lisp form or a command string containing
11113 '%1', i.e. using at least one subexpression match as a
11114 parameter."
11115 (let ((selector (car entry))
11116 (action (cdr entry)))
11117 (if (stringp selector)
11118 (and (> (regexp-opt-depth selector) 0)
11119 (or (and (stringp action)
11120 (string-match "%[0-9]" action))
11121 (consp action)))
11122 nil)))
11124 (defun org-default-apps ()
11125 "Return the default applications for this operating system."
11126 (cond
11127 ((eq system-type 'darwin)
11128 org-file-apps-defaults-macosx)
11129 ((eq system-type 'windows-nt)
11130 org-file-apps-defaults-windowsnt)
11131 (t org-file-apps-defaults-gnu)))
11133 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11134 "Convert extensions to regular expressions in the cars of LIST.
11135 Also, weed out any non-string entries, because the return value is used
11136 only for regexp matching.
11137 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11138 point to the symbol `emacs', indicating that the file should
11139 be opened in Emacs."
11140 (append
11141 (delq nil
11142 (mapcar (lambda (x)
11143 (if (not (stringp (car x)))
11145 (if (string-match "\\W" (car x))
11147 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11148 list))
11149 (if add-auto-mode
11150 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11152 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11153 (defun org-file-remote-p (file)
11154 "Test whether FILE specifies a location on a remote system.
11155 Return non-nil if the location is indeed remote.
11157 For example, the filename \"/user@host:/foo\" specifies a location
11158 on the system \"/user@host:\"."
11159 (cond ((fboundp 'file-remote-p)
11160 (file-remote-p file))
11161 ((fboundp 'tramp-handle-file-remote-p)
11162 (tramp-handle-file-remote-p file))
11163 ((and (boundp 'ange-ftp-name-format)
11164 (string-match (car ange-ftp-name-format) file))
11165 t)))
11168 ;;;; Refiling
11170 (defun org-get-org-file ()
11171 "Read a filename, with default directory `org-directory'."
11172 (let ((default (or org-default-notes-file remember-data-file)))
11173 (read-file-name (format "File name [%s]: " default)
11174 (file-name-as-directory org-directory)
11175 default)))
11177 (defun org-notes-order-reversed-p ()
11178 "Check if the current file should receive notes in reversed order."
11179 (cond
11180 ((not org-reverse-note-order) nil)
11181 ((eq t org-reverse-note-order) t)
11182 ((not (listp org-reverse-note-order)) nil)
11183 (t (catch 'exit
11184 (let ((all org-reverse-note-order)
11185 entry)
11186 (while (setq entry (pop all))
11187 (if (string-match (car entry) buffer-file-name)
11188 (throw 'exit (cdr entry))))
11189 nil)))))
11191 (defvar org-refile-target-table nil
11192 "The list of refile targets, created by `org-refile'.")
11194 (defvar org-agenda-new-buffers nil
11195 "Buffers created to visit agenda files.")
11197 (defvar org-refile-cache nil
11198 "Cache for refile targets.")
11200 (defvar org-refile-markers nil
11201 "All the markers used for caching refile locations.")
11203 (defun org-refile-marker (pos)
11204 "Get a new refile marker, but only if caching is in use."
11205 (if (not org-refile-use-cache)
11207 (let ((m (make-marker)))
11208 (move-marker m pos)
11209 (push m org-refile-markers)
11210 m)))
11212 (defun org-refile-cache-clear ()
11213 "Clear the refile cache and disable all the markers."
11214 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11215 (setq org-refile-markers nil)
11216 (setq org-refile-cache nil)
11217 (message "Refile cache has been cleared"))
11219 (defun org-refile-cache-check-set (set)
11220 "Check if all the markers in the cache still have live buffers."
11221 (let (marker)
11222 (catch 'exit
11223 (while (and set (setq marker (nth 3 (pop set))))
11224 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11225 (when (and marker (null (marker-buffer marker)))
11226 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11227 (sit-for 3)
11228 (throw 'exit nil)))
11229 t)))
11231 (defun org-refile-cache-put (set &rest identifiers)
11232 "Push the refile targets SET into the cache, under IDENTIFIERS."
11233 (let* ((key (sha1 (prin1-to-string identifiers)))
11234 (entry (assoc key org-refile-cache)))
11235 (if entry
11236 (setcdr entry set)
11237 (push (cons key set) org-refile-cache))))
11239 (defun org-refile-cache-get (&rest identifiers)
11240 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11241 (cond
11242 ((not org-refile-cache) nil)
11243 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11245 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11246 org-refile-cache))))
11247 (and set (org-refile-cache-check-set set) set)))))
11249 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11250 "Produce a table with refile targets."
11251 (let ((case-fold-search nil)
11252 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11253 (entries (or org-refile-targets '((nil . (:level . 1)))))
11254 targets tgs txt re files f desc descre fast-path-p level pos0)
11255 (message "Getting targets...")
11256 (with-current-buffer (or default-buffer (current-buffer))
11257 (while (setq entry (pop entries))
11258 (setq files (car entry) desc (cdr entry))
11259 (setq fast-path-p nil)
11260 (cond
11261 ((null files) (setq files (list (current-buffer))))
11262 ((eq files 'org-agenda-files)
11263 (setq files (org-agenda-files 'unrestricted)))
11264 ((and (symbolp files) (fboundp files))
11265 (setq files (funcall files)))
11266 ((and (symbolp files) (boundp files))
11267 (setq files (symbol-value files))))
11268 (if (stringp files) (setq files (list files)))
11269 (cond
11270 ((eq (car desc) :tag)
11271 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11272 ((eq (car desc) :todo)
11273 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11274 ((eq (car desc) :regexp)
11275 (setq descre (cdr desc)))
11276 ((eq (car desc) :level)
11277 (setq descre (concat "^\\*\\{" (number-to-string
11278 (if org-odd-levels-only
11279 (1- (* 2 (cdr desc)))
11280 (cdr desc)))
11281 "\\}[ \t]")))
11282 ((eq (car desc) :maxlevel)
11283 (setq fast-path-p t)
11284 (setq descre (concat "^\\*\\{1," (number-to-string
11285 (if org-odd-levels-only
11286 (1- (* 2 (cdr desc)))
11287 (cdr desc)))
11288 "\\}[ \t]")))
11289 (t (error "Bad refiling target description %s" desc)))
11290 (while (setq f (pop files))
11291 (with-current-buffer
11292 (if (bufferp f) f (org-get-agenda-file-buffer f))
11294 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11295 (progn
11296 (if (bufferp f) (setq f (buffer-file-name
11297 (buffer-base-buffer f))))
11298 (setq f (and f (expand-file-name f)))
11299 (if (eq org-refile-use-outline-path 'file)
11300 (push (list (file-name-nondirectory f) f nil nil) tgs))
11301 (save-excursion
11302 (save-restriction
11303 (widen)
11304 (goto-char (point-min))
11305 (while (re-search-forward descre nil t)
11306 (goto-char (setq pos0 (point-at-bol)))
11307 (catch 'next
11308 (when org-refile-target-verify-function
11309 (save-match-data
11310 (or (funcall org-refile-target-verify-function)
11311 (throw 'next t))))
11312 (when (and (looking-at org-complex-heading-regexp)
11313 (not (member (match-string 4) excluded-entries))
11314 (match-string 4))
11315 (setq level (org-reduced-level
11316 (- (match-end 1) (match-beginning 1)))
11317 txt (org-link-display-format (match-string 4))
11318 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11319 re (format org-complex-heading-regexp-format
11320 (regexp-quote (match-string 4))))
11321 (when org-refile-use-outline-path
11322 (setq txt (mapconcat
11323 'org-protect-slash
11324 (append
11325 (if (eq org-refile-use-outline-path
11326 'file)
11327 (list (file-name-nondirectory
11328 (buffer-file-name
11329 (buffer-base-buffer))))
11330 (if (eq org-refile-use-outline-path
11331 'full-file-path)
11332 (list (buffer-file-name
11333 (buffer-base-buffer)))))
11334 (org-get-outline-path fast-path-p
11335 level txt)
11336 (list txt))
11337 "/")))
11338 (push (list txt f re (org-refile-marker (point)))
11339 tgs)))
11340 (when (= (point) pos0)
11341 ;; verification function has not moved point
11342 (goto-char (point-at-eol))))))))
11343 (when org-refile-use-cache
11344 (org-refile-cache-put tgs (buffer-file-name) descre))
11345 (setq targets (append tgs targets))))))
11346 (message "Getting targets...done")
11347 (nreverse targets)))
11349 (defun org-protect-slash (s)
11350 (while (string-match "/" s)
11351 (setq s (replace-match "\\" t t s)))
11354 (defvar org-olpa (make-vector 20 nil))
11356 (defun org-get-outline-path (&optional fastp level heading)
11357 "Return the outline path to the current entry, as a list.
11359 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11360 routine which makes outline path derivations for an entire file,
11361 avoiding backtracing. Refile target collection makes use of that."
11362 (if fastp
11363 (progn
11364 (if (> level 19)
11365 (error "Outline path failure, more than 19 levels"))
11366 (loop for i from level upto 19 do
11367 (aset org-olpa i nil))
11368 (prog1
11369 (delq nil (append org-olpa nil))
11370 (aset org-olpa level heading)))
11371 (let (rtn case-fold-search)
11372 (save-excursion
11373 (save-restriction
11374 (widen)
11375 (while (org-up-heading-safe)
11376 (when (looking-at org-complex-heading-regexp)
11377 (push (org-trim
11378 (replace-regexp-in-string
11379 ;; Remove statistical/checkboxes cookies
11380 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11381 (org-match-string-no-properties 4)))
11382 rtn)))
11383 rtn)))))
11385 (defun org-format-outline-path (path &optional width prefix separator)
11386 "Format the outline path PATH for display.
11387 WIDTH is the maximum number of characters that is available.
11388 PREFIX is a prefix to be included in the returned string,
11389 such as the file name.
11390 SEPARATOR is inserted between the different parts of the path,
11391 the default is \"/\"."
11392 (setq width (or width 79))
11393 (if prefix (setq width (- width (length prefix))))
11394 (if (not path)
11395 (or prefix "")
11396 (let* ((nsteps (length path))
11397 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11398 (maxwidth (if (<= total-width width)
11399 10000 ;; everything fits
11400 ;; we need to shorten the level headings
11401 (/ (- width nsteps) nsteps)))
11402 (org-odd-levels-only nil)
11403 (n 0)
11404 (total (1+ (length prefix))))
11405 (setq maxwidth (max maxwidth 10))
11406 (concat prefix
11407 (if prefix (or separator "/"))
11408 (mapconcat
11409 (lambda (h)
11410 (setq n (1+ n))
11411 (if (and (= n nsteps) (< maxwidth 10000))
11412 (setq maxwidth (- total-width total)))
11413 (if (< (length h) maxwidth)
11414 (progn (setq total (+ total (length h) 1)) h)
11415 (setq h (substring h 0 (- maxwidth 2))
11416 total (+ total maxwidth 1))
11417 (if (string-match "[ \t]+\\'" h)
11418 (setq h (substring h 0 (match-beginning 0))))
11419 (setq h (concat h "..")))
11420 (org-add-props h nil 'face
11421 (nth (% (1- n) org-n-level-faces)
11422 org-level-faces))
11424 path (or separator "/"))))))
11426 (defun org-display-outline-path (&optional file current separator just-return-string)
11427 "Display the current outline path in the echo area.
11429 If FILE is non-nil, prepend the output with the file name.
11430 If CURRENT is non-nil, append the current heading to the output.
11431 SEPARATOR is passed through to `org-format-outline-path'. It separates
11432 the different parts of the path and defaults to \"/\".
11433 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11434 (interactive "P")
11435 (let* (case-fold-search
11436 (bfn (buffer-file-name (buffer-base-buffer)))
11437 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11438 res)
11439 (if current (setq path (append path
11440 (save-excursion
11441 (org-back-to-heading t)
11442 (if (looking-at org-complex-heading-regexp)
11443 (list (match-string 4)))))))
11444 (setq res
11445 (org-format-outline-path
11446 path
11447 (1- (frame-width))
11448 (and file bfn (concat (file-name-nondirectory bfn) separator))
11449 separator))
11450 (if just-return-string
11451 (org-no-properties res)
11452 (org-unlogged-message "%s" res))))
11454 (defvar org-refile-history nil
11455 "History for refiling operations.")
11457 (defvar org-after-refile-insert-hook nil
11458 "Hook run after `org-refile' has inserted its stuff at the new location.
11459 Note that this is still *before* the stuff will be removed from
11460 the *old* location.")
11462 (defvar org-capture-last-stored-marker)
11463 (defvar org-refile-keep nil
11464 "Non-nil means `org-refile' will copy instead of refile.")
11466 (defun org-copy ()
11467 "Like `org-refile', but copy."
11468 (interactive)
11469 (let ((org-refile-keep t))
11470 (funcall 'org-refile nil nil nil "Copy")))
11472 (defun org-refile (&optional goto default-buffer rfloc msg)
11473 "Move the entry or entries at point to another heading.
11474 The list of target headings is compiled using the information in
11475 `org-refile-targets', which see.
11477 At the target location, the entry is filed as a subitem of the target
11478 heading. Depending on `org-reverse-note-order', the new subitem will
11479 either be the first or the last subitem.
11481 If there is an active region, all entries in that region will be moved.
11482 However, the region must fulfill the requirement that the first heading
11483 is the first one sets the top-level of the moved text - at most siblings
11484 below it are allowed.
11486 With prefix arg GOTO, the command will only visit the target location
11487 and not actually move anything.
11489 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11490 go to the location where the last refiling operation has put the subtree.
11492 With a numeric prefix argument of `2', refile to the running clock.
11494 With a numeric prefix argument of `3', emulate `org-refile-keep'
11495 being set to `t' and copy to the target location, don't move it.
11496 Beware that keeping refiled entries may result in duplicated ID
11497 properties.
11499 RFLOC can be a refile location obtained in a different way.
11501 MSG is a string to replace \"Refile\" in the default prompt with
11502 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11504 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11506 If you are using target caching (see `org-refile-use-cache'),
11507 you have to clear the target cache in order to find new targets.
11508 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11509 prefix argument (`C-u C-u C-u C-c C-w')."
11511 (interactive "P")
11512 (if (member goto '(0 (64)))
11513 (org-refile-cache-clear)
11514 (let* ((actionmsg (or msg "Refile"))
11515 (cbuf (current-buffer))
11516 (regionp (org-region-active-p))
11517 (region-start (and regionp (region-beginning)))
11518 (region-end (and regionp (region-end)))
11519 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11520 (org-refile-keep (if (equal goto 3) t org-refile-keep))
11521 pos it nbuf file re level reversed)
11522 (setq last-command nil)
11523 (when regionp
11524 (goto-char region-start)
11525 (or (bolp) (goto-char (point-at-bol)))
11526 (setq region-start (point))
11527 (unless (or (org-kill-is-subtree-p
11528 (buffer-substring region-start region-end))
11529 (prog1 org-refile-active-region-within-subtree
11530 (let ((s (point-at-eol)))
11531 (org-toggle-heading)
11532 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11533 (user-error "The region is not a (sequence of) subtree(s)")))
11534 (if (equal goto '(16))
11535 (org-refile-goto-last-stored)
11536 (when (or
11537 (and (equal goto 2)
11538 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11539 (prog1
11540 (setq it (list (or org-clock-heading "running clock")
11541 (buffer-file-name
11542 (marker-buffer org-clock-hd-marker))
11544 (marker-position org-clock-hd-marker)))
11545 (setq goto nil)))
11546 (setq it (or rfloc
11547 (let (heading-text)
11548 (save-excursion
11549 (unless goto
11550 (org-back-to-heading t)
11551 (setq heading-text
11552 (nth 4 (org-heading-components))))
11554 (org-refile-get-location
11555 (cond (goto "Goto")
11556 (regionp (concat actionmsg " region to"))
11557 (t (concat actionmsg " subtree \""
11558 heading-text "\" to")))
11559 default-buffer
11560 (and (not (equal '(4) goto))
11561 org-refile-allow-creating-parent-nodes)
11562 goto))))))
11563 (setq file (nth 1 it)
11564 re (nth 2 it)
11565 pos (nth 3 it))
11566 (if (and (not goto)
11568 (equal (buffer-file-name) file)
11569 (if regionp
11570 (and (>= pos region-start)
11571 (<= pos region-end))
11572 (and (>= pos (point))
11573 (< pos (save-excursion
11574 (org-end-of-subtree t t))))))
11575 (error "Cannot refile to position inside the tree or region"))
11577 (setq nbuf (or (find-buffer-visiting file)
11578 (find-file-noselect file)))
11579 (if (and goto (not (equal goto 3)))
11580 (progn
11581 (org-pop-to-buffer-same-window nbuf)
11582 (goto-char pos)
11583 (org-show-context 'org-goto))
11584 (if regionp
11585 (progn
11586 (org-kill-new (buffer-substring region-start region-end))
11587 (org-save-markers-in-region region-start region-end))
11588 (org-copy-subtree 1 nil t))
11589 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11590 (find-file-noselect file)))
11591 (setq reversed (org-notes-order-reversed-p))
11592 (save-excursion
11593 (save-restriction
11594 (widen)
11595 (if pos
11596 (progn
11597 (goto-char pos)
11598 (looking-at org-outline-regexp)
11599 (setq level (org-get-valid-level (funcall outline-level) 1))
11600 (goto-char
11601 (if reversed
11602 (or (outline-next-heading) (point-max))
11603 (or (save-excursion (org-get-next-sibling))
11604 (org-end-of-subtree t t)
11605 (point-max)))))
11606 (setq level 1)
11607 (if (not reversed)
11608 (goto-char (point-max))
11609 (goto-char (point-min))
11610 (or (outline-next-heading) (goto-char (point-max)))))
11611 (if (not (bolp)) (newline))
11612 (org-paste-subtree level)
11613 (when org-log-refile
11614 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11615 (unless (eq org-log-refile 'note)
11616 (save-excursion (org-add-log-note))))
11617 (and org-auto-align-tags
11618 (let ((org-loop-over-headlines-in-active-region nil))
11619 (org-set-tags nil t)))
11620 (let ((bookmark-name (plist-get org-bookmark-names-plist
11621 :last-refile)))
11622 (when bookmark-name
11623 (with-demoted-errors
11624 (bookmark-set bookmark-name))))
11625 ;; If we are refiling for capture, make sure that the
11626 ;; last-capture pointers point here
11627 (when (org-bound-and-true-p org-refile-for-capture)
11628 (let ((bookmark-name (plist-get org-bookmark-names-plist
11629 :last-capture-marker)))
11630 (when bookmark-name
11631 (with-demoted-errors
11632 (bookmark-set bookmark-name))))
11633 (move-marker org-capture-last-stored-marker (point)))
11634 (if (fboundp 'deactivate-mark) (deactivate-mark))
11635 (run-hooks 'org-after-refile-insert-hook))))
11636 (unless org-refile-keep
11637 (if regionp
11638 (delete-region (point) (+ (point) (- region-end region-start)))
11639 (delete-region
11640 (and (org-back-to-heading t) (point))
11641 (min (buffer-size) (org-end-of-subtree t t) (point)))))
11642 (when (featurep 'org-inlinetask)
11643 (org-inlinetask-remove-END-maybe))
11644 (setq org-markers-to-move nil)
11645 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11647 (defun org-refile-goto-last-stored ()
11648 "Go to the location where the last refile was stored."
11649 (interactive)
11650 (bookmark-jump "org-refile-last-stored")
11651 (message "This is the location of the last refile"))
11653 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11654 no-exclude)
11655 "Prompt the user for a refile location, using PROMPT.
11656 PROMPT should not be suffixed with a colon and a space, because
11657 this function appends the default value from
11658 `org-refile-history' automatically, if that is not empty.
11659 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11660 this is used for the GOTO interface."
11661 (let ((org-refile-targets org-refile-targets)
11662 (org-refile-use-outline-path org-refile-use-outline-path)
11663 excluded-entries)
11664 (when (and (derived-mode-p 'org-mode)
11665 (not org-refile-use-cache)
11666 (not no-exclude))
11667 (org-map-tree
11668 (lambda()
11669 (setq excluded-entries
11670 (append excluded-entries (list (org-get-heading t t)))))))
11671 (setq org-refile-target-table
11672 (org-refile-get-targets default-buffer excluded-entries)))
11673 (unless org-refile-target-table
11674 (user-error "No refile targets"))
11675 (let* ((cbuf (current-buffer))
11676 (partial-completion-mode nil)
11677 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11678 (cfunc (if (and org-refile-use-outline-path
11679 org-outline-path-complete-in-steps)
11680 'org-olpath-completing-read
11681 'org-icompleting-read))
11682 (extra (if org-refile-use-outline-path "/" ""))
11683 (cbnex (concat (buffer-name) extra))
11684 (filename (and cfn (expand-file-name cfn)))
11685 (tbl (mapcar
11686 (lambda (x)
11687 (if (and (not (member org-refile-use-outline-path
11688 '(file full-file-path)))
11689 (not (equal filename (nth 1 x))))
11690 (cons (concat (car x) extra " ("
11691 (file-name-nondirectory (nth 1 x)) ")")
11692 (cdr x))
11693 (cons (concat (car x) extra) (cdr x))))
11694 org-refile-target-table))
11695 (completion-ignore-case t)
11696 cdef
11697 (prompt (concat prompt
11698 (or (and (car org-refile-history)
11699 (concat " (default " (car org-refile-history) ")"))
11700 (and (assoc cbnex tbl) (setq cdef cbnex)
11701 (concat " (default " cbnex ")"))) ": "))
11702 pa answ parent-target child parent old-hist)
11703 (setq old-hist org-refile-history)
11704 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11705 nil 'org-refile-history (or cdef (car org-refile-history))))
11706 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11707 (org-refile-check-position pa)
11708 (if pa
11709 (progn
11710 (when (or (not org-refile-history)
11711 (not (eq old-hist org-refile-history))
11712 (not (equal (car pa) (car org-refile-history))))
11713 (setq org-refile-history
11714 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11715 org-refile-history
11716 (cdr org-refile-history))))
11717 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11718 (pop org-refile-history)))
11720 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11721 (progn
11722 (setq parent (match-string 1 answ)
11723 child (match-string 2 answ))
11724 (setq parent-target (or (assoc parent tbl)
11725 (assoc (concat parent "/") tbl)))
11726 (when (and parent-target
11727 (or (eq new-nodes t)
11728 (and (eq new-nodes 'confirm)
11729 (y-or-n-p (format "Create new node \"%s\"? "
11730 child)))))
11731 (org-refile-new-child parent-target child)))
11732 (user-error "Invalid target location")))))
11734 (declare-function org-string-nw-p "org-macs" (s))
11735 (defun org-refile-check-position (refile-pointer)
11736 "Check if the refile pointer matches the headline to which it points."
11737 (let* ((file (nth 1 refile-pointer))
11738 (re (nth 2 refile-pointer))
11739 (pos (nth 3 refile-pointer))
11740 buffer)
11741 (if (and (not (markerp pos)) (not file))
11742 (user-error "Please save the buffer to a file before refiling")
11743 (when (org-string-nw-p re)
11744 (setq buffer (if (markerp pos)
11745 (marker-buffer pos)
11746 (or (find-buffer-visiting file)
11747 (find-file-noselect file))))
11748 (with-current-buffer buffer
11749 (save-excursion
11750 (save-restriction
11751 (widen)
11752 (goto-char pos)
11753 (beginning-of-line 1)
11754 (unless (org-looking-at-p re)
11755 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11757 (defun org-refile-new-child (parent-target child)
11758 "Use refile target PARENT-TARGET to add new CHILD below it."
11759 (unless parent-target
11760 (error "Cannot find parent for new node"))
11761 (let ((file (nth 1 parent-target))
11762 (pos (nth 3 parent-target))
11763 level)
11764 (with-current-buffer (or (find-buffer-visiting file)
11765 (find-file-noselect file))
11766 (save-excursion
11767 (save-restriction
11768 (widen)
11769 (if pos
11770 (goto-char pos)
11771 (goto-char (point-max))
11772 (if (not (bolp)) (newline)))
11773 (when (looking-at org-outline-regexp)
11774 (setq level (funcall outline-level))
11775 (org-end-of-subtree t t))
11776 (org-back-over-empty-lines)
11777 (insert "\n" (make-string
11778 (if pos (org-get-valid-level level 1) 1) ?*)
11779 " " child "\n")
11780 (beginning-of-line 0)
11781 (list (concat (car parent-target) "/" child) file "" (point)))))))
11783 (defun org-olpath-completing-read (prompt collection &rest args)
11784 "Read an outline path like a file name."
11785 (let ((thetable collection)
11786 (org-completion-use-ido nil) ; does not work with ido.
11787 (org-completion-use-iswitchb nil)) ; or iswitchb
11788 (apply
11789 'org-icompleting-read prompt
11790 (lambda (string predicate &optional flag)
11791 (let (rtn r f (l (length string)))
11792 (cond
11793 ((eq flag nil)
11794 ;; try completion
11795 (try-completion string thetable))
11796 ((eq flag t)
11797 ;; all-completions
11798 (setq rtn (all-completions string thetable predicate))
11799 (mapcar
11800 (lambda (x)
11801 (setq r (substring x l))
11802 (if (string-match " ([^)]*)$" x)
11803 (setq f (match-string 0 x))
11804 (setq f ""))
11805 (if (string-match "/" r)
11806 (concat string (substring r 0 (match-end 0)) f)
11808 rtn))
11809 ((eq flag 'lambda)
11810 ;; exact match?
11811 (assoc string thetable)))))
11812 args)))
11814 ;;;; Dynamic blocks
11816 (defun org-find-dblock (name)
11817 "Find the first dynamic block with name NAME in the buffer.
11818 If not found, stay at current position and return nil."
11819 (let ((case-fold-search t) pos)
11820 (save-excursion
11821 (goto-char (point-min))
11822 (setq pos (and (re-search-forward
11823 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11824 (match-beginning 0))))
11825 (if pos (goto-char pos))
11826 pos))
11828 (defconst org-dblock-start-re
11829 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11830 "Matches the start line of a dynamic block, with parameters.")
11832 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11833 "Matches the end of a dynamic block.")
11835 (defun org-create-dblock (plist)
11836 "Create a dynamic block section, with parameters taken from PLIST.
11837 PLIST must contain a :name entry which is used as name of the block."
11838 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11839 (end-of-line 1)
11840 (newline))
11841 (let ((col (current-column))
11842 (name (plist-get plist :name)))
11843 (insert "#+BEGIN: " name)
11844 (while plist
11845 (if (eq (car plist) :name)
11846 (setq plist (cddr plist))
11847 (insert " " (prin1-to-string (pop plist)))))
11848 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11849 (beginning-of-line -2)))
11851 (defun org-prepare-dblock ()
11852 "Prepare dynamic block for refresh.
11853 This empties the block, puts the cursor at the insert position and returns
11854 the property list including an extra property :name with the block name."
11855 (unless (looking-at org-dblock-start-re)
11856 (user-error "Not at a dynamic block"))
11857 (let* ((begdel (1+ (match-end 0)))
11858 (name (org-no-properties (match-string 1)))
11859 (params (append (list :name name)
11860 (read (concat "(" (match-string 3) ")")))))
11861 (save-excursion
11862 (beginning-of-line 1)
11863 (skip-chars-forward " \t")
11864 (setq params (plist-put params :indentation-column (current-column))))
11865 (unless (re-search-forward org-dblock-end-re nil t)
11866 (error "Dynamic block not terminated"))
11867 (setq params
11868 (append params
11869 (list :content (buffer-substring
11870 begdel (match-beginning 0)))))
11871 (delete-region begdel (match-beginning 0))
11872 (goto-char begdel)
11873 (open-line 1)
11874 params))
11876 (defun org-map-dblocks (&optional command)
11877 "Apply COMMAND to all dynamic blocks in the current buffer.
11878 If COMMAND is not given, use `org-update-dblock'."
11879 (let ((cmd (or command 'org-update-dblock)))
11880 (save-excursion
11881 (goto-char (point-min))
11882 (while (re-search-forward org-dblock-start-re nil t)
11883 (goto-char (match-beginning 0))
11884 (save-excursion
11885 (condition-case nil
11886 (funcall cmd)
11887 (error (message "Error during update of dynamic block"))))
11888 (unless (re-search-forward org-dblock-end-re nil t)
11889 (error "Dynamic block not terminated"))))))
11891 (defun org-dblock-update (&optional arg)
11892 "User command for updating dynamic blocks.
11893 Update the dynamic block at point. With prefix ARG, update all dynamic
11894 blocks in the buffer."
11895 (interactive "P")
11896 (if arg
11897 (org-update-all-dblocks)
11898 (or (looking-at org-dblock-start-re)
11899 (org-beginning-of-dblock))
11900 (org-update-dblock)))
11902 (defun org-update-dblock ()
11903 "Update the dynamic block at point.
11904 This means to empty the block, parse for parameters and then call
11905 the correct writing function."
11906 (interactive)
11907 (save-window-excursion
11908 (let* ((pos (point))
11909 (line (org-current-line))
11910 (params (org-prepare-dblock))
11911 (name (plist-get params :name))
11912 (indent (plist-get params :indentation-column))
11913 (cmd (intern (concat "org-dblock-write:" name))))
11914 (message "Updating dynamic block `%s' at line %d..." name line)
11915 (funcall cmd params)
11916 (message "Updating dynamic block `%s' at line %d...done" name line)
11917 (goto-char pos)
11918 (when (and indent (> indent 0))
11919 (setq indent (make-string indent ?\ ))
11920 (save-excursion
11921 (org-beginning-of-dblock)
11922 (forward-line 1)
11923 (while (not (looking-at org-dblock-end-re))
11924 (insert indent)
11925 (beginning-of-line 2))
11926 (when (looking-at org-dblock-end-re)
11927 (and (looking-at "[ \t]+")
11928 (replace-match ""))
11929 (insert indent)))))))
11931 (defun org-beginning-of-dblock ()
11932 "Find the beginning of the dynamic block at point.
11933 Error if there is no such block at point."
11934 (let ((pos (point))
11935 beg)
11936 (end-of-line 1)
11937 (if (and (re-search-backward org-dblock-start-re nil t)
11938 (setq beg (match-beginning 0))
11939 (re-search-forward org-dblock-end-re nil t)
11940 (> (match-end 0) pos))
11941 (goto-char beg)
11942 (goto-char pos)
11943 (error "Not in a dynamic block"))))
11945 (defun org-update-all-dblocks ()
11946 "Update all dynamic blocks in the buffer.
11947 This function can be used in a hook."
11948 (interactive)
11949 (when (derived-mode-p 'org-mode)
11950 (org-map-dblocks 'org-update-dblock)))
11953 ;;;; Completion
11955 (declare-function org-export-backend-name "org-export" (cl-x))
11956 (declare-function org-export-backend-options "org-export" (cl-x))
11957 (defun org-get-export-keywords ()
11958 "Return a list of all currently understood export keywords.
11959 Export keywords include options, block names, attributes and
11960 keywords relative to each registered export back-end."
11961 (let (keywords)
11962 (dolist (backend
11963 (org-bound-and-true-p org-export--registered-backends)
11964 (delq nil keywords))
11965 ;; Back-end name (for keywords, like #+LATEX:)
11966 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
11967 (dolist (option-entry (org-export-backend-options backend))
11968 ;; Back-end options.
11969 (push (nth 1 option-entry) keywords)))))
11971 (defconst org-options-keywords
11972 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11973 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11974 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11975 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11976 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11978 (defcustom org-structure-template-alist
11979 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC" "<src lang=\"?\">\n\n</src>")
11980 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE" "<example>\n?\n</example>")
11981 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE" "<quote>\n?\n</quote>")
11982 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE" "<verse>\n?\n</verse>")
11983 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM" "<verbatim>\n?\n</verbatim>")
11984 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER" "<center>\n?\n</center>")
11985 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11986 "<literal style=\"latex\">\n?\n</literal>")
11987 ("L" "#+LaTeX: " "<literal style=\"latex\">?</literal>")
11988 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11989 "<literal style=\"html\">\n?\n</literal>")
11990 ("H" "#+HTML: " "<literal style=\"html\">?</literal>")
11991 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII" "")
11992 ("A" "#+ASCII: " "")
11993 ("i" "#+INDEX: ?" "#+INDEX: ?")
11994 ("I" "#+INCLUDE: %file ?"
11995 "<include file=%file markup=\"?\">"))
11996 "Structure completion elements.
11997 This is a list of abbreviation keys and values. The value gets inserted
11998 if you type `<' followed by the key and then press the completion key,
11999 usually `M-TAB'. %file will be replaced by a file name after prompting
12000 for the file using completion. The cursor will be placed at the position
12001 of the `?` in the template.
12002 There are two templates for each key, the first uses the original Org syntax,
12003 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12004 the default when the /org-mtags.el/ module has been loaded. See also the
12005 variable `org-mtags-prefer-muse-templates'."
12006 :group 'org-completion
12007 :type '(repeat
12008 (list
12009 (string :tag "Key")
12010 (string :tag "Template")
12011 (string :tag "Muse Template"))))
12013 (defun org-try-structure-completion ()
12014 "Try to complete a structure template before point.
12015 This looks for strings like \"<e\" on an otherwise empty line and
12016 expands them."
12017 (let ((l (buffer-substring (point-at-bol) (point)))
12019 (when (and (looking-at "[ \t]*$")
12020 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12021 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12022 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12023 (match-beginning 1)) a)
12024 t)))
12026 (defun org-complete-expand-structure-template (start cell)
12027 "Expand a structure template."
12028 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
12029 (rpl (nth (if musep 2 1) cell))
12030 (ind ""))
12031 (delete-region start (point))
12032 (when (string-match "\\`#\\+" rpl)
12033 (cond
12034 ((bolp))
12035 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12036 (setq ind (buffer-substring (point-at-bol) (point))))
12037 (t (newline))))
12038 (setq start (point))
12039 (if (string-match "%file" rpl)
12040 (setq rpl (replace-match
12041 (concat
12042 "\""
12043 (save-match-data
12044 (abbreviate-file-name (read-file-name "Include file: ")))
12045 "\"")
12046 t t rpl)))
12047 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12048 (concat "\n" ind)))
12049 (insert rpl)
12050 (if (re-search-backward "\\?" start t) (delete-char 1))))
12052 ;;;; TODO, DEADLINE, Comments
12054 (defun org-toggle-comment ()
12055 "Change the COMMENT state of an entry."
12056 (interactive)
12057 (save-excursion
12058 (org-back-to-heading)
12059 (let (case-fold-search)
12060 (cond
12061 ((looking-at (format org-heading-keyword-regexp-format
12062 org-comment-string))
12063 (goto-char (match-end 1))
12064 (looking-at (concat " +" org-comment-string))
12065 (replace-match "" t t)
12066 (when (eolp) (insert " ")))
12067 ((looking-at org-outline-regexp)
12068 (goto-char (match-end 0))
12069 (insert org-comment-string " "))))))
12071 (defvar org-last-todo-state-is-todo nil
12072 "This is non-nil when the last TODO state change led to a TODO state.
12073 If the last change removed the TODO tag or switched to DONE, then
12074 this is nil.")
12076 (defvar org-setting-tags nil) ; dynamically skipped
12078 (defvar org-todo-setup-filter-hook nil
12079 "Hook for functions that pre-filter todo specs.
12080 Each function takes a todo spec and returns either nil or the spec
12081 transformed into canonical form." )
12083 (defvar org-todo-get-default-hook nil
12084 "Hook for functions that get a default item for todo.
12085 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12086 nil or a string to be used for the todo mark." )
12088 (defvar org-agenda-headline-snapshot-before-repeat)
12090 (defun org-current-effective-time ()
12091 "Return current time adjusted for `org-extend-today-until' variable."
12092 (let* ((ct (org-current-time))
12093 (dct (decode-time ct))
12094 (ct1
12095 (cond
12096 (org-use-last-clock-out-time-as-effective-time
12097 (or (org-clock-get-last-clock-out-time) ct))
12098 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12099 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12100 (t ct))))
12101 ct1))
12103 (defun org-todo-yesterday (&optional arg)
12104 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12105 (interactive "P")
12106 (if (eq major-mode 'org-agenda-mode)
12107 (apply 'org-agenda-todo-yesterday arg)
12108 (let* ((hour (third (decode-time
12109 (org-current-time))))
12110 (org-extend-today-until (1+ hour)))
12111 (org-todo arg))))
12113 (defvar org-block-entry-blocking ""
12114 "First entry preventing the TODO state change.")
12116 (defun org-todo (&optional arg)
12117 "Change the TODO state of an item.
12118 The state of an item is given by a keyword at the start of the heading,
12119 like
12120 *** TODO Write paper
12121 *** DONE Call mom
12123 The different keywords are specified in the variable `org-todo-keywords'.
12124 By default the available states are \"TODO\" and \"DONE\".
12125 So for this example: when the item starts with TODO, it is changed to DONE.
12126 When it starts with DONE, the DONE is removed. And when neither TODO nor
12127 DONE are present, add TODO at the beginning of the heading.
12129 With \\[universal-argument] prefix arg, use completion to determine the new \
12130 state.
12131 With numeric prefix arg, switch to that state.
12132 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12133 keywords (nextset).
12134 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12135 With a numeric prefix arg of 0, inhibit note taking for the change.
12137 For calling through lisp, arg is also interpreted in the following way:
12138 'none -> empty state
12139 \"\"(empty string) -> switch to empty state
12140 'done -> switch to DONE
12141 'nextset -> switch to the next set of keywords
12142 'previousset -> switch to the previous set of keywords
12143 \"WAITING\" -> switch to the specified keyword, but only if it
12144 really is a member of `org-todo-keywords'."
12145 (interactive "P")
12146 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12147 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12148 'region-start-level 'region))
12149 org-loop-over-headlines-in-active-region)
12150 (org-map-entries
12151 `(org-todo ,arg)
12152 org-loop-over-headlines-in-active-region
12153 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12154 (if (equal arg '(16)) (setq arg 'nextset))
12155 (let ((org-blocker-hook org-blocker-hook)
12156 commentp
12157 case-fold-search)
12158 (when (equal arg '(64))
12159 (setq arg nil org-blocker-hook nil))
12160 (when (and org-blocker-hook
12161 (or org-inhibit-blocking
12162 (org-entry-get nil "NOBLOCKING")))
12163 (setq org-blocker-hook nil))
12164 (save-excursion
12165 (catch 'exit
12166 (org-back-to-heading t)
12167 (when (looking-at (concat "^\\*+ " org-comment-string))
12168 (org-toggle-comment)
12169 (setq commentp t))
12170 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12171 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12172 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12173 (let* ((match-data (match-data))
12174 (startpos (point-at-bol))
12175 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12176 (org-log-done org-log-done)
12177 (org-log-repeat org-log-repeat)
12178 (org-todo-log-states org-todo-log-states)
12179 (org-inhibit-logging
12180 (if (equal arg 0)
12181 (progn (setq arg nil) 'note) org-inhibit-logging))
12182 (this (match-string 1))
12183 (hl-pos (match-beginning 0))
12184 (head (org-get-todo-sequence-head this))
12185 (ass (assoc head org-todo-kwd-alist))
12186 (interpret (nth 1 ass))
12187 (done-word (nth 3 ass))
12188 (final-done-word (nth 4 ass))
12189 (org-last-state (or this ""))
12190 (completion-ignore-case t)
12191 (member (member this org-todo-keywords-1))
12192 (tail (cdr member))
12193 (org-state (cond
12194 ((and org-todo-key-trigger
12195 (or (and (equal arg '(4))
12196 (eq org-use-fast-todo-selection 'prefix))
12197 (and (not arg) org-use-fast-todo-selection
12198 (not (eq org-use-fast-todo-selection
12199 'prefix)))))
12200 ;; Use fast selection
12201 (org-fast-todo-selection))
12202 ((and (equal arg '(4))
12203 (or (not org-use-fast-todo-selection)
12204 (not org-todo-key-trigger)))
12205 ;; Read a state with completion
12206 (org-icompleting-read
12207 "State: " (mapcar 'list org-todo-keywords-1)
12208 nil t))
12209 ((eq arg 'right)
12210 (if this
12211 (if tail (car tail) nil)
12212 (car org-todo-keywords-1)))
12213 ((eq arg 'left)
12214 (if (equal member org-todo-keywords-1)
12216 (if this
12217 (nth (- (length org-todo-keywords-1)
12218 (length tail) 2)
12219 org-todo-keywords-1)
12220 (org-last org-todo-keywords-1))))
12221 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12222 (setq arg nil))) ; hack to fall back to cycling
12223 (arg
12224 ;; user or caller requests a specific state
12225 (cond
12226 ((equal arg "") nil)
12227 ((eq arg 'none) nil)
12228 ((eq arg 'done) (or done-word (car org-done-keywords)))
12229 ((eq arg 'nextset)
12230 (or (car (cdr (member head org-todo-heads)))
12231 (car org-todo-heads)))
12232 ((eq arg 'previousset)
12233 (let ((org-todo-heads (reverse org-todo-heads)))
12234 (or (car (cdr (member head org-todo-heads)))
12235 (car org-todo-heads))))
12236 ((car (member arg org-todo-keywords-1)))
12237 ((stringp arg)
12238 (user-error "State `%s' not valid in this file" arg))
12239 ((nth (1- (prefix-numeric-value arg))
12240 org-todo-keywords-1))))
12241 ((null member) (or head (car org-todo-keywords-1)))
12242 ((equal this final-done-word) nil) ;; -> make empty
12243 ((null tail) nil) ;; -> first entry
12244 ((memq interpret '(type priority))
12245 (if (eq this-command last-command)
12246 (car tail)
12247 (if (> (length tail) 0)
12248 (or done-word (car org-done-keywords))
12249 nil)))
12251 (car tail))))
12252 (org-state (or
12253 (run-hook-with-args-until-success
12254 'org-todo-get-default-hook org-state org-last-state)
12255 org-state))
12256 (next (if org-state (concat " " org-state " ") " "))
12257 (change-plist (list :type 'todo-state-change :from this :to org-state
12258 :position startpos))
12259 dolog now-done-p)
12260 (when org-blocker-hook
12261 (setq org-last-todo-state-is-todo
12262 (not (member this org-done-keywords)))
12263 (unless (save-excursion
12264 (save-match-data
12265 (org-with-wide-buffer
12266 (run-hook-with-args-until-failure
12267 'org-blocker-hook change-plist))))
12268 (if (org-called-interactively-p 'interactive)
12269 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12270 this org-state org-block-entry-blocking)
12271 ;; fail silently
12272 (message "TODO state change from %s to %s blocked (by \"%s\")"
12273 this org-state org-block-entry-blocking)
12274 (throw 'exit nil))))
12275 (store-match-data match-data)
12276 (replace-match next t t)
12277 (unless (pos-visible-in-window-p hl-pos)
12278 (message "TODO state changed to %s" (org-trim next)))
12279 (unless head
12280 (setq head (org-get-todo-sequence-head org-state)
12281 ass (assoc head org-todo-kwd-alist)
12282 interpret (nth 1 ass)
12283 done-word (nth 3 ass)
12284 final-done-word (nth 4 ass)))
12285 (when (memq arg '(nextset previousset))
12286 (message "Keyword-Set %d/%d: %s"
12287 (- (length org-todo-sets) -1
12288 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12289 (length org-todo-sets)
12290 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12291 (setq org-last-todo-state-is-todo
12292 (not (member org-state org-done-keywords)))
12293 (setq now-done-p (and (member org-state org-done-keywords)
12294 (not (member this org-done-keywords))))
12295 (and logging (org-local-logging logging))
12296 (when (and (or org-todo-log-states org-log-done)
12297 (not (eq org-inhibit-logging t))
12298 (not (memq arg '(nextset previousset))))
12299 ;; we need to look at recording a time and note
12300 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12301 (nth 2 (assoc this org-todo-log-states))))
12302 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12303 (setq dolog 'time))
12304 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12305 (and org-state
12306 (member org-state org-not-done-keywords)
12307 (not (member this org-not-done-keywords))))
12308 ;; This is now a todo state and was not one before
12309 ;; If there was a CLOSED time stamp, get rid of it.
12310 (org-add-planning-info nil nil 'closed))
12311 (when (and now-done-p org-log-done)
12312 ;; It is now done, and it was not done before
12313 (org-add-planning-info 'closed (org-current-effective-time))
12314 (if (and (not dolog) (eq 'note org-log-done))
12315 (org-add-log-setup 'done org-state this 'findpos 'note)))
12316 (when (and org-state dolog)
12317 ;; This is a non-nil state, and we need to log it
12318 (org-add-log-setup 'state org-state this 'findpos dolog)))
12319 ;; Fixup tag positioning
12320 (org-todo-trigger-tag-changes org-state)
12321 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12322 (when org-provide-todo-statistics
12323 (org-update-parent-todo-statistics))
12324 (run-hooks 'org-after-todo-state-change-hook)
12325 (if (and arg (not (member org-state org-done-keywords)))
12326 (setq head (org-get-todo-sequence-head org-state)))
12327 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12328 ;; Do we need to trigger a repeat?
12329 (when now-done-p
12330 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12331 ;; This is for the agenda, take a snapshot of the headline.
12332 (save-match-data
12333 (setq org-agenda-headline-snapshot-before-repeat
12334 (org-get-heading))))
12335 (org-auto-repeat-maybe org-state))
12336 ;; Fixup cursor location if close to the keyword
12337 (if (and (outline-on-heading-p)
12338 (not (bolp))
12339 (save-excursion (beginning-of-line 1)
12340 (looking-at org-todo-line-regexp))
12341 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12342 (progn
12343 (goto-char (or (match-end 2) (match-end 1)))
12344 (and (looking-at " ") (just-one-space))))
12345 (when org-trigger-hook
12346 (save-excursion
12347 (run-hook-with-args 'org-trigger-hook change-plist)))
12348 (when commentp (org-toggle-comment))))))))
12350 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12351 "Block turning an entry into a TODO, using the hierarchy.
12352 This checks whether the current task should be blocked from state
12353 changes. Such blocking occurs when:
12355 1. The task has children which are not all in a completed state.
12357 2. A task has a parent with the property :ORDERED:, and there
12358 are siblings prior to the current task with incomplete
12359 status.
12361 3. The parent of the task is blocked because it has siblings that should
12362 be done first, or is child of a block grandparent TODO entry."
12364 (if (not org-enforce-todo-dependencies)
12365 t ; if locally turned off don't block
12366 (catch 'dont-block
12367 ;; If this is not a todo state change, or if this entry is already DONE,
12368 ;; do not block
12369 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12370 (member (plist-get change-plist :from)
12371 (cons 'done org-done-keywords))
12372 (member (plist-get change-plist :to)
12373 (cons 'todo org-not-done-keywords))
12374 (not (plist-get change-plist :to)))
12375 (throw 'dont-block t))
12376 ;; If this task has children, and any are undone, it's blocked
12377 (save-excursion
12378 (org-back-to-heading t)
12379 (let ((this-level (funcall outline-level)))
12380 (outline-next-heading)
12381 (let ((child-level (funcall outline-level)))
12382 (while (and (not (eobp))
12383 (> child-level this-level))
12384 ;; this todo has children, check whether they are all
12385 ;; completed
12386 (if (and (not (org-entry-is-done-p))
12387 (org-entry-is-todo-p))
12388 (progn (setq org-block-entry-blocking (org-get-heading))
12389 (throw 'dont-block nil)))
12390 (outline-next-heading)
12391 (setq child-level (funcall outline-level))))))
12392 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12393 ;; any previous siblings are undone, it's blocked
12394 (save-excursion
12395 (org-back-to-heading t)
12396 (let* ((pos (point))
12397 (parent-pos (and (org-up-heading-safe) (point))))
12398 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12399 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12400 (forward-line 1)
12401 (re-search-forward org-not-done-heading-regexp pos t))
12402 (setq org-block-entry-blocking (match-string 0))
12403 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12404 ;; Search further up the hierarchy, to see if an ancestor is blocked
12405 (while t
12406 (goto-char parent-pos)
12407 (if (not (looking-at org-not-done-heading-regexp))
12408 (throw 'dont-block t)) ; do not block, parent is not a TODO
12409 (setq pos (point))
12410 (setq parent-pos (and (org-up-heading-safe) (point)))
12411 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12412 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12413 (forward-line 1)
12414 (re-search-forward org-not-done-heading-regexp pos t)
12415 (setq org-block-entry-blocking (org-get-heading)))
12416 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12418 (defcustom org-track-ordered-property-with-tag nil
12419 "Should the ORDERED property also be shown as a tag?
12420 The ORDERED property decides if an entry should require subtasks to be
12421 completed in sequence. Since a property is not very visible, setting
12422 this option means that toggling the ORDERED property with the command
12423 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12424 not relevant for the behavior, but it makes things more visible.
12426 Note that toggling the tag with tags commands will not change the property
12427 and therefore not influence behavior!
12429 This can be t, meaning the tag ORDERED should be used, It can also be a
12430 string to select a different tag for this task."
12431 :group 'org-todo
12432 :type '(choice
12433 (const :tag "No tracking" nil)
12434 (const :tag "Track with ORDERED tag" t)
12435 (string :tag "Use other tag")))
12437 (defun org-toggle-ordered-property ()
12438 "Toggle the ORDERED property of the current entry.
12439 For better visibility, you can track the value of this property with a tag.
12440 See variable `org-track-ordered-property-with-tag'."
12441 (interactive)
12442 (let* ((t1 org-track-ordered-property-with-tag)
12443 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12444 (save-excursion
12445 (org-back-to-heading)
12446 (if (org-entry-get nil "ORDERED")
12447 (progn
12448 (org-delete-property "ORDERED" "PROPERTIES")
12449 (and tag (org-toggle-tag tag 'off))
12450 (message "Subtasks can be completed in arbitrary order"))
12451 (org-entry-put nil "ORDERED" "t")
12452 (and tag (org-toggle-tag tag 'on))
12453 (message "Subtasks must be completed in sequence")))))
12455 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12456 (defun org-block-todo-from-checkboxes (change-plist)
12457 "Block turning an entry into a TODO, using checkboxes.
12458 This checks whether the current task should be blocked from state
12459 changes because there are unchecked boxes in this entry."
12460 (if (not org-enforce-todo-checkbox-dependencies)
12461 t ; if locally turned off don't block
12462 (catch 'dont-block
12463 ;; If this is not a todo state change, or if this entry is already DONE,
12464 ;; do not block
12465 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12466 (member (plist-get change-plist :from)
12467 (cons 'done org-done-keywords))
12468 (member (plist-get change-plist :to)
12469 (cons 'todo org-not-done-keywords))
12470 (not (plist-get change-plist :to)))
12471 (throw 'dont-block t))
12472 ;; If this task has checkboxes that are not checked, it's blocked
12473 (save-excursion
12474 (org-back-to-heading t)
12475 (let ((beg (point)) end)
12476 (outline-next-heading)
12477 (setq end (point))
12478 (goto-char beg)
12479 (if (org-list-search-forward
12480 (concat (org-item-beginning-re)
12481 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12482 "\\[[- ]\\]")
12483 end t)
12484 (progn
12485 (if (boundp 'org-blocked-by-checkboxes)
12486 (setq org-blocked-by-checkboxes t))
12487 (throw 'dont-block nil)))))
12488 t))) ; do not block
12490 (defun org-entry-blocked-p ()
12491 "Is the current entry blocked?"
12492 (org-with-silent-modifications
12493 (if (org-entry-get nil "NOBLOCKING")
12494 nil ;; Never block this entry
12495 (not (run-hook-with-args-until-failure
12496 'org-blocker-hook
12497 (list :type 'todo-state-change
12498 :position (point)
12499 :from 'todo
12500 :to 'done))))))
12502 (defun org-update-statistics-cookies (all)
12503 "Update the statistics cookie, either from TODO or from checkboxes.
12504 This should be called with the cursor in a line with a statistics cookie."
12505 (interactive "P")
12506 (if all
12507 (progn
12508 (org-update-checkbox-count 'all)
12509 (org-map-entries 'org-update-parent-todo-statistics))
12510 (if (not (org-at-heading-p))
12511 (org-update-checkbox-count)
12512 (let ((pos (point-marker))
12513 end l1 l2)
12514 (ignore-errors (org-back-to-heading t))
12515 (if (not (org-at-heading-p))
12516 (org-update-checkbox-count)
12517 (setq l1 (org-outline-level))
12518 (setq end (save-excursion
12519 (outline-next-heading)
12520 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12521 (point)))
12522 (if (and (save-excursion
12523 (re-search-forward
12524 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12525 (not (save-excursion (re-search-forward
12526 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12527 (org-update-checkbox-count)
12528 (if (and l2 (> l2 l1))
12529 (progn
12530 (goto-char end)
12531 (org-update-parent-todo-statistics))
12532 (goto-char pos)
12533 (beginning-of-line 1)
12534 (while (re-search-forward
12535 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12536 (point-at-eol) t)
12537 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12538 (goto-char pos)
12539 (move-marker pos nil)))))
12541 (defvar org-entry-property-inherited-from) ;; defined below
12542 (defun org-update-parent-todo-statistics ()
12543 "Update any statistics cookie in the parent of the current headline.
12544 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12545 the entire subtree and this will travel up the hierarchy and update
12546 statistics everywhere."
12547 (let* ((prop (save-excursion (org-up-heading-safe)
12548 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12549 (recursive (or (not org-hierarchical-todo-statistics)
12550 (and prop (string-match "\\<recursive\\>" prop))))
12551 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12553 (first t)
12554 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12555 level ltoggle l1 new ndel
12556 (cnt-all 0) (cnt-done 0) is-percent kwd
12557 checkbox-beg ov ovs ove cookie-present)
12558 (catch 'exit
12559 (save-excursion
12560 (beginning-of-line 1)
12561 (setq ltoggle (funcall outline-level))
12562 ;; Three situations are to consider:
12564 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12565 ;; to the top-level ancestor on the headline;
12567 ;; 2. If parent has "recursive" property, repeat up to the
12568 ;; headline setting that property, taking inheritance into
12569 ;; account;
12571 ;; 3. Else, move up to direct parent and proceed only once.
12572 (while (and (setq level (org-up-heading-safe))
12573 (or recursive first)
12574 (>= (point) lim))
12575 (setq first nil cookie-present nil)
12576 (unless (and level
12577 (not (string-match
12578 "\\<checkbox\\>"
12579 (downcase (or (org-entry-get nil "COOKIE_DATA")
12580 "")))))
12581 (throw 'exit nil))
12582 (while (re-search-forward box-re (point-at-eol) t)
12583 (setq cnt-all 0 cnt-done 0 cookie-present t)
12584 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12585 (save-match-data
12586 (unless (outline-next-heading) (throw 'exit nil))
12587 (while (and (looking-at org-complex-heading-regexp)
12588 (> (setq l1 (length (match-string 1))) level))
12589 (setq kwd (and (or recursive (= l1 ltoggle))
12590 (match-string 2)))
12591 (if (or (eq org-provide-todo-statistics 'all-headlines)
12592 (and (listp org-provide-todo-statistics)
12593 (or (member kwd org-provide-todo-statistics)
12594 (member kwd org-done-keywords))))
12595 (setq cnt-all (1+ cnt-all))
12596 (if (eq org-provide-todo-statistics t)
12597 (and kwd (setq cnt-all (1+ cnt-all)))))
12598 (and (member kwd org-done-keywords)
12599 (setq cnt-done (1+ cnt-done)))
12600 (outline-next-heading)))
12601 (setq new
12602 (if is-percent
12603 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12604 (format "[%d/%d]" cnt-done cnt-all))
12605 ndel (- (match-end 0) checkbox-beg))
12606 ;; handle overlays when updating cookie from column view
12607 (when (setq ov (car (overlays-at checkbox-beg)))
12608 (setq ovs (overlay-start ov) ove (overlay-end ov))
12609 (delete-overlay ov))
12610 (goto-char checkbox-beg)
12611 (insert new)
12612 (delete-region (point) (+ (point) ndel))
12613 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12614 (when ov (move-overlay ov ovs ove)))
12615 (when cookie-present
12616 (run-hook-with-args 'org-after-todo-statistics-hook
12617 cnt-done (- cnt-all cnt-done))))))
12618 (run-hooks 'org-todo-statistics-hook)))
12620 (defvar org-after-todo-statistics-hook nil
12621 "Hook that is called after a TODO statistics cookie has been updated.
12622 Each function is called with two arguments: the number of not-done entries
12623 and the number of done entries.
12625 For example, the following function, when added to this hook, will switch
12626 an entry to DONE when all children are done, and back to TODO when new
12627 entries are set to a TODO status. Note that this hook is only called
12628 when there is a statistics cookie in the headline!
12630 (defun org-summary-todo (n-done n-not-done)
12631 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12632 (let (org-log-done org-log-states) ; turn off logging
12633 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12636 (defvar org-todo-statistics-hook nil
12637 "Hook that is run whenever Org thinks TODO statistics should be updated.
12638 This hook runs even if there is no statistics cookie present, in which case
12639 `org-after-todo-statistics-hook' would not run.")
12641 (defun org-todo-trigger-tag-changes (state)
12642 "Apply the changes defined in `org-todo-state-tags-triggers'."
12643 (let ((l org-todo-state-tags-triggers)
12644 changes)
12645 (when (or (not state) (equal state ""))
12646 (setq changes (append changes (cdr (assoc "" l)))))
12647 (when (and (stringp state) (> (length state) 0))
12648 (setq changes (append changes (cdr (assoc state l)))))
12649 (when (member state org-not-done-keywords)
12650 (setq changes (append changes (cdr (assoc 'todo l)))))
12651 (when (member state org-done-keywords)
12652 (setq changes (append changes (cdr (assoc 'done l)))))
12653 (dolist (c changes)
12654 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12656 (defun org-local-logging (value)
12657 "Get logging settings from a property VALUE."
12658 (let* (words w a)
12659 ;; directly set the variables, they are already local.
12660 (setq org-log-done nil
12661 org-log-repeat nil
12662 org-todo-log-states nil)
12663 (setq words (org-split-string value))
12664 (while (setq w (pop words))
12665 (cond
12666 ((setq a (assoc w org-startup-options))
12667 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12668 (set (nth 1 a) (nth 2 a))))
12669 ((setq a (org-extract-log-state-settings w))
12670 (and (member (car a) org-todo-keywords-1)
12671 (push a org-todo-log-states)))))))
12673 (defun org-get-todo-sequence-head (kwd)
12674 "Return the head of the TODO sequence to which KWD belongs.
12675 If KWD is not set, check if there is a text property remembering the
12676 right sequence."
12677 (let (p)
12678 (cond
12679 ((not kwd)
12680 (or (get-text-property (point-at-bol) 'org-todo-head)
12681 (progn
12682 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12683 nil (point-at-eol)))
12684 (get-text-property p 'org-todo-head))))
12685 ((not (member kwd org-todo-keywords-1))
12686 (car org-todo-keywords-1))
12687 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12689 (defun org-fast-todo-selection ()
12690 "Fast TODO keyword selection with single keys.
12691 Returns the new TODO keyword, or nil if no state change should occur."
12692 (let* ((fulltable org-todo-key-alist)
12693 (done-keywords org-done-keywords) ;; needed for the faces.
12694 (maxlen (apply 'max (mapcar
12695 (lambda (x)
12696 (if (stringp (car x)) (string-width (car x)) 0))
12697 fulltable)))
12698 (expert nil)
12699 (fwidth (+ maxlen 3 1 3))
12700 (ncol (/ (- (window-width) 4) fwidth))
12701 tg cnt e c tbl
12702 groups ingroup)
12703 (save-excursion
12704 (save-window-excursion
12705 (if expert
12706 (set-buffer (get-buffer-create " *Org todo*"))
12707 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12708 (erase-buffer)
12709 (org-set-local 'org-done-keywords done-keywords)
12710 (setq tbl fulltable cnt 0)
12711 (while (setq e (pop tbl))
12712 (cond
12713 ((equal e '(:startgroup))
12714 (push '() groups) (setq ingroup t)
12715 (when (not (= cnt 0))
12716 (setq cnt 0)
12717 (insert "\n"))
12718 (insert "{ "))
12719 ((equal e '(:endgroup))
12720 (setq ingroup nil cnt 0)
12721 (insert "}\n"))
12722 ((equal e '(:newline))
12723 (when (not (= cnt 0))
12724 (setq cnt 0)
12725 (insert "\n")
12726 (setq e (car tbl))
12727 (while (equal (car tbl) '(:newline))
12728 (insert "\n")
12729 (setq tbl (cdr tbl)))))
12731 (setq tg (car e) c (cdr e))
12732 (if ingroup (push tg (car groups)))
12733 (setq tg (org-add-props tg nil 'face
12734 (org-get-todo-face tg)))
12735 (if (and (= cnt 0) (not ingroup)) (insert " "))
12736 (insert "[" c "] " tg (make-string
12737 (- fwidth 4 (length tg)) ?\ ))
12738 (when (= (setq cnt (1+ cnt)) ncol)
12739 (insert "\n")
12740 (if ingroup (insert " "))
12741 (setq cnt 0)))))
12742 (insert "\n")
12743 (goto-char (point-min))
12744 (if (not expert) (org-fit-window-to-buffer))
12745 (message "[a-z..]:Set [SPC]:clear")
12746 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12747 (cond
12748 ((or (= c ?\C-g)
12749 (and (= c ?q) (not (rassoc c fulltable))))
12750 (setq quit-flag t))
12751 ((= c ?\ ) nil)
12752 ((setq e (rassoc c fulltable) tg (car e))
12754 (t (setq quit-flag t)))))))
12756 (defun org-entry-is-todo-p ()
12757 (member (org-get-todo-state) org-not-done-keywords))
12759 (defun org-entry-is-done-p ()
12760 (member (org-get-todo-state) org-done-keywords))
12762 (defun org-get-todo-state ()
12763 "Return the TODO keyword of the current subtree."
12764 (save-excursion
12765 (org-back-to-heading t)
12766 (and (looking-at org-todo-line-regexp)
12767 (match-end 2)
12768 (match-string 2))))
12770 (defun org-at-date-range-p (&optional inactive-ok)
12771 "Is the cursor inside a date range?"
12772 (interactive)
12773 (save-excursion
12774 (catch 'exit
12775 (let ((pos (point)))
12776 (skip-chars-backward "^[<\r\n")
12777 (skip-chars-backward "<[")
12778 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12779 (>= (match-end 0) pos)
12780 (throw 'exit t))
12781 (skip-chars-backward "^<[\r\n")
12782 (skip-chars-backward "<[")
12783 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12784 (>= (match-end 0) pos)
12785 (throw 'exit t)))
12786 nil)))
12788 (defun org-get-repeat (&optional tagline)
12789 "Check if there is a deadline/schedule with repeater in this entry."
12790 (save-match-data
12791 (save-excursion
12792 (org-back-to-heading t)
12793 (and (re-search-forward (if tagline
12794 (concat tagline "\\s-*" org-repeat-re)
12795 org-repeat-re)
12796 (org-entry-end-position) t)
12797 (match-string-no-properties 1)))))
12799 (defvar org-last-changed-timestamp)
12800 (defvar org-last-inserted-timestamp)
12801 (defvar org-log-post-message)
12802 (defvar org-log-note-purpose)
12803 (defvar org-log-note-how)
12804 (defvar org-log-note-extra)
12805 (defun org-auto-repeat-maybe (done-word)
12806 "Check if the current headline contains a repeated deadline/schedule.
12807 If yes, set TODO state back to what it was and change the base date
12808 of repeating deadline/scheduled time stamps to new date.
12809 This function is run automatically after each state change to a DONE state."
12810 ;; last-state is dynamically scoped into this function
12811 (let* ((repeat (org-get-repeat))
12812 (aa (assoc org-last-state org-todo-kwd-alist))
12813 (interpret (nth 1 aa))
12814 (head (nth 2 aa))
12815 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12816 (msg "Entry repeats: ")
12817 (org-log-done nil)
12818 (org-todo-log-states nil)
12819 re type n what ts time to-state)
12820 (when repeat
12821 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12822 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12823 org-todo-repeat-to-state))
12824 (unless (and to-state (member to-state org-todo-keywords-1))
12825 (setq to-state (if (eq interpret 'type) org-last-state head)))
12826 (org-todo to-state)
12827 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12828 (org-entry-put nil "LAST_REPEAT" (format-time-string
12829 (org-time-stamp-format t t))))
12830 (when org-log-repeat
12831 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12832 (memq 'org-add-log-note post-command-hook))
12833 ;; OK, we are already setup for some record
12834 (if (eq org-log-repeat 'note)
12835 ;; make sure we take a note, not only a time stamp
12836 (setq org-log-note-how 'note))
12837 ;; Set up for taking a record
12838 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12839 org-last-state
12840 'findpos org-log-repeat)))
12841 (org-back-to-heading t)
12842 (org-add-planning-info nil nil 'closed)
12843 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12844 org-deadline-time-regexp "\\)\\|\\("
12845 org-ts-regexp "\\)"))
12846 (while (re-search-forward
12847 re (save-excursion (outline-next-heading) (point)) t)
12848 (setq type (if (match-end 1) org-scheduled-string
12849 (if (match-end 3) org-deadline-string "Plain:"))
12850 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12851 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12852 (setq n (string-to-number (match-string 2 ts))
12853 what (match-string 3 ts))
12854 (if (equal what "w") (setq n (* n 7) what "d"))
12855 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12856 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12857 ;; Preparation, see if we need to modify the start date for the change
12858 (when (match-end 1)
12859 (setq time (save-match-data (org-time-string-to-time ts)))
12860 (cond
12861 ((equal (match-string 1 ts) ".")
12862 ;; Shift starting date to today
12863 (org-timestamp-change
12864 (- (org-today) (time-to-days time))
12865 'day))
12866 ((equal (match-string 1 ts) "+")
12867 (let ((nshiftmax 10) (nshift 0))
12868 (while (or (= nshift 0)
12869 (<= (time-to-days time)
12870 (time-to-days (current-time))))
12871 (when (= (incf nshift) nshiftmax)
12872 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12873 (error "Abort")))
12874 (org-timestamp-change n (cdr (assoc what whata)))
12875 (org-at-timestamp-p t)
12876 (setq ts (match-string 1))
12877 (setq time (save-match-data (org-time-string-to-time ts)))))
12878 (org-timestamp-change (- n) (cdr (assoc what whata)))
12879 ;; rematch, so that we have everything in place for the real shift
12880 (org-at-timestamp-p t)
12881 (setq ts (match-string 1))
12882 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12883 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12884 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12885 (setq org-log-post-message msg)
12886 (message "%s" msg))))
12888 (defun org-show-todo-tree (arg)
12889 "Make a compact tree which shows all headlines marked with TODO.
12890 The tree will show the lines where the regexp matches, and all higher
12891 headlines above the match.
12892 With a \\[universal-argument] prefix, prompt for a regexp to match.
12893 With a numeric prefix N, construct a sparse tree for the Nth element
12894 of `org-todo-keywords-1'."
12895 (interactive "P")
12896 (let ((case-fold-search nil)
12897 (kwd-re
12898 (cond ((null arg) org-not-done-regexp)
12899 ((equal arg '(4))
12900 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12901 (mapcar 'list org-todo-keywords-1))))
12902 (concat "\\("
12903 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12904 "\\)\\>")))
12905 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12906 (regexp-quote (nth (1- (prefix-numeric-value arg))
12907 org-todo-keywords-1)))
12908 (t (user-error "Invalid prefix argument: %s" arg)))))
12909 (message "%d TODO entries found"
12910 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12912 (defun org-deadline (arg &optional time)
12913 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12914 With one universal prefix argument, remove any deadline from the item.
12915 With two universal prefix arguments, prompt for a warning delay.
12916 With argument TIME, set the deadline at the corresponding date. TIME
12917 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12918 (interactive "P")
12919 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12920 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12921 'region-start-level 'region))
12922 org-loop-over-headlines-in-active-region)
12923 (org-map-entries
12924 `(org-deadline ',arg ,time)
12925 org-loop-over-headlines-in-active-region
12926 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12927 (let* ((old-date (org-entry-get nil "DEADLINE"))
12928 (old-date-time (if old-date (org-time-string-to-time old-date)))
12929 (repeater (and old-date
12930 (string-match
12931 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12932 old-date)
12933 (match-string 1 old-date))))
12934 (cond
12935 ((equal arg '(4))
12936 (when (and old-date org-log-redeadline)
12937 (org-add-log-setup 'deldeadline nil old-date 'findpos
12938 org-log-redeadline))
12939 (org-remove-timestamp-with-keyword org-deadline-string)
12940 (message "Item no longer has a deadline."))
12941 ((equal arg '(16))
12942 (save-excursion
12943 (org-back-to-heading t)
12944 (if (re-search-forward
12945 org-deadline-time-regexp
12946 (save-excursion (outline-next-heading) (point)) t)
12947 (let* ((rpl0 (match-string 1))
12948 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12949 (replace-match
12950 (concat org-deadline-string
12951 " <" rpl
12952 (format " -%dd"
12953 (abs
12954 (- (time-to-days
12955 (save-match-data
12956 (org-read-date nil t nil "Warn starting from" old-date-time)))
12957 (time-to-days old-date-time))))
12958 ">") t t))
12959 (user-error "No deadline information to update"))))
12961 (org-add-planning-info 'deadline time 'closed)
12962 (when (and old-date org-log-redeadline
12963 (not (equal old-date
12964 (substring org-last-inserted-timestamp 1 -1))))
12965 (org-add-log-setup 'redeadline nil old-date 'findpos
12966 org-log-redeadline))
12967 (when repeater
12968 (save-excursion
12969 (org-back-to-heading t)
12970 (when (re-search-forward (concat org-deadline-string " "
12971 org-last-inserted-timestamp)
12972 (save-excursion
12973 (outline-next-heading) (point)) t)
12974 (goto-char (1- (match-end 0)))
12975 (insert " " repeater)
12976 (setq org-last-inserted-timestamp
12977 (concat (substring org-last-inserted-timestamp 0 -1)
12978 " " repeater
12979 (substring org-last-inserted-timestamp -1))))))
12980 (message "Deadline on %s" org-last-inserted-timestamp))))))
12982 (defun org-schedule (arg &optional time)
12983 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12984 With one universal prefix argument, remove any scheduling date from the item.
12985 With two universal prefix arguments, prompt for a delay cookie.
12986 With argument TIME, scheduled at the corresponding date. TIME can
12987 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12988 (interactive "P")
12989 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12990 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12991 'region-start-level 'region))
12992 org-loop-over-headlines-in-active-region)
12993 (org-map-entries
12994 `(org-schedule ',arg ,time)
12995 org-loop-over-headlines-in-active-region
12996 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12997 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12998 (old-date-time (if old-date (org-time-string-to-time old-date)))
12999 (repeater (and old-date
13000 (string-match
13001 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13002 old-date)
13003 (match-string 1 old-date))))
13004 (cond
13005 ((equal arg '(4))
13006 (progn
13007 (when (and old-date org-log-reschedule)
13008 (org-add-log-setup 'delschedule nil old-date 'findpos
13009 org-log-reschedule))
13010 (org-remove-timestamp-with-keyword org-scheduled-string)
13011 (message "Item is no longer scheduled.")))
13012 ((equal arg '(16))
13013 (save-excursion
13014 (org-back-to-heading t)
13015 (if (re-search-forward
13016 org-scheduled-time-regexp
13017 (save-excursion (outline-next-heading) (point)) t)
13018 (let* ((rpl0 (match-string 1))
13019 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13020 (replace-match
13021 (concat org-scheduled-string
13022 " <" rpl
13023 (format " -%dd"
13024 (abs
13025 (- (time-to-days
13026 (save-match-data
13027 (org-read-date nil t nil "Delay until" old-date-time)))
13028 (time-to-days old-date-time))))
13029 ">") t t))
13030 (user-error "No scheduled information to update"))))
13032 (org-add-planning-info 'scheduled time 'closed)
13033 (when (and old-date org-log-reschedule
13034 (not (equal old-date
13035 (substring org-last-inserted-timestamp 1 -1))))
13036 (org-add-log-setup 'reschedule nil old-date 'findpos
13037 org-log-reschedule))
13038 (when repeater
13039 (save-excursion
13040 (org-back-to-heading t)
13041 (when (re-search-forward (concat org-scheduled-string " "
13042 org-last-inserted-timestamp)
13043 (save-excursion
13044 (outline-next-heading) (point)) t)
13045 (goto-char (1- (match-end 0)))
13046 (insert " " repeater)
13047 (setq org-last-inserted-timestamp
13048 (concat (substring org-last-inserted-timestamp 0 -1)
13049 " " repeater
13050 (substring org-last-inserted-timestamp -1))))))
13051 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13053 (defun org-get-scheduled-time (pom &optional inherit)
13054 "Get the scheduled time as a time tuple, of a format suitable
13055 for calling org-schedule with, or if there is no scheduling,
13056 returns nil."
13057 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13058 (when time
13059 (apply 'encode-time (org-parse-time-string time)))))
13061 (defun org-get-deadline-time (pom &optional inherit)
13062 "Get the deadline as a time tuple, of a format suitable for
13063 calling org-deadline with, or if there is no scheduling, returns
13064 nil."
13065 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13066 (when time
13067 (apply 'encode-time (org-parse-time-string time)))))
13069 (defun org-remove-timestamp-with-keyword (keyword)
13070 "Remove all time stamps with KEYWORD in the current entry."
13071 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13072 beg)
13073 (save-excursion
13074 (org-back-to-heading t)
13075 (setq beg (point))
13076 (outline-next-heading)
13077 (while (re-search-backward re beg t)
13078 (replace-match "")
13079 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13080 (equal (char-before) ?\ ))
13081 (backward-delete-char 1)
13082 (if (string-match "^[ \t]*$" (buffer-substring
13083 (point-at-bol) (point-at-eol)))
13084 (delete-region (point-at-bol)
13085 (min (point-max) (1+ (point-at-eol))))))))))
13087 (defvar org-time-was-given) ; dynamically scoped parameter
13088 (defvar org-end-time-was-given) ; dynamically scoped parameter
13090 (defun org-add-planning-info (what &optional time &rest remove)
13091 "Insert new timestamp with keyword in the line directly after the headline.
13092 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13093 If non is given, the user is prompted for a date.
13094 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13095 be removed."
13096 (interactive)
13097 (let (org-time-was-given org-end-time-was-given ts
13098 end default-time default-input)
13100 (catch 'exit
13101 (when (and (memq what '(scheduled deadline))
13102 (or (not time)
13103 (and (stringp time)
13104 (string-match "^[-+]+[0-9]" time))))
13105 ;; Try to get a default date/time from existing timestamp
13106 (save-excursion
13107 (org-back-to-heading t)
13108 (setq end (save-excursion (outline-next-heading) (point)))
13109 (when (re-search-forward (if (eq what 'scheduled)
13110 org-scheduled-time-regexp
13111 org-deadline-time-regexp)
13112 end t)
13113 (setq ts (match-string 1)
13114 default-time
13115 (apply 'encode-time (org-parse-time-string ts))
13116 default-input (and ts (org-get-compact-tod ts))))))
13117 (when what
13118 (setq time
13119 (if (stringp time)
13120 ;; This is a string (relative or absolute), set proper date
13121 (apply 'encode-time
13122 (org-read-date-analyze
13123 time default-time (decode-time default-time)))
13124 ;; If necessary, get the time from the user
13125 (or time (org-read-date nil 'to-time nil nil
13126 default-time default-input)))))
13128 (when (and org-insert-labeled-timestamps-at-point
13129 (member what '(scheduled deadline)))
13130 (insert
13131 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13132 (org-insert-time-stamp time org-time-was-given
13133 nil nil nil (list org-end-time-was-given))
13134 (setq what nil))
13135 (save-excursion
13136 (save-restriction
13137 (let (col list elt ts buffer-invisibility-spec)
13138 (org-back-to-heading t)
13139 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13140 (goto-char (match-end 1))
13141 (setq col (current-column))
13142 (goto-char (match-end 0))
13143 (if (eobp) (insert "\n") (forward-char 1))
13144 (when (and (not what)
13145 (not (looking-at
13146 (concat "[ \t]*"
13147 org-keyword-time-not-clock-regexp))))
13148 ;; Nothing to add, nothing to remove...... :-)
13149 (throw 'exit nil))
13150 (if (and (not (looking-at org-outline-regexp))
13151 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13152 "[^\r\n]*"))
13153 (not (equal (match-string 1) org-clock-string)))
13154 (narrow-to-region (match-beginning 0) (match-end 0))
13155 (insert-before-markers "\n")
13156 (backward-char 1)
13157 (narrow-to-region (point) (point))
13158 (and org-adapt-indentation (org-indent-to-column col)))
13159 ;; Check if we have to remove something.
13160 (setq list (cons what remove))
13161 (while list
13162 (setq elt (pop list))
13163 (when (or (and (eq elt 'scheduled)
13164 (re-search-forward org-scheduled-time-regexp nil t))
13165 (and (eq elt 'deadline)
13166 (re-search-forward org-deadline-time-regexp nil t))
13167 (and (eq elt 'closed)
13168 (re-search-forward org-closed-time-regexp nil t)))
13169 (replace-match "")
13170 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13171 (and (looking-at "[ \t]+") (replace-match ""))
13172 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13173 (when what
13174 (insert
13175 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13176 (cond ((eq what 'scheduled) org-scheduled-string)
13177 ((eq what 'deadline) org-deadline-string)
13178 ((eq what 'closed) org-closed-string))
13179 " ")
13180 (setq ts (org-insert-time-stamp
13181 time
13182 (or org-time-was-given
13183 (and (eq what 'closed) org-log-done-with-time))
13184 (eq what 'closed)
13185 nil nil (list org-end-time-was-given)))
13186 (insert
13187 (if (not (or (bolp) (eq (char-before) ?\ )
13188 (memq (char-after) '(32 10))
13189 (eobp))) " " ""))
13190 (end-of-line 1))
13191 (goto-char (point-min))
13192 (widen)
13193 (if (and (looking-at "[ \t]*\n")
13194 (equal (char-before) ?\n))
13195 (delete-region (1- (point)) (point-at-eol)))
13196 ts))))))
13198 (defvar org-log-note-marker (make-marker))
13199 (defvar org-log-note-purpose nil)
13200 (defvar org-log-note-state nil)
13201 (defvar org-log-note-previous-state nil)
13202 (defvar org-log-note-how nil)
13203 (defvar org-log-note-extra nil)
13204 (defvar org-log-note-window-configuration nil)
13205 (defvar org-log-note-return-to (make-marker))
13206 (defvar org-log-note-effective-time nil
13207 "Remembered current time so that dynamically scoped
13208 `org-extend-today-until' affects tha timestamps in state change
13209 log")
13211 (defvar org-log-post-message nil
13212 "Message to be displayed after a log note has been stored.
13213 The auto-repeater uses this.")
13215 (defun org-add-note ()
13216 "Add a note to the current entry.
13217 This is done in the same way as adding a state change note."
13218 (interactive)
13219 (org-add-log-setup 'note nil nil 'findpos nil))
13221 (defvar org-property-end-re)
13222 (defun org-add-log-setup (&optional purpose state prev-state
13223 findpos how extra)
13224 "Set up the post command hook to take a note.
13225 If this is about to TODO state change, the new state is expected in STATE.
13226 When FINDPOS is non-nil, find the correct position for the note in
13227 the current entry. If not, assume that it can be inserted at point.
13228 HOW is an indicator what kind of note should be created.
13229 EXTRA is additional text that will be inserted into the notes buffer."
13230 (let* ((org-log-into-drawer (org-log-into-drawer))
13231 (drawer (cond ((stringp org-log-into-drawer)
13232 org-log-into-drawer)
13233 (org-log-into-drawer "LOGBOOK"))))
13234 (save-restriction
13235 (save-excursion
13236 (when findpos
13237 (org-back-to-heading t)
13238 (narrow-to-region (point) (save-excursion
13239 (outline-next-heading) (point)))
13240 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13241 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13242 "[^\r\n]*\\)?"))
13243 (goto-char (match-end 0))
13244 (cond
13245 (drawer
13246 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13247 nil t)
13248 (progn
13249 (goto-char (match-end 0))
13250 (or org-log-states-order-reversed
13251 (and (re-search-forward org-property-end-re nil t)
13252 (goto-char (1- (match-beginning 0))))))
13253 (insert "\n:" drawer ":\n:END:")
13254 (beginning-of-line 0)
13255 (org-indent-line)
13256 (beginning-of-line 2)
13257 (org-indent-line)
13258 (end-of-line 0)))
13259 ((and org-log-state-notes-insert-after-drawers
13260 (save-excursion
13261 (forward-line) (looking-at org-drawer-regexp)))
13262 (forward-line)
13263 (while (looking-at org-drawer-regexp)
13264 (goto-char (match-end 0))
13265 (re-search-forward org-property-end-re (point-max) t)
13266 (forward-line))
13267 (forward-line -1)))
13268 (unless org-log-states-order-reversed
13269 (and (= (char-after) ?\n) (forward-char 1))
13270 (org-skip-over-state-notes)
13271 (skip-chars-backward " \t\n\r")))
13272 (move-marker org-log-note-marker (point))
13273 (setq org-log-note-purpose purpose
13274 org-log-note-state state
13275 org-log-note-previous-state prev-state
13276 org-log-note-how how
13277 org-log-note-extra extra
13278 org-log-note-effective-time (org-current-effective-time))
13279 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13281 (defun org-skip-over-state-notes ()
13282 "Skip past the list of State notes in an entry."
13283 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13284 (when (ignore-errors (goto-char (org-in-item-p)))
13285 (let* ((struct (org-list-struct))
13286 (prevs (org-list-prevs-alist struct)))
13287 (while (looking-at "[ \t]*- State")
13288 (goto-char (or (org-list-get-next-item (point) struct prevs)
13289 (org-list-get-item-end (point) struct)))))))
13291 (defun org-add-log-note (&optional purpose)
13292 "Pop up a window for taking a note, and add this note later at point."
13293 (remove-hook 'post-command-hook 'org-add-log-note)
13294 (setq org-log-note-window-configuration (current-window-configuration))
13295 (delete-other-windows)
13296 (move-marker org-log-note-return-to (point))
13297 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13298 (goto-char org-log-note-marker)
13299 (org-switch-to-buffer-other-window "*Org Note*")
13300 (erase-buffer)
13301 (if (memq org-log-note-how '(time state))
13302 (let (current-prefix-arg) (org-store-log-note))
13303 (let ((org-inhibit-startup t)) (org-mode))
13304 (insert (format "# Insert note for %s.
13305 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13306 (cond
13307 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13308 ((eq org-log-note-purpose 'done) "closed todo item")
13309 ((eq org-log-note-purpose 'state)
13310 (format "state change from \"%s\" to \"%s\""
13311 (or org-log-note-previous-state "")
13312 (or org-log-note-state "")))
13313 ((eq org-log-note-purpose 'reschedule)
13314 "rescheduling")
13315 ((eq org-log-note-purpose 'delschedule)
13316 "no longer scheduled")
13317 ((eq org-log-note-purpose 'redeadline)
13318 "changing deadline")
13319 ((eq org-log-note-purpose 'deldeadline)
13320 "removing deadline")
13321 ((eq org-log-note-purpose 'refile)
13322 "refiling")
13323 ((eq org-log-note-purpose 'note)
13324 "this entry")
13325 (t (error "This should not happen")))))
13326 (if org-log-note-extra (insert org-log-note-extra))
13327 (org-set-local 'org-finish-function 'org-store-log-note)
13328 (run-hooks 'org-log-buffer-setup-hook)))
13330 (defvar org-note-abort nil) ; dynamically scoped
13331 (defun org-store-log-note ()
13332 "Finish taking a log note, and insert it to where it belongs."
13333 (let ((txt (buffer-string)))
13334 (kill-buffer (current-buffer))
13335 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13336 lines ind bul)
13337 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13338 (setq txt (replace-match "" t t txt)))
13339 (if (string-match "\\s-+\\'" txt)
13340 (setq txt (replace-match "" t t txt)))
13341 (setq lines (org-split-string txt "\n"))
13342 (when (and note (string-match "\\S-" note))
13343 (setq note
13344 (org-replace-escapes
13345 note
13346 (list (cons "%u" (user-login-name))
13347 (cons "%U" user-full-name)
13348 (cons "%t" (format-time-string
13349 (org-time-stamp-format 'long 'inactive)
13350 org-log-note-effective-time))
13351 (cons "%T" (format-time-string
13352 (org-time-stamp-format 'long nil)
13353 org-log-note-effective-time))
13354 (cons "%d" (format-time-string
13355 (org-time-stamp-format nil 'inactive)
13356 org-log-note-effective-time))
13357 (cons "%D" (format-time-string
13358 (org-time-stamp-format nil nil)
13359 org-log-note-effective-time))
13360 (cons "%s" (if org-log-note-state
13361 (concat "\"" org-log-note-state "\"")
13362 ""))
13363 (cons "%S" (if org-log-note-previous-state
13364 (concat "\"" org-log-note-previous-state "\"")
13365 "\"\"")))))
13366 (if lines (setq note (concat note " \\\\")))
13367 (push note lines))
13368 (when (or current-prefix-arg org-note-abort)
13369 (when org-log-into-drawer
13370 (org-remove-empty-drawer-at
13371 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
13372 org-log-note-marker))
13373 (setq lines nil))
13374 (when lines
13375 (with-current-buffer (marker-buffer org-log-note-marker)
13376 (save-excursion
13377 (goto-char org-log-note-marker)
13378 (move-marker org-log-note-marker nil)
13379 (end-of-line 1)
13380 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13381 (setq ind (save-excursion
13382 (if (ignore-errors (goto-char (org-in-item-p)))
13383 (let ((struct (org-list-struct)))
13384 (org-list-get-ind
13385 (org-list-get-top-point struct) struct))
13386 (skip-chars-backward " \r\t\n")
13387 (cond
13388 ((and (org-at-heading-p)
13389 org-adapt-indentation)
13390 (1+ (org-current-level)))
13391 ((org-at-heading-p) 0)
13392 (t (org-get-indentation))))))
13393 (setq bul (org-list-bullet-string "-"))
13394 (org-indent-line-to ind)
13395 (insert bul (pop lines))
13396 (let ((ind-body (+ (length bul) ind)))
13397 (while lines
13398 (insert "\n")
13399 (org-indent-line-to ind-body)
13400 (insert (pop lines))))
13401 (message "Note stored")
13402 (org-back-to-heading t)
13403 (org-cycle-hide-drawers 'children))
13404 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13405 ;; from within `org-add-log-note' because `buffer-undo-list'
13406 ;; is then modified outside of `org-with-remote-undo'.
13407 (when (eq this-command 'org-agenda-todo)
13408 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13409 ;; Don't add undo information when called from `org-agenda-todo'
13410 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13411 (set-window-configuration org-log-note-window-configuration)
13412 (with-current-buffer (marker-buffer org-log-note-return-to)
13413 (goto-char org-log-note-return-to))
13414 (move-marker org-log-note-return-to nil)
13415 (and org-log-post-message (message "%s" org-log-post-message))))
13417 (defun org-remove-empty-drawer-at (drawer pos)
13418 "Remove an empty drawer DRAWER at position POS.
13419 POS may also be a marker."
13420 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13421 (save-excursion
13422 (save-restriction
13423 (widen)
13424 (goto-char pos)
13425 (if (org-in-regexp
13426 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13427 (replace-match ""))))))
13429 (defvar org-ts-type nil)
13430 (defun org-sparse-tree (&optional arg type)
13431 "Create a sparse tree, prompt for the details.
13432 This command can create sparse trees. You first need to select the type
13433 of match used to create the tree:
13435 t Show all TODO entries.
13436 T Show entries with a specific TODO keyword.
13437 m Show entries selected by a tags/property match.
13438 p Enter a property name and its value (both with completion on existing
13439 names/values) and show entries with that property.
13440 r Show entries matching a regular expression (`/' can be used as well).
13441 b Show deadlines and scheduled items before a date.
13442 a Show deadlines and scheduled items after a date.
13443 d Show deadlines due within `org-deadline-warning-days'.
13444 D Show deadlines and scheduled items between a date range."
13445 (interactive "P")
13446 (let (ans kwd value ts-type)
13447 (setq type (or type org-sparse-tree-default-date-type))
13448 (setq org-ts-type type)
13449 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty\n [d]eadlines [b]efore-date [a]fter-date [D]ates range\n [c]ycle through date types: %s"
13450 (cond ((eq type 'all) "all timestamps")
13451 ((eq type 'scheduled) "only scheduled")
13452 ((eq type 'deadline) "only deadline")
13453 ((eq type 'active) "only active timestamps")
13454 ((eq type 'inactive) "only inactive timestamps")
13455 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13456 ((eq type 'closed) "with a closed time-stamp")
13457 (t "scheduled/deadline")))
13458 (setq ans (read-char-exclusive))
13459 (cond
13460 ((equal ans ?c)
13461 (org-sparse-tree
13462 arg (cadr (member type '(scheduled-or-deadline
13463 all scheduled deadline active inactive closed)))))
13464 ((equal ans ?d)
13465 (call-interactively 'org-check-deadlines))
13466 ((equal ans ?b)
13467 (call-interactively 'org-check-before-date))
13468 ((equal ans ?a)
13469 (call-interactively 'org-check-after-date))
13470 ((equal ans ?D)
13471 (call-interactively 'org-check-dates-range))
13472 ((equal ans ?t)
13473 (call-interactively 'org-show-todo-tree))
13474 ((equal ans ?T)
13475 (org-show-todo-tree '(4)))
13476 ((member ans '(?T ?m))
13477 (call-interactively 'org-match-sparse-tree))
13478 ((member ans '(?p ?P))
13479 (setq kwd (org-icompleting-read "Property: "
13480 (mapcar 'list (org-buffer-property-keys))))
13481 (setq value (org-icompleting-read "Value: "
13482 (mapcar 'list (org-property-values kwd))))
13483 (unless (string-match "\\`{.*}\\'" value)
13484 (setq value (concat "\"" value "\"")))
13485 (org-match-sparse-tree arg (concat kwd "=" value)))
13486 ((member ans '(?r ?R ?/))
13487 (call-interactively 'org-occur))
13488 (t (user-error "No such sparse tree command \"%c\"" ans)))))
13490 (defvar org-occur-highlights nil
13491 "List of overlays used for occur matches.")
13492 (make-variable-buffer-local 'org-occur-highlights)
13493 (defvar org-occur-parameters nil
13494 "Parameters of the active org-occur calls.
13495 This is a list, each call to org-occur pushes as cons cell,
13496 containing the regular expression and the callback, onto the list.
13497 The list can contain several entries if `org-occur' has been called
13498 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13499 will only contain one set of parameters. When the highlights are
13500 removed (for example with `C-c C-c', or with the next edit (depending
13501 on `org-remove-highlights-with-change'), this variable is emptied
13502 as well.")
13503 (make-variable-buffer-local 'org-occur-parameters)
13505 (defun org-occur (regexp &optional keep-previous callback)
13506 "Make a compact tree which shows all matches of REGEXP.
13507 The tree will show the lines where the regexp matches, and all higher
13508 headlines above the match. It will also show the heading after the match,
13509 to make sure editing the matching entry is easy.
13510 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13511 call to `org-occur' will be kept, to allow stacking of calls to this
13512 command.
13513 If CALLBACK is non-nil, it is a function which is called to confirm
13514 that the match should indeed be shown."
13515 (interactive "sRegexp: \nP")
13516 (when (equal regexp "")
13517 (user-error "Regexp cannot be empty"))
13518 (unless keep-previous
13519 (org-remove-occur-highlights nil nil t))
13520 (push (cons regexp callback) org-occur-parameters)
13521 (let ((cnt 0))
13522 (save-excursion
13523 (goto-char (point-min))
13524 (if (or (not keep-previous) ; do not want to keep
13525 (not org-occur-highlights)) ; no previous matches
13526 ;; hide everything
13527 (org-overview))
13528 (while (re-search-forward regexp nil t)
13529 (when (or (not callback)
13530 (save-match-data (funcall callback)))
13531 (setq cnt (1+ cnt))
13532 (when org-highlight-sparse-tree-matches
13533 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13534 (org-show-context 'occur-tree))))
13535 (when org-remove-highlights-with-change
13536 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13537 nil 'local))
13538 (unless org-sparse-tree-open-archived-trees
13539 (org-hide-archived-subtrees (point-min) (point-max)))
13540 (run-hooks 'org-occur-hook)
13541 (if (org-called-interactively-p 'interactive)
13542 (message "%d match(es) for regexp %s" cnt regexp))
13543 cnt))
13545 (defun org-occur-next-match (&optional n reset)
13546 "Function for `next-error-function' to find sparse tree matches.
13547 N is the number of matches to move, when negative move backwards.
13548 RESET is entirely ignored - this function always goes back to the
13549 starting point when no match is found."
13550 (let* ((limit (if (< n 0) (point-min) (point-max)))
13551 (search-func (if (< n 0)
13552 'previous-single-char-property-change
13553 'next-single-char-property-change))
13554 (n (abs n))
13555 (pos (point))
13557 (catch 'exit
13558 (while (setq p1 (funcall search-func (point) 'org-type))
13559 (when (equal p1 limit)
13560 (goto-char pos)
13561 (error "No more matches"))
13562 (when (equal (get-char-property p1 'org-type) 'org-occur)
13563 (setq n (1- n))
13564 (when (= n 0)
13565 (goto-char p1)
13566 (throw 'exit (point))))
13567 (goto-char p1))
13568 (goto-char p1)
13569 (error "No more matches"))))
13571 (defun org-show-context (&optional key)
13572 "Make sure point and context are visible.
13573 How much context is shown depends upon the variables
13574 `org-show-hierarchy-above', `org-show-following-heading',
13575 `org-show-entry-below' and `org-show-siblings'."
13576 (let ((heading-p (org-at-heading-p t))
13577 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13578 (following-p (org-get-alist-option org-show-following-heading key))
13579 (entry-p (org-get-alist-option org-show-entry-below key))
13580 (siblings-p (org-get-alist-option org-show-siblings key)))
13581 ;; Show heading or entry text
13582 (if (and heading-p (not entry-p))
13583 (org-flag-heading nil) ; only show the heading
13584 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13585 (org-show-hidden-entry))) ; show entire entry
13586 (when following-p
13587 ;; Show next sibling, or heading below text
13588 (save-excursion
13589 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13590 (org-flag-heading nil))))
13591 (when siblings-p (org-show-siblings))
13592 (when hierarchy-p
13593 ;; show all higher headings, possibly with siblings
13594 (save-excursion
13595 (while (and (condition-case nil
13596 (progn (org-up-heading-all 1) t)
13597 (error nil))
13598 (not (bobp)))
13599 (org-flag-heading nil)
13600 (when siblings-p (org-show-siblings)))))
13601 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13603 (defvar org-reveal-start-hook nil
13604 "Hook run before revealing a location.")
13606 (defun org-reveal (&optional siblings)
13607 "Show current entry, hierarchy above it, and the following headline.
13608 This can be used to show a consistent set of context around locations
13609 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13610 not t for the search context.
13612 With optional argument SIBLINGS, on each level of the hierarchy all
13613 siblings are shown. This repairs the tree structure to what it would
13614 look like when opened with hierarchical calls to `org-cycle'.
13615 With double optional argument \\[universal-argument] \\[universal-argument], \
13616 go to the parent and show the
13617 entire tree."
13618 (interactive "P")
13619 (run-hooks 'org-reveal-start-hook)
13620 (let ((org-show-hierarchy-above t)
13621 (org-show-following-heading t)
13622 (org-show-siblings (if siblings t org-show-siblings)))
13623 (org-show-context nil))
13624 (when (equal siblings '(16))
13625 (save-excursion
13626 (when (org-up-heading-safe)
13627 (org-show-subtree)
13628 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13630 (defun org-highlight-new-match (beg end)
13631 "Highlight from BEG to END and mark the highlight is an occur headline."
13632 (let ((ov (make-overlay beg end)))
13633 (overlay-put ov 'face 'secondary-selection)
13634 (overlay-put ov 'org-type 'org-occur)
13635 (push ov org-occur-highlights)))
13637 (defun org-remove-occur-highlights (&optional beg end noremove)
13638 "Remove the occur highlights from the buffer.
13639 BEG and END are ignored. If NOREMOVE is nil, remove this function
13640 from the `before-change-functions' in the current buffer."
13641 (interactive)
13642 (unless org-inhibit-highlight-removal
13643 (mapc 'delete-overlay org-occur-highlights)
13644 (setq org-occur-highlights nil)
13645 (setq org-occur-parameters nil)
13646 (unless noremove
13647 (remove-hook 'before-change-functions
13648 'org-remove-occur-highlights 'local))))
13650 ;;;; Priorities
13652 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13653 "Regular expression matching the priority indicator.")
13655 (defvar org-remove-priority-next-time nil)
13657 (defun org-priority-up ()
13658 "Increase the priority of the current item."
13659 (interactive)
13660 (org-priority 'up))
13662 (defun org-priority-down ()
13663 "Decrease the priority of the current item."
13664 (interactive)
13665 (org-priority 'down))
13667 (defun org-priority (&optional action show)
13668 "Change the priority of an item.
13669 ACTION can be `set', `up', `down', or a character."
13670 (interactive "P")
13671 (if (equal action '(4))
13672 (org-show-priority)
13673 (unless org-enable-priority-commands
13674 (user-error "Priority commands are disabled"))
13675 (setq action (or action 'set))
13676 (let (current new news have remove)
13677 (save-excursion
13678 (org-back-to-heading t)
13679 (if (looking-at org-priority-regexp)
13680 (setq current (string-to-char (match-string 2))
13681 have t))
13682 (cond
13683 ((eq action 'remove)
13684 (setq remove t new ?\ ))
13685 ((or (eq action 'set)
13686 (if (featurep 'xemacs) (characterp action) (integerp action)))
13687 (if (not (eq action 'set))
13688 (setq new action)
13689 (message "Priority %c-%c, SPC to remove: "
13690 org-highest-priority org-lowest-priority)
13691 (save-match-data
13692 (setq new (read-char-exclusive))))
13693 (if (and (= (upcase org-highest-priority) org-highest-priority)
13694 (= (upcase org-lowest-priority) org-lowest-priority))
13695 (setq new (upcase new)))
13696 (cond ((equal new ?\ ) (setq remove t))
13697 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13698 (user-error "Priority must be between `%c' and `%c'"
13699 org-highest-priority org-lowest-priority))))
13700 ((eq action 'up)
13701 (setq new (if have
13702 (1- current) ; normal cycling
13703 ;; last priority was empty
13704 (if (eq last-command this-command)
13705 org-lowest-priority ; wrap around empty to lowest
13706 ;; default
13707 (if org-priority-start-cycle-with-default
13708 org-default-priority
13709 (1- org-default-priority))))))
13710 ((eq action 'down)
13711 (setq new (if have
13712 (1+ current) ; normal cycling
13713 ;; last priority was empty
13714 (if (eq last-command this-command)
13715 org-highest-priority ; wrap around empty to highest
13716 ;; default
13717 (if org-priority-start-cycle-with-default
13718 org-default-priority
13719 (1+ org-default-priority))))))
13720 (t (user-error "Invalid action")))
13721 (if (or (< (upcase new) org-highest-priority)
13722 (> (upcase new) org-lowest-priority))
13723 (if (and (memq action '(up down))
13724 (not have) (not (eq last-command this-command)))
13725 ;; `new' is from default priority
13726 (error
13727 "The default can not be set, see `org-default-priority' why")
13728 ;; normal cycling: `new' is beyond highest/lowest priority
13729 ;; and is wrapped around to the empty priority
13730 (setq remove t)))
13731 (setq news (format "%c" new))
13732 (if have
13733 (if remove
13734 (replace-match "" t t nil 1)
13735 (replace-match news t t nil 2))
13736 (if remove
13737 (user-error "No priority cookie found in line")
13738 (let ((case-fold-search nil))
13739 (looking-at org-todo-line-regexp))
13740 (if (match-end 2)
13741 (progn
13742 (goto-char (match-end 2))
13743 (insert " [#" news "]"))
13744 (goto-char (match-beginning 3))
13745 (insert "[#" news "] "))))
13746 (org-preserve-lc (org-set-tags nil 'align)))
13747 (if remove
13748 (message "Priority removed")
13749 (message "Priority of current item set to %s" news)))))
13751 (defun org-show-priority ()
13752 "Show the priority of the current item.
13753 This priority is composed of the main priority given with the [#A] cookies,
13754 and by additional input from the age of a schedules or deadline entry."
13755 (interactive)
13756 (let ((pri (if (eq major-mode 'org-agenda-mode)
13757 (org-get-at-bol 'priority)
13758 (save-excursion
13759 (save-match-data
13760 (beginning-of-line)
13761 (and (looking-at org-heading-regexp)
13762 (org-get-priority (match-string 0))))))))
13763 (message "Priority is %d" (if pri pri -1000))))
13765 (defun org-get-priority (s)
13766 "Find priority cookie and return priority."
13767 (save-match-data
13768 (if (functionp org-get-priority-function)
13769 (funcall org-get-priority-function)
13770 (if (not (string-match org-priority-regexp s))
13771 (* 1000 (- org-lowest-priority org-default-priority))
13772 (* 1000 (- org-lowest-priority
13773 (string-to-char (match-string 2 s))))))))
13775 ;;;; Tags
13777 (defvar org-agenda-archives-mode)
13778 (defvar org-map-continue-from nil
13779 "Position from where mapping should continue.
13780 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13782 (defvar org-scanner-tags nil
13783 "The current tag list while the tags scanner is running.")
13784 (defvar org-trust-scanner-tags nil
13785 "Should `org-get-tags-at' use the tags for the scanner.
13786 This is for internal dynamical scoping only.
13787 When this is non-nil, the function `org-get-tags-at' will return the value
13788 of `org-scanner-tags' instead of building the list by itself. This
13789 can lead to large speed-ups when the tags scanner is used in a file with
13790 many entries, and when the list of tags is retrieved, for example to
13791 obtain a list of properties. Building the tags list for each entry in such
13792 a file becomes an N^2 operation - but with this variable set, it scales
13793 as N.")
13795 (defun org-scan-tags (action matcher todo-only &optional start-level)
13796 "Sca headline tags with inheritance and produce output ACTION.
13798 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13799 or `agenda' to produce an entry list for an agenda view. It can also be
13800 a Lisp form or a function that should be called at each matched headline, in
13801 this case the return value is a list of all return values from these calls.
13803 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13804 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13805 only lines with a not-done TODO keyword are included in the output.
13806 This should be the same variable that was scoped into
13807 and set by `org-make-tags-matcher' when it constructed MATCHER.
13809 START-LEVEL can be a string with asterisks, reducing the scope to
13810 headlines matching this string."
13811 (require 'org-agenda)
13812 (let* ((re (concat "^"
13813 (if start-level
13814 ;; Get the correct level to match
13815 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13816 org-outline-regexp)
13817 " *\\(\\<\\("
13818 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13819 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13820 (props (list 'face 'default
13821 'done-face 'org-agenda-done
13822 'undone-face 'default
13823 'mouse-face 'highlight
13824 'org-not-done-regexp org-not-done-regexp
13825 'org-todo-regexp org-todo-regexp
13826 'org-complex-heading-regexp org-complex-heading-regexp
13827 'help-echo
13828 (format "mouse-2 or RET jump to org file %s"
13829 (abbreviate-file-name
13830 (or (buffer-file-name (buffer-base-buffer))
13831 (buffer-name (buffer-base-buffer)))))))
13832 (org-map-continue-from nil)
13833 lspos tags tags-list
13834 (tags-alist (list (cons 0 org-file-tags)))
13835 (llast 0) rtn rtn1 level category i txt
13836 todo marker entry priority)
13837 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13838 (setq action (list 'lambda nil action)))
13839 (save-excursion
13840 (goto-char (point-min))
13841 (when (eq action 'sparse-tree)
13842 (org-overview)
13843 (org-remove-occur-highlights))
13844 (while (let (case-fold-search)
13845 (re-search-forward re nil t))
13846 (setq org-map-continue-from nil)
13847 (catch :skip
13848 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13849 tags (if (match-end 4) (org-match-string-no-properties 4)))
13850 (goto-char (setq lspos (match-beginning 0)))
13851 (setq level (org-reduced-level (org-outline-level))
13852 category (org-get-category))
13853 (setq i llast llast level)
13854 ;; remove tag lists from same and sublevels
13855 (while (>= i level)
13856 (when (setq entry (assoc i tags-alist))
13857 (setq tags-alist (delete entry tags-alist)))
13858 (setq i (1- i)))
13859 ;; add the next tags
13860 (when tags
13861 (setq tags (org-split-string tags ":")
13862 tags-alist
13863 (cons (cons level tags) tags-alist)))
13864 ;; compile tags for current headline
13865 (setq tags-list
13866 (if org-use-tag-inheritance
13867 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13868 tags)
13869 org-scanner-tags tags-list)
13870 (when org-use-tag-inheritance
13871 (setcdr (car tags-alist)
13872 (mapcar (lambda (x)
13873 (setq x (copy-sequence x))
13874 (org-add-prop-inherited x))
13875 (cdar tags-alist))))
13876 (when (and tags org-use-tag-inheritance
13877 (or (not (eq t org-use-tag-inheritance))
13878 org-tags-exclude-from-inheritance))
13879 ;; selective inheritance, remove uninherited ones
13880 (setcdr (car tags-alist)
13881 (org-remove-uninherited-tags (cdar tags-alist))))
13882 (when (and
13884 ;; eval matcher only when the todo condition is OK
13885 (and (or (not todo-only) (member todo org-not-done-keywords))
13886 (let ((case-fold-search t) (org-trust-scanner-tags t))
13887 (eval matcher)))
13889 ;; Call the skipper, but return t if it does not skip,
13890 ;; so that the `and' form continues evaluating
13891 (progn
13892 (unless (eq action 'sparse-tree) (org-agenda-skip))
13895 ;; Check if timestamps are deselecting this entry
13896 (or (not todo-only)
13897 (and (member todo org-not-done-keywords)
13898 (or (not org-agenda-tags-todo-honor-ignore-options)
13899 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13901 ;; select this headline
13902 (cond
13903 ((eq action 'sparse-tree)
13904 (and org-highlight-sparse-tree-matches
13905 (org-get-heading) (match-end 0)
13906 (org-highlight-new-match
13907 (match-beginning 1) (match-end 1)))
13908 (org-show-context 'tags-tree))
13909 ((eq action 'agenda)
13910 (setq txt (org-agenda-format-item
13912 (concat
13913 (if (eq org-tags-match-list-sublevels 'indented)
13914 (make-string (1- level) ?.) "")
13915 (org-get-heading))
13916 level category
13917 tags-list)
13918 priority (org-get-priority txt))
13919 (goto-char lspos)
13920 (setq marker (org-agenda-new-marker))
13921 (org-add-props txt props
13922 'org-marker marker 'org-hd-marker marker 'org-category category
13923 'todo-state todo
13924 'priority priority 'type "tagsmatch")
13925 (push txt rtn))
13926 ((functionp action)
13927 (setq org-map-continue-from nil)
13928 (save-excursion
13929 (setq rtn1 (funcall action))
13930 (push rtn1 rtn)))
13931 (t (user-error "Invalid action")))
13933 ;; if we are to skip sublevels, jump to end of subtree
13934 (unless org-tags-match-list-sublevels
13935 (org-end-of-subtree t)
13936 (backward-char 1))))
13937 ;; Get the correct position from where to continue
13938 (if org-map-continue-from
13939 (goto-char org-map-continue-from)
13940 (and (= (point) lspos) (end-of-line 1)))))
13941 (when (and (eq action 'sparse-tree)
13942 (not org-sparse-tree-open-archived-trees))
13943 (org-hide-archived-subtrees (point-min) (point-max)))
13944 (nreverse rtn)))
13946 (defun org-remove-uninherited-tags (tags)
13947 "Remove all tags that are not inherited from the list TAGS."
13948 (cond
13949 ((eq org-use-tag-inheritance t)
13950 (if org-tags-exclude-from-inheritance
13951 (org-delete-all org-tags-exclude-from-inheritance tags)
13952 tags))
13953 ((not org-use-tag-inheritance) nil)
13954 ((stringp org-use-tag-inheritance)
13955 (delq nil (mapcar
13956 (lambda (x)
13957 (if (and (string-match org-use-tag-inheritance x)
13958 (not (member x org-tags-exclude-from-inheritance)))
13959 x nil))
13960 tags)))
13961 ((listp org-use-tag-inheritance)
13962 (delq nil (mapcar
13963 (lambda (x)
13964 (if (member x org-use-tag-inheritance) x nil))
13965 tags)))))
13967 (defun org-match-sparse-tree (&optional todo-only match)
13968 "Create a sparse tree according to tags string MATCH.
13969 MATCH can contain positive and negative selection of tags, like
13970 \"+WORK+URGENT-WITHBOSS\".
13971 If optional argument TODO-ONLY is non-nil, only select lines that are
13972 also TODO lines."
13973 (interactive "P")
13974 (org-agenda-prepare-buffers (list (current-buffer)))
13975 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13977 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13979 (defvar org-cached-props nil)
13980 (defun org-cached-entry-get (pom property)
13981 (if (or (eq t org-use-property-inheritance)
13982 (and (stringp org-use-property-inheritance)
13983 (string-match org-use-property-inheritance property))
13984 (and (listp org-use-property-inheritance)
13985 (member property org-use-property-inheritance)))
13986 ;; Caching is not possible, check it directly
13987 (org-entry-get pom property 'inherit)
13988 ;; Get all properties, so that we can do complicated checks easily
13989 (cdr (assoc property (or org-cached-props
13990 (setq org-cached-props
13991 (org-entry-properties pom)))))))
13993 (defun org-global-tags-completion-table (&optional files)
13994 "Return the list of all tags in all agenda buffer/files.
13995 Optional FILES argument is a list of files which can be used
13996 instead of the agenda files."
13997 (save-excursion
13998 (org-uniquify
13999 (delq nil
14000 (apply 'append
14001 (mapcar
14002 (lambda (file)
14003 (set-buffer (find-file-noselect file))
14004 (append (org-get-buffer-tags)
14005 (mapcar (lambda (x) (if (stringp (car-safe x))
14006 (list (car-safe x)) nil))
14007 org-tag-alist)))
14008 (if (and files (car files))
14009 files
14010 (org-agenda-files))))))))
14012 (defun org-make-tags-matcher (match)
14013 "Create the TAGS/TODO matcher form for the selection string MATCH.
14015 The variable `todo-only' is scoped dynamically into this function.
14016 It will be set to t if the matcher restricts matching to TODO entries,
14017 otherwise will not be touched.
14019 Returns a cons of the selection string MATCH and the constructed
14020 lisp form implementing the matcher. The matcher is to be evaluated
14021 at an Org entry, with point on the headline, and returns t if the
14022 entry matches the selection string MATCH. The returned lisp form
14023 references two variables with information about the entry, which
14024 must be bound around the form's evaluation: todo, the TODO keyword
14025 at the entry (or nil of none); and tags-list, the list of all tags
14026 at the entry including inherited ones. Additionally, the category
14027 of the entry (if any) must be specified as the text property
14028 'org-category on the headline.
14030 See also `org-scan-tags'.
14032 (declare (special todo-only))
14033 (unless (boundp 'todo-only)
14034 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14035 (unless match
14036 ;; Get a new match request, with completion against the global
14037 ;; tags table and the local tags in current buffer
14038 (let ((org-last-tags-completion-table
14039 (org-uniquify
14040 (delq nil (append (org-get-buffer-tags)
14041 (org-global-tags-completion-table))))))
14042 (setq match (org-completing-read-no-i
14043 "Match: " 'org-tags-completion-function nil nil nil
14044 'org-tags-history))))
14046 ;; Parse the string and create a lisp form
14047 (let ((match0 match)
14048 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14049 minus tag mm
14050 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14051 orterms term orlist re-p str-p level-p level-op time-p
14052 prop-p pn pv po gv rest (start 0) (ss 0))
14053 ;; Expand group tags
14054 (setq match (org-tags-expand match))
14056 ;; Check if there is a TODO part of this match, which would be the
14057 ;; part after a "/". TO make sure that this slash is not part of
14058 ;; a property value to be matched against, we also check that there
14059 ;; is no " after that slash.
14060 ;; First, find the last slash
14061 (while (string-match "/+" match ss)
14062 (setq start (match-beginning 0) ss (match-end 0)))
14063 (if (and (string-match "/+" match start)
14064 (not (save-match-data (string-match "\"" match start))))
14065 ;; match contains also a todo-matching request
14066 (progn
14067 (setq tagsmatch (substring match 0 (match-beginning 0))
14068 todomatch (substring match (match-end 0)))
14069 (if (string-match "^!" todomatch)
14070 (setq todo-only t todomatch (substring todomatch 1)))
14071 (if (string-match "^\\s-*$" todomatch)
14072 (setq todomatch nil)))
14073 ;; only matching tags
14074 (setq tagsmatch match todomatch nil))
14076 ;; Make the tags matcher
14077 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14078 (setq tagsmatcher t)
14079 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14080 (while (setq term (pop orterms))
14081 (while (and (equal (substring term -1) "\\") orterms)
14082 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14083 (while (string-match re term)
14084 (setq rest (substring term (match-end 0))
14085 minus (and (match-end 1)
14086 (equal (match-string 1 term) "-"))
14087 tag (save-match-data (replace-regexp-in-string
14088 "\\\\-" "-"
14089 (match-string 2 term)))
14090 re-p (equal (string-to-char tag) ?{)
14091 level-p (match-end 4)
14092 prop-p (match-end 5)
14093 mm (cond
14094 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14095 (level-p
14096 (setq level-op (org-op-to-function (match-string 3 term)))
14097 `(,level-op level ,(string-to-number
14098 (match-string 4 term))))
14099 (prop-p
14100 (setq pn (match-string 5 term)
14101 po (match-string 6 term)
14102 pv (match-string 7 term)
14103 re-p (equal (string-to-char pv) ?{)
14104 str-p (equal (string-to-char pv) ?\")
14105 time-p (save-match-data
14106 (string-match "^\"[[<].*[]>]\"$" pv))
14107 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14108 (if time-p (setq pv (org-matcher-time pv)))
14109 (setq po (org-op-to-function po (if time-p 'time str-p)))
14110 (cond
14111 ((equal pn "CATEGORY")
14112 (setq gv '(get-text-property (point) 'org-category)))
14113 ((equal pn "TODO")
14114 (setq gv 'todo))
14116 (setq gv `(org-cached-entry-get nil ,pn))))
14117 (if re-p
14118 (if (eq po 'org<>)
14119 `(not (string-match ,pv (or ,gv "")))
14120 `(string-match ,pv (or ,gv "")))
14121 (if str-p
14122 `(,po (or ,gv "") ,pv)
14123 `(,po (string-to-number (or ,gv ""))
14124 ,(string-to-number pv) ))))
14125 (t `(member ,tag tags-list)))
14126 mm (if minus (list 'not mm) mm)
14127 term rest)
14128 (push mm tagsmatcher))
14129 (push (if (> (length tagsmatcher) 1)
14130 (cons 'and tagsmatcher)
14131 (car tagsmatcher))
14132 orlist)
14133 (setq tagsmatcher nil))
14134 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14135 (setq tagsmatcher
14136 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14137 ;; Make the todo matcher
14138 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14139 (setq todomatcher t)
14140 (setq orterms (org-split-string todomatch "|") orlist nil)
14141 (while (setq term (pop orterms))
14142 (while (string-match re term)
14143 (setq minus (and (match-end 1)
14144 (equal (match-string 1 term) "-"))
14145 kwd (match-string 2 term)
14146 re-p (equal (string-to-char kwd) ?{)
14147 term (substring term (match-end 0))
14148 mm (if re-p
14149 `(string-match ,(substring kwd 1 -1) todo)
14150 (list 'equal 'todo kwd))
14151 mm (if minus (list 'not mm) mm))
14152 (push mm todomatcher))
14153 (push (if (> (length todomatcher) 1)
14154 (cons 'and todomatcher)
14155 (car todomatcher))
14156 orlist)
14157 (setq todomatcher nil))
14158 (setq todomatcher (if (> (length orlist) 1)
14159 (cons 'or orlist) (car orlist))))
14161 ;; Return the string and lisp forms of the matcher
14162 (setq matcher (if todomatcher
14163 (list 'and tagsmatcher todomatcher)
14164 tagsmatcher))
14165 (when todo-only
14166 (setq matcher (list 'and '(member todo org-not-done-keywords)
14167 matcher)))
14168 (cons match0 matcher)))
14170 (defun org-tags-expand (match &optional single-as-list downcased)
14171 "Expand group tags in MATCH.
14173 This replaces every group tag in MATCH with a regexp tag search.
14174 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14175 will be replaced like this:
14177 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14178 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14179 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14181 Replacing by a regexp preserves the structure of the match.
14182 E.g., this expansion
14184 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14186 will match anything tagged with \"Lab\" and \"Home\", or tagged
14187 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14189 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14190 assumed to be a single group tag, and the function will return
14191 the list of tags in this group.
14193 When DOWNCASE is non-nil, expand downcased TAGS."
14194 (if org-group-tags
14195 (let* ((case-fold-search t)
14196 (stable org-mode-syntax-table)
14197 (tal (or org-tag-groups-alist-for-agenda
14198 org-tag-groups-alist))
14199 (tal (if downcased
14200 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14201 (tml (mapcar 'car tal))
14202 (rtnmatch match) rpl)
14203 ;; @ and _ are allowed as word-components in tags
14204 (modify-syntax-entry ?@ "w" stable)
14205 (modify-syntax-entry ?_ "w" stable)
14206 (while (and tml
14207 (with-syntax-table stable
14208 (string-match
14209 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14210 (regexp-opt tml) "\\>\\)") rtnmatch)))
14211 (let* ((dir (match-string 1 rtnmatch))
14212 (tag (match-string 2 rtnmatch))
14213 (tag (if downcased (downcase tag) tag)))
14214 (setq tml (delete tag tml))
14215 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14216 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14217 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14218 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14219 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14220 (if single-as-list
14221 (or (reverse rpl) (list rtnmatch))
14222 rtnmatch))
14223 (if single-as-list (list (if downcased (downcase match) match))
14224 match)))
14226 (defun org-op-to-function (op &optional stringp)
14227 "Turn an operator into the appropriate function."
14228 (setq op
14229 (cond
14230 ((equal op "<" ) '(< string< org-time<))
14231 ((equal op ">" ) '(> org-string> org-time>))
14232 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14233 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14234 ((member op '("=" "==")) '(= string= org-time=))
14235 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14236 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14238 (defun org<> (a b) (not (= a b)))
14239 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14240 (defun org-string>= (a b) (not (string< a b)))
14241 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14242 (defun org-string<> (a b) (not (string= a b)))
14243 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14244 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14245 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14246 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14247 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14248 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14249 (defun org-2ft (s)
14250 "Convert S to a floating point time.
14251 If S is already a number, just return it. If it is a string, parse
14252 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14253 (cond
14254 ((numberp s) s)
14255 ((stringp s)
14256 (condition-case nil
14257 (float-time (apply 'encode-time (org-parse-time-string s)))
14258 (error 0.)))
14259 (t 0.)))
14261 (defun org-time-today ()
14262 "Time in seconds today at 0:00.
14263 Returns the float number of seconds since the beginning of the
14264 epoch to the beginning of today (00:00)."
14265 (float-time (apply 'encode-time
14266 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14268 (defun org-matcher-time (s)
14269 "Interpret a time comparison value."
14270 (save-match-data
14271 (cond
14272 ((string= s "<now>") (float-time))
14273 ((string= s "<today>") (org-time-today))
14274 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14275 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14276 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14277 (+ (org-time-today)
14278 (* (string-to-number (match-string 1 s))
14279 (cdr (assoc (match-string 2 s)
14280 '(("d" . 86400.0) ("w" . 604800.0)
14281 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14282 (t (org-2ft s)))))
14284 (defun org-match-any-p (re list)
14285 "Does re match any element of list?"
14286 (setq list (mapcar (lambda (x) (string-match re x)) list))
14287 (delq nil list))
14289 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14290 (defvar org-tags-overlay (make-overlay 1 1))
14291 (org-detach-overlay org-tags-overlay)
14293 (defun org-get-local-tags-at (&optional pos)
14294 "Get a list of tags defined in the current headline."
14295 (org-get-tags-at pos 'local))
14297 (defun org-get-local-tags ()
14298 "Get a list of tags defined in the current headline."
14299 (org-get-tags-at nil 'local))
14301 (defun org-get-tags-at (&optional pos local)
14302 "Get a list of all headline tags applicable at POS.
14303 POS defaults to point. If tags are inherited, the list contains
14304 the targets in the same sequence as the headlines appear, i.e.
14305 the tags of the current headline come last.
14306 When LOCAL is non-nil, only return tags from the current headline,
14307 ignore inherited ones."
14308 (interactive)
14309 (if (and org-trust-scanner-tags
14310 (or (not pos) (equal pos (point)))
14311 (not local))
14312 org-scanner-tags
14313 (let (tags ltags lastpos parent)
14314 (save-excursion
14315 (save-restriction
14316 (widen)
14317 (goto-char (or pos (point)))
14318 (save-match-data
14319 (catch 'done
14320 (condition-case nil
14321 (progn
14322 (org-back-to-heading t)
14323 (while (not (equal lastpos (point)))
14324 (setq lastpos (point))
14325 (when (looking-at
14326 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14327 (setq ltags (org-split-string
14328 (org-match-string-no-properties 1) ":"))
14329 (when parent
14330 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14331 (setq tags (append
14332 (if parent
14333 (org-remove-uninherited-tags ltags)
14334 ltags)
14335 tags)))
14336 (or org-use-tag-inheritance (throw 'done t))
14337 (if local (throw 'done t))
14338 (or (org-up-heading-safe) (error nil))
14339 (setq parent t)))
14340 (error nil)))))
14341 (if local
14342 tags
14343 (reverse (delete-dups
14344 (reverse (append
14345 (org-remove-uninherited-tags
14346 org-file-tags) tags)))))))))
14348 (defun org-add-prop-inherited (s)
14349 (add-text-properties 0 (length s) '(inherited t) s)
14352 (defun org-toggle-tag (tag &optional onoff)
14353 "Toggle the tag TAG for the current line.
14354 If ONOFF is `on' or `off', don't toggle but set to this state."
14355 (let (res current)
14356 (save-excursion
14357 (org-back-to-heading t)
14358 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14359 (point-at-eol) t)
14360 (progn
14361 (setq current (match-string 1))
14362 (replace-match ""))
14363 (setq current ""))
14364 (setq current (nreverse (org-split-string current ":")))
14365 (cond
14366 ((eq onoff 'on)
14367 (setq res t)
14368 (or (member tag current) (push tag current)))
14369 ((eq onoff 'off)
14370 (or (not (member tag current)) (setq current (delete tag current))))
14371 (t (if (member tag current)
14372 (setq current (delete tag current))
14373 (setq res t)
14374 (push tag current))))
14375 (end-of-line 1)
14376 (if current
14377 (progn
14378 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14379 (org-set-tags nil t))
14380 (delete-horizontal-space))
14381 (run-hooks 'org-after-tags-change-hook))
14382 res))
14384 (defun org-align-tags-here (to-col)
14385 ;; Assumes that this is a headline
14386 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14387 (beginning-of-line 1)
14388 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14389 (< pos (match-beginning 2)))
14390 (progn
14391 (setq tags-l (- (match-end 2) (match-beginning 2)))
14392 (goto-char (match-beginning 1))
14393 (insert " ")
14394 (delete-region (point) (1+ (match-beginning 2)))
14395 (setq ncol (max (current-column)
14396 (1+ col)
14397 (if (> to-col 0)
14398 to-col
14399 (- (abs to-col) tags-l))))
14400 (setq p (point))
14401 (insert (make-string (- ncol (current-column)) ?\ ))
14402 (setq ncol (current-column))
14403 (when indent-tabs-mode (tabify p (point-at-eol)))
14404 (org-move-to-column (min ncol col) t nil t))
14405 (goto-char pos))))
14407 (defun org-set-tags-command (&optional arg just-align)
14408 "Call the set-tags command for the current entry."
14409 (interactive "P")
14410 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14411 (org-set-tags arg just-align)
14412 (save-excursion
14413 (unless (and (org-region-active-p)
14414 org-loop-over-headlines-in-active-region)
14415 (org-back-to-heading t))
14416 (org-set-tags arg just-align))))
14418 (defun org-set-tags-to (data)
14419 "Set the tags of the current entry to DATA, replacing the current tags.
14420 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14421 If DATA is nil or the empty string, any tags will be removed."
14422 (interactive "sTags: ")
14423 (setq data
14424 (cond
14425 ((eq data nil) "")
14426 ((equal data "") "")
14427 ((stringp data)
14428 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14429 ":"))
14430 ((listp data)
14431 (concat ":" (mapconcat 'identity data ":") ":"))))
14432 (when data
14433 (save-excursion
14434 (org-back-to-heading t)
14435 (when (looking-at org-complex-heading-regexp)
14436 (if (match-end 5)
14437 (progn
14438 (goto-char (match-beginning 5))
14439 (insert data)
14440 (delete-region (point) (point-at-eol))
14441 (org-set-tags nil 'align))
14442 (goto-char (point-at-eol))
14443 (insert " " data)
14444 (org-set-tags nil 'align)))
14445 (beginning-of-line 1)
14446 (if (looking-at ".*?\\([ \t]+\\)$")
14447 (delete-region (match-beginning 1) (match-end 1))))))
14449 (defun org-align-all-tags ()
14450 "Align the tags i all headings."
14451 (interactive)
14452 (save-excursion
14453 (or (ignore-errors (org-back-to-heading t))
14454 (outline-next-heading))
14455 (if (org-at-heading-p)
14456 (org-set-tags t)
14457 (message "No headings"))))
14459 (defvar org-indent-indentation-per-level)
14460 (defun org-set-tags (&optional arg just-align)
14461 "Set the tags for the current headline.
14462 With prefix ARG, realign all tags in headings in the current buffer."
14463 (interactive "P")
14464 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14465 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14466 'region-start-level 'region))
14467 org-loop-over-headlines-in-active-region)
14468 (org-map-entries
14469 ;; We don't use ARG and JUST-ALIGN here these args are not
14470 ;; useful when looping over headlines
14471 `(org-set-tags)
14472 org-loop-over-headlines-in-active-region
14473 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14474 (let* ((re org-outline-regexp-bol)
14475 (current (unless arg (org-get-tags-string)))
14476 (col (current-column))
14477 (org-setting-tags t)
14478 table current-tags inherited-tags ; computed below when needed
14479 tags p0 c0 c1 rpl di tc level)
14480 (if arg
14481 (save-excursion
14482 (goto-char (point-min))
14483 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14484 (while (re-search-forward re nil t)
14485 (org-set-tags nil t)
14486 (end-of-line 1)))
14487 (message "All tags realigned to column %d" org-tags-column))
14488 (if just-align
14489 (setq tags current)
14490 ;; Get a new set of tags from the user
14491 (save-excursion
14492 (setq table (append org-tag-persistent-alist
14493 (or org-tag-alist (org-get-buffer-tags))
14494 (and
14495 org-complete-tags-always-offer-all-agenda-tags
14496 (org-global-tags-completion-table
14497 (org-agenda-files))))
14498 org-last-tags-completion-table table
14499 current-tags (org-split-string current ":")
14500 inherited-tags (nreverse
14501 (nthcdr (length current-tags)
14502 (nreverse (org-get-tags-at))))
14503 tags
14504 (if (or (eq t org-use-fast-tag-selection)
14505 (and org-use-fast-tag-selection
14506 (delq nil (mapcar 'cdr table))))
14507 (org-fast-tag-selection
14508 current-tags inherited-tags table
14509 (if org-fast-tag-selection-include-todo
14510 org-todo-key-alist))
14511 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14512 (org-trim
14513 (org-icompleting-read "Tags: "
14514 'org-tags-completion-function
14515 nil nil current 'org-tags-history))))))
14516 (while (string-match "[-+&]+" tags)
14517 ;; No boolean logic, just a list
14518 (setq tags (replace-match ":" t t tags))))
14520 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14522 (if org-tags-sort-function
14523 (setq tags (mapconcat 'identity
14524 (sort (org-split-string
14525 tags (org-re "[^[:alnum:]_@#%]+"))
14526 org-tags-sort-function) ":")))
14528 (if (string-match "\\`[\t ]*\\'" tags)
14529 (setq tags "")
14530 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14531 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14533 ;; Insert new tags at the correct column
14534 (beginning-of-line 1)
14535 (setq level (or (and (looking-at org-outline-regexp)
14536 (- (match-end 0) (point) 1))
14538 (cond
14539 ((and (equal current "") (equal tags "")))
14540 ((re-search-forward
14541 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14542 (point-at-eol) t)
14543 (if (equal tags "")
14544 (setq rpl "")
14545 (goto-char (match-beginning 0))
14546 (setq c0 (current-column)
14547 ;; compute offset for the case of org-indent-mode active
14548 di (if org-indent-mode
14549 (* (1- org-indent-indentation-per-level) (1- level))
14551 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14552 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14553 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14554 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14555 (replace-match rpl t t)
14556 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14557 tags)
14558 (t (error "Tags alignment failed")))
14559 (org-move-to-column col)
14560 (unless just-align
14561 (run-hooks 'org-after-tags-change-hook))))))
14563 (defun org-change-tag-in-region (beg end tag off)
14564 "Add or remove TAG for each entry in the region.
14565 This works in the agenda, and also in an org-mode buffer."
14566 (interactive
14567 (list (region-beginning) (region-end)
14568 (let ((org-last-tags-completion-table
14569 (if (derived-mode-p 'org-mode)
14570 (org-uniquify
14571 (delq nil (append (org-get-buffer-tags)
14572 (org-global-tags-completion-table))))
14573 (org-global-tags-completion-table))))
14574 (org-icompleting-read
14575 "Tag: " 'org-tags-completion-function nil nil nil
14576 'org-tags-history))
14577 (progn
14578 (message "[s]et or [r]emove? ")
14579 (equal (read-char-exclusive) ?r))))
14580 (if (fboundp 'deactivate-mark) (deactivate-mark))
14581 (let ((agendap (equal major-mode 'org-agenda-mode))
14582 l1 l2 m buf pos newhead (cnt 0))
14583 (goto-char end)
14584 (setq l2 (1- (org-current-line)))
14585 (goto-char beg)
14586 (setq l1 (org-current-line))
14587 (loop for l from l1 to l2 do
14588 (org-goto-line l)
14589 (setq m (get-text-property (point) 'org-hd-marker))
14590 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14591 (and agendap m))
14592 (setq buf (if agendap (marker-buffer m) (current-buffer))
14593 pos (if agendap m (point)))
14594 (with-current-buffer buf
14595 (save-excursion
14596 (save-restriction
14597 (goto-char pos)
14598 (setq cnt (1+ cnt))
14599 (org-toggle-tag tag (if off 'off 'on))
14600 (setq newhead (org-get-heading)))))
14601 (and agendap (org-agenda-change-all-lines newhead m))))
14602 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14604 (defun org-tags-completion-function (string predicate &optional flag)
14605 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14606 (confirm (lambda (x) (stringp (car x)))))
14607 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14608 (setq s1 (match-string 1 string)
14609 s2 (match-string 2 string))
14610 (setq s1 "" s2 string))
14611 (cond
14612 ((eq flag nil)
14613 ;; try completion
14614 (setq rtn (try-completion s2 ctable confirm))
14615 (if (stringp rtn)
14616 (setq rtn
14617 (concat s1 s2 (substring rtn (length s2))
14618 (if (and org-add-colon-after-tag-completion
14619 (assoc rtn ctable))
14620 ":" ""))))
14621 rtn)
14622 ((eq flag t)
14623 ;; all-completions
14624 (all-completions s2 ctable confirm))
14625 ((eq flag 'lambda)
14626 ;; exact match?
14627 (assoc s2 ctable)))))
14629 (defun org-fast-tag-insert (kwd tags face &optional end)
14630 "Insert KDW, and the TAGS, the latter with face FACE.
14631 Also insert END."
14632 (insert (format "%-12s" (concat kwd ":"))
14633 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14634 (or end "")))
14636 (defun org-fast-tag-show-exit (flag)
14637 (save-excursion
14638 (org-goto-line 3)
14639 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14640 (replace-match ""))
14641 (when flag
14642 (end-of-line 1)
14643 (org-move-to-column (- (window-width) 19) t)
14644 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14646 (defun org-set-current-tags-overlay (current prefix)
14647 "Add an overlay to CURRENT tag with PREFIX."
14648 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14649 (if (featurep 'xemacs)
14650 (org-overlay-display org-tags-overlay (concat prefix s)
14651 'secondary-selection)
14652 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14653 (org-overlay-display org-tags-overlay (concat prefix s)))))
14655 (defvar org-last-tag-selection-key nil)
14656 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14657 "Fast tag selection with single keys.
14658 CURRENT is the current list of tags in the headline, INHERITED is the
14659 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14660 possibly with grouping information. TODO-TABLE is a similar table with
14661 TODO keywords, should these have keys assigned to them.
14662 If the keys are nil, a-z are automatically assigned.
14663 Returns the new tags string, or nil to not change the current settings."
14664 (let* ((fulltable (append table todo-table))
14665 (maxlen (apply 'max (mapcar
14666 (lambda (x)
14667 (if (stringp (car x)) (string-width (car x)) 0))
14668 fulltable)))
14669 (buf (current-buffer))
14670 (expert (eq org-fast-tag-selection-single-key 'expert))
14671 (buffer-tags nil)
14672 (fwidth (+ maxlen 3 1 3))
14673 (ncol (/ (- (window-width) 4) fwidth))
14674 (i-face 'org-done)
14675 (c-face 'org-todo)
14676 tg cnt e c char c1 c2 ntable tbl rtn
14677 ov-start ov-end ov-prefix
14678 (exit-after-next org-fast-tag-selection-single-key)
14679 (done-keywords org-done-keywords)
14680 groups ingroup)
14681 (save-excursion
14682 (beginning-of-line 1)
14683 (if (looking-at
14684 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14685 (setq ov-start (match-beginning 1)
14686 ov-end (match-end 1)
14687 ov-prefix "")
14688 (setq ov-start (1- (point-at-eol))
14689 ov-end (1+ ov-start))
14690 (skip-chars-forward "^\n\r")
14691 (setq ov-prefix
14692 (concat
14693 (buffer-substring (1- (point)) (point))
14694 (if (> (current-column) org-tags-column)
14696 (make-string (- org-tags-column (current-column)) ?\ ))))))
14697 (move-overlay org-tags-overlay ov-start ov-end)
14698 (save-window-excursion
14699 (if expert
14700 (set-buffer (get-buffer-create " *Org tags*"))
14701 (delete-other-windows)
14702 (split-window-vertically)
14703 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14704 (erase-buffer)
14705 (org-set-local 'org-done-keywords done-keywords)
14706 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14707 (org-fast-tag-insert "Current" current c-face "\n\n")
14708 (org-fast-tag-show-exit exit-after-next)
14709 (org-set-current-tags-overlay current ov-prefix)
14710 (setq tbl fulltable char ?a cnt 0)
14711 (while (setq e (pop tbl))
14712 (cond
14713 ((equal (car e) :startgroup)
14714 (push '() groups) (setq ingroup t)
14715 (when (not (= cnt 0))
14716 (setq cnt 0)
14717 (insert "\n"))
14718 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14719 ((equal (car e) :endgroup)
14720 (setq ingroup nil cnt 0)
14721 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14722 ((equal e '(:newline))
14723 (when (not (= cnt 0))
14724 (setq cnt 0)
14725 (insert "\n")
14726 (setq e (car tbl))
14727 (while (equal (car tbl) '(:newline))
14728 (insert "\n")
14729 (setq tbl (cdr tbl)))))
14730 ((equal e '(:grouptags)) nil)
14732 (setq tg (copy-sequence (car e)) c2 nil)
14733 (if (cdr e)
14734 (setq c (cdr e))
14735 ;; automatically assign a character.
14736 (setq c1 (string-to-char
14737 (downcase (substring
14738 tg (if (= (string-to-char tg) ?@) 1 0)))))
14739 (if (or (rassoc c1 ntable) (rassoc c1 table))
14740 (while (or (rassoc char ntable) (rassoc char table))
14741 (setq char (1+ char)))
14742 (setq c2 c1))
14743 (setq c (or c2 char)))
14744 (if ingroup (push tg (car groups)))
14745 (setq tg (org-add-props tg nil 'face
14746 (cond
14747 ((not (assoc tg table))
14748 (org-get-todo-face tg))
14749 ((member tg current) c-face)
14750 ((member tg inherited) i-face))))
14751 (if (equal (caar tbl) :grouptags)
14752 (org-add-props tg nil 'face 'org-tag-group))
14753 (if (and (= cnt 0) (not ingroup)) (insert " "))
14754 (insert "[" c "] " tg (make-string
14755 (- fwidth 4 (length tg)) ?\ ))
14756 (push (cons tg c) ntable)
14757 (when (= (setq cnt (1+ cnt)) ncol)
14758 (insert "\n")
14759 (if ingroup (insert " "))
14760 (setq cnt 0)))))
14761 (setq ntable (nreverse ntable))
14762 (insert "\n")
14763 (goto-char (point-min))
14764 (if (not expert) (org-fit-window-to-buffer))
14765 (setq rtn
14766 (catch 'exit
14767 (while t
14768 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14769 (if (not groups) "no " "")
14770 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14771 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14772 (setq org-last-tag-selection-key c)
14773 (cond
14774 ((= c ?\r) (throw 'exit t))
14775 ((= c ?!)
14776 (setq groups (not groups))
14777 (goto-char (point-min))
14778 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14779 ((= c ?\C-c)
14780 (if (not expert)
14781 (org-fast-tag-show-exit
14782 (setq exit-after-next (not exit-after-next)))
14783 (setq expert nil)
14784 (delete-other-windows)
14785 (set-window-buffer (split-window-vertically) " *Org tags*")
14786 (org-switch-to-buffer-other-window " *Org tags*")
14787 (org-fit-window-to-buffer)))
14788 ((or (= c ?\C-g)
14789 (and (= c ?q) (not (rassoc c ntable))))
14790 (org-detach-overlay org-tags-overlay)
14791 (setq quit-flag t))
14792 ((= c ?\ )
14793 (setq current nil)
14794 (if exit-after-next (setq exit-after-next 'now)))
14795 ((= c ?\t)
14796 (condition-case nil
14797 (setq tg (org-icompleting-read
14798 "Tag: "
14799 (or buffer-tags
14800 (with-current-buffer buf
14801 (org-get-buffer-tags)))))
14802 (quit (setq tg "")))
14803 (when (string-match "\\S-" tg)
14804 (add-to-list 'buffer-tags (list tg))
14805 (if (member tg current)
14806 (setq current (delete tg current))
14807 (push tg current)))
14808 (if exit-after-next (setq exit-after-next 'now)))
14809 ((setq e (rassoc c todo-table) tg (car e))
14810 (with-current-buffer buf
14811 (save-excursion (org-todo tg)))
14812 (if exit-after-next (setq exit-after-next 'now)))
14813 ((setq e (rassoc c ntable) tg (car e))
14814 (if (member tg current)
14815 (setq current (delete tg current))
14816 (loop for g in groups do
14817 (if (member tg g)
14818 (mapc (lambda (x)
14819 (setq current (delete x current)))
14820 g)))
14821 (push tg current))
14822 (if exit-after-next (setq exit-after-next 'now))))
14824 ;; Create a sorted list
14825 (setq current
14826 (sort current
14827 (lambda (a b)
14828 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14829 (if (eq exit-after-next 'now) (throw 'exit t))
14830 (goto-char (point-min))
14831 (beginning-of-line 2)
14832 (delete-region (point) (point-at-eol))
14833 (org-fast-tag-insert "Current" current c-face)
14834 (org-set-current-tags-overlay current ov-prefix)
14835 (while (re-search-forward
14836 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14837 (setq tg (match-string 1))
14838 (add-text-properties
14839 (match-beginning 1) (match-end 1)
14840 (list 'face
14841 (cond
14842 ((member tg current) c-face)
14843 ((member tg inherited) i-face)
14844 (t (get-text-property (match-beginning 1) 'face))))))
14845 (goto-char (point-min)))))
14846 (org-detach-overlay org-tags-overlay)
14847 (if rtn
14848 (mapconcat 'identity current ":")
14849 nil))))
14851 (defun org-get-tags-string ()
14852 "Get the TAGS string in the current headline."
14853 (unless (org-at-heading-p t)
14854 (user-error "Not on a heading"))
14855 (save-excursion
14856 (beginning-of-line 1)
14857 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14858 (org-match-string-no-properties 1)
14859 "")))
14861 (defun org-get-tags ()
14862 "Get the list of tags specified in the current headline."
14863 (org-split-string (org-get-tags-string) ":"))
14865 (defun org-get-buffer-tags ()
14866 "Get a table of all tags used in the buffer, for completion."
14867 (let (tags)
14868 (save-excursion
14869 (goto-char (point-min))
14870 (while (re-search-forward
14871 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14872 (when (equal (char-after (point-at-bol 0)) ?*)
14873 (mapc (lambda (x) (add-to-list 'tags x))
14874 (org-split-string (org-match-string-no-properties 1) ":")))))
14875 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14876 (mapcar 'list tags)))
14878 ;;;; The mapping API
14880 (defun org-map-entries (func &optional match scope &rest skip)
14881 "Call FUNC at each headline selected by MATCH in SCOPE.
14883 FUNC is a function or a lisp form. The function will be called without
14884 arguments, with the cursor positioned at the beginning of the headline.
14885 The return values of all calls to the function will be collected and
14886 returned as a list.
14888 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14889 does not need to preserve point. After evaluation, the cursor will be
14890 moved to the end of the line (presumably of the headline of the
14891 processed entry) and search continues from there. Under some
14892 circumstances, this may not produce the wanted results. For example,
14893 if you have removed (e.g. archived) the current (sub)tree it could
14894 mean that the next entry will be skipped entirely. In such cases, you
14895 can specify the position from where search should continue by making
14896 FUNC set the variable `org-map-continue-from' to the desired buffer
14897 position.
14899 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14900 Only headlines that are matched by this query will be considered during
14901 the iteration. When MATCH is nil or t, all headlines will be
14902 visited by the iteration.
14904 SCOPE determines the scope of this command. It can be any of:
14906 nil The current buffer, respecting the restriction if any
14907 tree The subtree started with the entry at point
14908 region The entries within the active region, if any
14909 region-start-level
14910 The entries within the active region, but only those at
14911 the same level than the first one.
14912 file The current buffer, without restriction
14913 file-with-archives
14914 The current buffer, and any archives associated with it
14915 agenda All agenda files
14916 agenda-with-archives
14917 All agenda files with any archive files associated with them
14918 \(file1 file2 ...)
14919 If this is a list, all files in the list will be scanned
14921 The remaining args are treated as settings for the skipping facilities of
14922 the scanner. The following items can be given here:
14924 archive skip trees with the archive tag
14925 comment skip trees with the COMMENT keyword
14926 function or Emacs Lisp form:
14927 will be used as value for `org-agenda-skip-function', so
14928 whenever the function returns a position, FUNC will not be
14929 called for that entry and search will continue from the
14930 position returned
14932 If your function needs to retrieve the tags including inherited tags
14933 at the *current* entry, you can use the value of the variable
14934 `org-scanner-tags' which will be much faster than getting the value
14935 with `org-get-tags-at'. If your function gets properties with
14936 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14937 to t around the call to `org-entry-properties' to get the same speedup.
14938 Note that if your function moves around to retrieve tags and properties at
14939 a *different* entry, you cannot use these techniques."
14940 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14941 (not (org-region-active-p)))
14942 (let* ((org-agenda-archives-mode nil) ; just to make sure
14943 (org-agenda-skip-archived-trees (memq 'archive skip))
14944 (org-agenda-skip-comment-trees (memq 'comment skip))
14945 (org-agenda-skip-function
14946 (car (org-delete-all '(comment archive) skip)))
14947 (org-tags-match-list-sublevels t)
14948 (start-level (eq scope 'region-start-level))
14949 matcher file res
14950 org-todo-keywords-for-agenda
14951 org-done-keywords-for-agenda
14952 org-todo-keyword-alist-for-agenda
14953 org-drawers-for-agenda
14954 org-tag-alist-for-agenda
14955 todo-only)
14957 (cond
14958 ((eq match t) (setq matcher t))
14959 ((eq match nil) (setq matcher t))
14960 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14962 (save-window-excursion
14963 (save-restriction
14964 (cond ((eq scope 'tree)
14965 (org-back-to-heading t)
14966 (org-narrow-to-subtree)
14967 (setq scope nil))
14968 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14969 (org-region-active-p))
14970 ;; If needed, set start-level to a string like "2"
14971 (when start-level
14972 (save-excursion
14973 (goto-char (region-beginning))
14974 (unless (org-at-heading-p) (outline-next-heading))
14975 (setq start-level (org-current-level))))
14976 (narrow-to-region (region-beginning)
14977 (save-excursion
14978 (goto-char (region-end))
14979 (unless (and (bolp) (org-at-heading-p))
14980 (outline-next-heading))
14981 (point)))
14982 (setq scope nil)))
14984 (if (not scope)
14985 (progn
14986 (org-agenda-prepare-buffers
14987 (list (buffer-file-name (current-buffer))))
14988 (setq res (org-scan-tags func matcher todo-only start-level)))
14989 ;; Get the right scope
14990 (cond
14991 ((and scope (listp scope) (symbolp (car scope)))
14992 (setq scope (eval scope)))
14993 ((eq scope 'agenda)
14994 (setq scope (org-agenda-files t)))
14995 ((eq scope 'agenda-with-archives)
14996 (setq scope (org-agenda-files t))
14997 (setq scope (org-add-archive-files scope)))
14998 ((eq scope 'file)
14999 (setq scope (list (buffer-file-name))))
15000 ((eq scope 'file-with-archives)
15001 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15002 (org-agenda-prepare-buffers scope)
15003 (while (setq file (pop scope))
15004 (with-current-buffer (org-find-base-buffer-visiting file)
15005 (save-excursion
15006 (save-restriction
15007 (widen)
15008 (goto-char (point-min))
15009 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
15010 res)))
15012 ;;;; Properties
15014 ;;; Setting and retrieving properties
15016 (defconst org-special-properties
15017 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
15018 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
15019 "The special properties valid in Org-mode.
15021 These are properties that are not defined in the property drawer,
15022 but in some other way.")
15024 (defconst org-default-properties
15025 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15026 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15027 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15028 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15029 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
15030 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15031 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15032 "Some properties that are used by Org-mode for various purposes.
15033 Being in this list makes sure that they are offered for completion.")
15035 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
15036 "Regular expression matching the first line of a property drawer.")
15038 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
15039 "Regular expression matching the last line of a property drawer.")
15041 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
15042 "Regular expression matching the first line of a property drawer.")
15044 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
15045 "Regular expression matching the first line of a property drawer.")
15047 (defconst org-property-drawer-re
15048 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
15049 org-property-end-re "\\)\n?")
15050 "Matches an entire property drawer.")
15052 (defconst org-clock-drawer-re
15053 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
15054 org-property-end-re "\\)\n?")
15055 "Matches an entire clock drawer.")
15057 (defun org-property-action ()
15058 "Do an action on properties."
15059 (interactive)
15060 (let (c)
15061 (org-at-property-p)
15062 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15063 (setq c (read-char-exclusive))
15064 (cond
15065 ((equal c ?s)
15066 (call-interactively 'org-set-property))
15067 ((equal c ?d)
15068 (call-interactively 'org-delete-property))
15069 ((equal c ?D)
15070 (call-interactively 'org-delete-property-globally))
15071 ((equal c ?c)
15072 (call-interactively 'org-compute-property-at-point))
15073 (t (user-error "No such property action %c" c)))))
15075 (defun org-inc-effort ()
15076 "Increment the value of the effort property in the current entry."
15077 (interactive)
15078 (org-set-effort nil t))
15080 (defvar org-clock-effort) ;; Defined in org-clock.el
15081 (defvar org-clock-current-task) ;; Defined in org-clock.el
15082 (defun org-set-effort (&optional value increment)
15083 "Set the effort property of the current entry.
15084 With numerical prefix arg, use the nth allowed value, 0 stands for the
15085 10th allowed value.
15087 When INCREMENT is non-nil, set the property to the next allowed value."
15088 (interactive "P")
15089 (if (equal value 0) (setq value 10))
15090 (let* ((completion-ignore-case t)
15091 (prop org-effort-property)
15092 (cur (org-entry-get nil prop))
15093 (allowed (org-property-get-allowed-values nil prop 'table))
15094 (existing (mapcar 'list (org-property-values prop)))
15095 (heading (nth 4 (org-heading-components)))
15097 (val (cond
15098 ((stringp value) value)
15099 ((and allowed (integerp value))
15100 (or (car (nth (1- value) allowed))
15101 (car (org-last allowed))))
15102 ((and allowed increment)
15103 (or (caadr (member (list cur) allowed))
15104 (user-error "Allowed effort values are not set")))
15105 (allowed
15106 (message "Select 1-9,0, [RET%s]: %s"
15107 (if cur (concat "=" cur) "")
15108 (mapconcat 'car allowed " "))
15109 (setq rpl (read-char-exclusive))
15110 (if (equal rpl ?\r)
15112 (setq rpl (- rpl ?0))
15113 (if (equal rpl 0) (setq rpl 10))
15114 (if (and (> rpl 0) (<= rpl (length allowed)))
15115 (car (nth (1- rpl) allowed))
15116 (org-completing-read "Effort: " allowed nil))))
15118 (let (org-completion-use-ido org-completion-use-iswitchb)
15119 (org-completing-read
15120 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15121 (concat "[" cur "]") "")
15122 ": ")
15123 existing nil nil "" nil cur))))))
15124 (unless (equal (org-entry-get nil prop) val)
15125 (org-entry-put nil prop val))
15126 (save-excursion
15127 (org-back-to-heading t)
15128 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
15129 (when (string= heading org-clock-current-task)
15130 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
15131 (org-clock-update-mode-line))
15132 (message "%s is now %s" prop val)))
15134 (defun org-at-property-p ()
15135 "Is cursor inside a property drawer?"
15136 (save-excursion
15137 (when (equal 'node-property (car (org-element-at-point)))
15138 (beginning-of-line 1)
15139 (looking-at org-property-re))))
15141 (defun org-get-property-block (&optional beg end force)
15142 "Return the (beg . end) range of the body of the property drawer.
15143 BEG and END are the beginning and end of the current subtree, or of
15144 the part before the first headline. If they are not given, they will
15145 be found. If the drawer does not exist and FORCE is non-nil, create
15146 the drawer."
15147 (catch 'exit
15148 (save-excursion
15149 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15150 (progn (org-back-to-heading t) (point))))
15151 (end (or end (and (not (outline-next-heading)) (point-max))
15152 (point))))
15153 (goto-char beg)
15154 (if (re-search-forward org-property-start-re end t)
15155 (setq beg (1+ (match-end 0)))
15156 (if force
15157 (save-excursion
15158 (org-insert-property-drawer)
15159 (setq end (progn (outline-next-heading) (point))))
15160 (throw 'exit nil))
15161 (goto-char beg)
15162 (if (re-search-forward org-property-start-re end t)
15163 (setq beg (1+ (match-end 0)))))
15164 (if (re-search-forward org-property-end-re end t)
15165 (setq end (match-beginning 0))
15166 (or force (throw 'exit nil))
15167 (goto-char beg)
15168 (setq end beg)
15169 (org-indent-line)
15170 (insert ":END:\n"))
15171 (cons beg end)))))
15173 (defun org-entry-properties (&optional pom which specific)
15174 "Get all properties of the entry at point-or-marker POM.
15175 This includes the TODO keyword, the tags, time strings for deadline,
15176 scheduled, and clocking, and any additional properties defined in the
15177 entry. The return value is an alist, keys may occur multiple times
15178 if the property key was used several times.
15179 POM may also be nil, in which case the current entry is used.
15180 If WHICH is nil or `all', get all properties. If WHICH is
15181 `special' or `standard', only get that subclass. If WHICH
15182 is a string only get exactly this property. SPECIFIC can be a string, the
15183 specific property we are interested in. Specifying it can speed
15184 things up because then unnecessary parsing is avoided."
15185 (setq which (or which 'all))
15186 (org-with-wide-buffer
15187 (org-with-point-at pom
15188 (let ((clockstr (substring org-clock-string 0 -1))
15189 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15190 (case-fold-search nil)
15191 beg end range props sum-props key key1 value string clocksum clocksumt)
15192 (when (and (derived-mode-p 'org-mode)
15193 (ignore-errors (org-back-to-heading t)))
15194 (setq beg (point))
15195 (setq sum-props (get-text-property (point) 'org-summaries))
15196 (setq clocksum (get-text-property (point) :org-clock-minutes)
15197 clocksumt (get-text-property (point) :org-clock-minutes-today))
15198 (outline-next-heading)
15199 (setq end (point))
15200 (when (memq which '(all special))
15201 ;; Get the special properties, like TODO and tags
15202 (goto-char beg)
15203 (when (and (or (not specific) (string= specific "TODO"))
15204 (looking-at org-todo-line-regexp) (match-end 2))
15205 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15206 (when (and (or (not specific) (string= specific "PRIORITY"))
15207 (looking-at org-priority-regexp))
15208 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15209 (when (or (not specific) (string= specific "FILE"))
15210 (push (cons "FILE" buffer-file-name) props))
15211 (when (and (or (not specific) (string= specific "TAGS"))
15212 (setq value (org-get-tags-string))
15213 (string-match "\\S-" value))
15214 (push (cons "TAGS" value) props))
15215 (when (and (or (not specific) (string= specific "ALLTAGS"))
15216 (setq value (org-get-tags-at)))
15217 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15218 ":"))
15219 props))
15220 (when (or (not specific) (string= specific "BLOCKED"))
15221 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15222 (when (or (not specific)
15223 (member specific
15224 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15225 "TIMESTAMP" "TIMESTAMP_IA")))
15226 (catch 'match
15227 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15228 (setq key (if (match-end 1)
15229 (substring (org-match-string-no-properties 1)
15230 0 -1))
15231 string (if (equal key clockstr)
15232 (org-trim
15233 (buffer-substring-no-properties
15234 (match-beginning 3) (goto-char
15235 (point-at-eol))))
15236 (substring (org-match-string-no-properties 3)
15237 1 -1)))
15238 ;; Get the correct property name from the key. This is
15239 ;; necessary if the user has configured time keywords.
15240 (setq key1 (concat key ":"))
15241 (cond
15242 ((not key)
15243 (setq key
15244 (if (= (char-after (match-beginning 3)) ?\[)
15245 "TIMESTAMP_IA" "TIMESTAMP")))
15246 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15247 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15248 ((equal key1 org-closed-string) (setq key "CLOSED"))
15249 ((equal key1 org-clock-string) (setq key "CLOCK")))
15250 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15251 (progn
15252 (push (cons key string) props)
15253 ;; no need to search further if match is found
15254 (throw 'match t))
15255 (when (or (equal key "CLOCK") (not (assoc key props)))
15256 (push (cons key string) props)))))))
15258 (when (memq which '(all standard))
15259 ;; Get the standard properties, like :PROP: ...
15260 (setq range (org-get-property-block beg end))
15261 (when range
15262 (goto-char (car range))
15263 (while (re-search-forward org-property-re
15264 (cdr range) t)
15265 (setq key (org-match-string-no-properties 2)
15266 value (org-trim (or (org-match-string-no-properties 3) "")))
15267 (unless (member key excluded)
15268 (push (cons key (or value "")) props)))))
15269 (if clocksum
15270 (push (cons "CLOCKSUM"
15271 (org-columns-number-to-string (/ (float clocksum) 60.)
15272 'add_times))
15273 props))
15274 (if clocksumt
15275 (push (cons "CLOCKSUM_T"
15276 (org-columns-number-to-string (/ (float clocksumt) 60.)
15277 'add_times))
15278 props))
15279 (unless (assoc "CATEGORY" props)
15280 (push (cons "CATEGORY" (org-get-category)) props))
15281 (append sum-props (nreverse props)))))))
15283 (defun org-entry-get (pom property &optional inherit literal-nil)
15284 "Get value of PROPERTY for entry or content at point-or-marker POM.
15285 If INHERIT is non-nil and the entry does not have the property,
15286 then also check higher levels of the hierarchy.
15287 If INHERIT is the symbol `selective', use inheritance only if the setting
15288 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15289 If the property is present but empty, the return value is the empty string.
15290 If the property is not present at all, nil is returned.
15292 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15293 do not interpret it as the list atom nil. This is used for inheritance
15294 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15295 (org-with-point-at pom
15296 (if (and inherit (if (eq inherit 'selective)
15297 (org-property-inherit-p property)
15299 (org-entry-get-with-inheritance property literal-nil)
15300 (if (member property org-special-properties)
15301 ;; We need a special property. Use `org-entry-properties'
15302 ;; to retrieve it, but specify the wanted property
15303 (cdr (assoc property (org-entry-properties nil 'special property)))
15304 (org-with-wide-buffer
15305 (let ((range (org-get-property-block)))
15306 (when (and range (not (eq (car range) (cdr range))))
15307 (let* ((props
15308 (list (or (assoc property org-file-properties)
15309 (assoc property org-global-properties)
15310 (assoc property org-global-properties-fixed))))
15311 (ap (lambda (key)
15312 (when (re-search-forward
15313 (org-re-property key) (cdr range) t)
15314 (setq props
15315 (org-update-property-plist
15317 (if (match-end 3)
15318 (org-match-string-no-properties 3) "")
15319 props)))))
15320 val)
15321 (goto-char (car range))
15322 (funcall ap property)
15323 (goto-char (car range))
15324 (while (funcall ap (concat property "+")))
15325 (setq val (cdr (assoc property props)))
15326 (when val (if literal-nil val (org-not-nil val)))))))))))
15328 (defun org-property-or-variable-value (var &optional inherit)
15329 "Check if there is a property fixing the value of VAR.
15330 If yes, return this value. If not, return the current value of the variable."
15331 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15332 (if (and prop (stringp prop) (string-match "\\S-" prop))
15333 (read prop)
15334 (symbol-value var))))
15336 (defun org-entry-delete (pom property &optional delete-empty-drawer)
15337 "Delete the property PROPERTY from entry at point-or-marker POM.
15338 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15339 an empty drawer to delete."
15340 (org-with-point-at pom
15341 (if (member property org-special-properties)
15342 nil ; cannot delete these properties.
15343 (let ((range (org-get-property-block)))
15344 (if (and range
15345 (goto-char (car range))
15346 (re-search-forward
15347 (org-re-property property)
15348 (cdr range) t))
15349 (progn
15350 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15351 (and delete-empty-drawer
15352 (org-remove-empty-drawer-at
15353 delete-empty-drawer (car range)))
15355 nil)))))
15357 ;; Multi-values properties are properties that contain multiple values
15358 ;; These values are assumed to be single words, separated by whitespace.
15359 (defun org-entry-add-to-multivalued-property (pom property value)
15360 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15361 (let* ((old (org-entry-get pom property))
15362 (values (and old (org-split-string old "[ \t]"))))
15363 (setq value (org-entry-protect-space value))
15364 (unless (member value values)
15365 (setq values (append values (list value)))
15366 (org-entry-put pom property
15367 (mapconcat 'identity values " ")))))
15369 (defun org-entry-remove-from-multivalued-property (pom property value)
15370 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15371 (let* ((old (org-entry-get pom property))
15372 (values (and old (org-split-string old "[ \t]"))))
15373 (setq value (org-entry-protect-space value))
15374 (when (member value values)
15375 (setq values (delete value values))
15376 (org-entry-put pom property
15377 (mapconcat 'identity values " ")))))
15379 (defun org-entry-member-in-multivalued-property (pom property value)
15380 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15381 (let* ((old (org-entry-get pom property))
15382 (values (and old (org-split-string old "[ \t]"))))
15383 (setq value (org-entry-protect-space value))
15384 (member value values)))
15386 (defun org-entry-get-multivalued-property (pom property)
15387 "Return a list of values in a multivalued property."
15388 (let* ((value (org-entry-get pom property))
15389 (values (and value (org-split-string value "[ \t]"))))
15390 (mapcar 'org-entry-restore-space values)))
15392 (defun org-entry-put-multivalued-property (pom property &rest values)
15393 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15394 VALUES should be a list of strings. Spaces will be protected."
15395 (org-entry-put pom property
15396 (mapconcat 'org-entry-protect-space values " "))
15397 (let* ((value (org-entry-get pom property))
15398 (values (and value (org-split-string value "[ \t]"))))
15399 (mapcar 'org-entry-restore-space values)))
15401 (defun org-entry-protect-space (s)
15402 "Protect spaces and newline in string S."
15403 (while (string-match " " s)
15404 (setq s (replace-match "%20" t t s)))
15405 (while (string-match "\n" s)
15406 (setq s (replace-match "%0A" t t s)))
15409 (defun org-entry-restore-space (s)
15410 "Restore spaces and newline in string S."
15411 (while (string-match "%20" s)
15412 (setq s (replace-match " " t t s)))
15413 (while (string-match "%0A" s)
15414 (setq s (replace-match "\n" t t s)))
15417 (defvar org-entry-property-inherited-from (make-marker)
15418 "Marker pointing to the entry from where a property was inherited.
15419 Each call to `org-entry-get-with-inheritance' will set this marker to the
15420 location of the entry where the inheritance search matched. If there was
15421 no match, the marker will point nowhere.
15422 Note that also `org-entry-get' calls this function, if the INHERIT flag
15423 is set.")
15425 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15426 "Get PROPERTY of entry or content at point, search higher levels if needed.
15427 The search will stop at the first ancestor which has the property defined.
15428 If the value found is \"nil\", return nil to show that the property
15429 should be considered as undefined (this is the meaning of nil here).
15430 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15431 (move-marker org-entry-property-inherited-from nil)
15432 (let (tmp)
15433 (save-excursion
15434 (save-restriction
15435 (widen)
15436 (catch 'ex
15437 (while t
15438 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
15439 (or (ignore-errors (org-back-to-heading t))
15440 (goto-char (point-min)))
15441 (move-marker org-entry-property-inherited-from (point))
15442 (throw 'ex tmp))
15443 (or (ignore-errors (org-up-heading-safe))
15444 (throw 'ex nil))))))
15445 (setq tmp (or tmp
15446 (cdr (assoc property org-file-properties))
15447 (cdr (assoc property org-global-properties))
15448 (cdr (assoc property org-global-properties-fixed))))
15449 (if literal-nil tmp (org-not-nil tmp))))
15451 (defvar org-property-changed-functions nil
15452 "Hook called when the value of a property has changed.
15453 Each hook function should accept two arguments, the name of the property
15454 and the new value.")
15456 (defun org-entry-put (pom property value)
15457 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15458 (org-with-point-at pom
15459 (org-back-to-heading t)
15460 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15461 range)
15462 (cond
15463 ((equal property "TODO")
15464 (when (and (stringp value) (string-match "\\S-" value)
15465 (not (member value org-todo-keywords-1)))
15466 (user-error "\"%s\" is not a valid TODO state" value))
15467 (if (or (not value)
15468 (not (string-match "\\S-" value)))
15469 (setq value 'none))
15470 (org-todo value)
15471 (org-set-tags nil 'align))
15472 ((equal property "PRIORITY")
15473 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15474 (string-to-char value) ?\ ))
15475 (org-set-tags nil 'align))
15476 ((equal property "CLOCKSUM")
15477 (if (not (re-search-forward
15478 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15479 (error "Cannot find a clock log")
15480 (goto-char (- (match-end 1) 2))
15481 (cond
15482 ((eq value 'earlier) (org-timestamp-down))
15483 ((eq value 'later) (org-timestamp-up)))
15484 (org-clock-sum-current-item)))
15485 ((equal property "SCHEDULED")
15486 (if (re-search-forward org-scheduled-time-regexp end t)
15487 (cond
15488 ((eq value 'earlier) (org-timestamp-change -1 'day))
15489 ((eq value 'later) (org-timestamp-change 1 'day))
15490 (t (call-interactively 'org-schedule)))
15491 (call-interactively 'org-schedule)))
15492 ((equal property "DEADLINE")
15493 (if (re-search-forward org-deadline-time-regexp end t)
15494 (cond
15495 ((eq value 'earlier) (org-timestamp-change -1 'day))
15496 ((eq value 'later) (org-timestamp-change 1 'day))
15497 (t (call-interactively 'org-deadline)))
15498 (call-interactively 'org-deadline)))
15499 ((member property org-special-properties)
15500 (error "The %s property can not yet be set with `org-entry-put'"
15501 property))
15502 (t ; a non-special property
15503 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15504 (setq range (org-get-property-block beg end 'force))
15505 (goto-char (car range))
15506 (if (re-search-forward
15507 (org-re-property property) (cdr range) t)
15508 (progn
15509 (delete-region (match-beginning 0) (match-end 0))
15510 (goto-char (match-beginning 0)))
15511 (goto-char (cdr range))
15512 (insert "\n")
15513 (backward-char 1)
15514 (org-indent-line))
15515 (insert ":" property ":")
15516 (and value (insert " " value))
15517 (org-indent-line)))))
15518 (run-hook-with-args 'org-property-changed-functions property value)))
15520 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15521 "Get all property keys in the current buffer.
15522 With INCLUDE-SPECIALS, also list the special properties that reflect things
15523 like tags and TODO state.
15524 With INCLUDE-DEFAULTS, also include properties that has special meaning
15525 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15526 and others.
15527 With INCLUDE-COLUMNS, also include property names given in COLUMN
15528 formats in the current buffer."
15529 (let (rtn range cfmt s p)
15530 (save-excursion
15531 (save-restriction
15532 (widen)
15533 (goto-char (point-min))
15534 (while (re-search-forward org-property-start-re nil t)
15535 (setq range (org-get-property-block))
15536 (goto-char (car range))
15537 (while (re-search-forward org-property-re
15538 (cdr range) t)
15539 (add-to-list 'rtn (org-match-string-no-properties 2)))
15540 (outline-next-heading))))
15542 (when include-specials
15543 (setq rtn (append org-special-properties rtn)))
15545 (when include-defaults
15546 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15547 (add-to-list 'rtn org-effort-property))
15549 (when include-columns
15550 (save-excursion
15551 (save-restriction
15552 (widen)
15553 (goto-char (point-min))
15554 (while (re-search-forward
15555 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15556 nil t)
15557 (setq cfmt (match-string 2) s 0)
15558 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15559 cfmt s)
15560 (setq s (match-end 0)
15561 p (match-string 1 cfmt))
15562 (unless (or (equal p "ITEM")
15563 (member p org-special-properties))
15564 (add-to-list 'rtn (match-string 1 cfmt))))))))
15566 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15568 (defun org-property-values (key)
15569 "Return a list of all values of property KEY in the current buffer."
15570 (save-excursion
15571 (save-restriction
15572 (widen)
15573 (goto-char (point-min))
15574 (let ((re (org-re-property key))
15575 values)
15576 (while (re-search-forward re nil t)
15577 (add-to-list 'values (org-trim (match-string 3))))
15578 (delete "" values)))))
15580 (defun org-insert-property-drawer ()
15581 "Insert a property drawer into the current entry."
15582 (org-back-to-heading t)
15583 (looking-at org-outline-regexp)
15584 (let ((indent (if org-adapt-indentation
15585 (- (match-end 0) (match-beginning 0))
15587 (beg (point))
15588 (re (concat "^[ \t]*" org-keyword-time-regexp))
15589 end hiddenp)
15590 (outline-next-heading)
15591 (setq end (point))
15592 (goto-char beg)
15593 (while (re-search-forward re end t))
15594 (setq hiddenp (outline-invisible-p))
15595 (end-of-line 1)
15596 (and (equal (char-after) ?\n) (forward-char 1))
15597 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15598 (if (member (match-string 1) '("CLOCK:" ":END:"))
15599 ;; just skip this line
15600 (beginning-of-line 2)
15601 ;; Drawer start, find the end
15602 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15603 (beginning-of-line 1)))
15604 (org-skip-over-state-notes)
15605 (skip-chars-backward " \t\n\r")
15606 (if (and (eq (char-before) ?*) (not (eq (char-after) ?\n)))
15607 (forward-char 1))
15608 (goto-char (point-at-eol))
15609 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15610 (beginning-of-line 0)
15611 (org-indent-to-column indent)
15612 (beginning-of-line 2)
15613 (org-indent-to-column indent)
15614 (beginning-of-line 0)
15615 (if hiddenp
15616 (save-excursion
15617 (org-back-to-heading t)
15618 (hide-entry))
15619 (org-flag-drawer t))))
15621 (defun org-insert-drawer (&optional arg drawer)
15622 "Insert a drawer at point.
15624 Optional argument DRAWER, when non-nil, is a string representing
15625 drawer's name. Otherwise, the user is prompted for a name.
15627 If a region is active, insert the drawer around that region
15628 instead.
15630 Point is left between drawer's boundaries."
15631 (interactive "P")
15632 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15633 "LOGBOOK"))
15634 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15635 ;; internally by Org. They are meant to be inserted
15636 ;; automatically.
15637 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15638 ;; Remove system drawers from list. Note: For some reason,
15639 ;; `org-completing-read' ignores the predicate while
15640 ;; `completing-read' handles it fine.
15641 (drawer (if arg "PROPERTIES"
15642 (or drawer
15643 (completing-read
15644 "Drawer: " org-drawers
15645 (lambda (d) (not (member d system-drawers))))))))
15646 (cond
15647 ;; With C-u, fall back on `org-insert-property-drawer'
15648 (arg (org-insert-property-drawer))
15649 ;; With an active region, insert a drawer at point.
15650 ((not (org-region-active-p))
15651 (progn
15652 (unless (bolp) (insert "\n"))
15653 (insert (format ":%s:\n\n:END:\n" drawer))
15654 (forward-line -2)))
15655 ;; Otherwise, insert the drawer at point
15657 (let ((rbeg (region-beginning))
15658 (rend (copy-marker (region-end))))
15659 (unwind-protect
15660 (progn
15661 (goto-char rbeg)
15662 (beginning-of-line)
15663 (when (save-excursion
15664 (re-search-forward org-outline-regexp-bol rend t))
15665 (user-error "Drawers cannot contain headlines"))
15666 ;; Position point at the beginning of the first
15667 ;; non-blank line in region. Insert drawer's opening
15668 ;; there, then indent it.
15669 (org-skip-whitespace)
15670 (beginning-of-line)
15671 (insert ":" drawer ":\n")
15672 (forward-line -1)
15673 (indent-for-tab-command)
15674 ;; Move point to the beginning of the first blank line
15675 ;; after the last non-blank line in region. Insert
15676 ;; drawer's closing, then indent it.
15677 (goto-char rend)
15678 (skip-chars-backward " \r\t\n")
15679 (insert "\n:END:")
15680 (deactivate-mark t)
15681 (indent-for-tab-command)
15682 (unless (eolp) (insert "\n")))
15683 ;; Clear marker, whatever the outcome of insertion is.
15684 (set-marker rend nil)))))))
15686 (defvar org-property-set-functions-alist nil
15687 "Property set function alist.
15688 Each entry should have the following format:
15690 (PROPERTY . READ-FUNCTION)
15692 The read function will be called with the same argument as
15693 `org-completing-read'.")
15695 (defun org-set-property-function (property)
15696 "Get the function that should be used to set PROPERTY.
15697 This is computed according to `org-property-set-functions-alist'."
15698 (or (cdr (assoc property org-property-set-functions-alist))
15699 'org-completing-read))
15701 (defun org-read-property-value (property)
15702 "Read PROPERTY value from user."
15703 (let* ((completion-ignore-case t)
15704 (allowed (org-property-get-allowed-values nil property 'table))
15705 (cur (org-entry-get nil property))
15706 (prompt (concat property " value"
15707 (if (and cur (string-match "\\S-" cur))
15708 (concat " [" cur "]") "") ": "))
15709 (set-function (org-set-property-function property))
15710 (val (if allowed
15711 (funcall set-function prompt allowed nil
15712 (not (get-text-property 0 'org-unrestricted
15713 (caar allowed))))
15714 (let (org-completion-use-ido org-completion-use-iswitchb)
15715 (funcall set-function prompt
15716 (mapcar 'list (org-property-values property))
15717 nil nil "" nil cur)))))
15718 (if (equal val "")
15720 val)))
15722 (defvar org-last-set-property nil)
15723 (defvar org-last-set-property-value nil)
15724 (defun org-read-property-name ()
15725 "Read a property name."
15726 (let* ((completion-ignore-case t)
15727 (keys (org-buffer-property-keys nil t t))
15728 (default-prop (or (save-excursion
15729 (save-match-data
15730 (beginning-of-line)
15731 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15732 (null (string= (match-string 1) "END"))
15733 (match-string 1))))
15734 org-last-set-property))
15735 (property (org-icompleting-read
15736 (concat "Property"
15737 (if default-prop (concat " [" default-prop "]") "")
15738 ": ")
15739 (mapcar 'list keys)
15740 nil nil nil nil
15741 default-prop)))
15742 (if (member property keys)
15743 property
15744 (or (cdr (assoc (downcase property)
15745 (mapcar (lambda (x) (cons (downcase x) x))
15746 keys)))
15747 property))))
15749 (defun org-set-property-and-value (use-last)
15750 "Allow to set [PROPERTY]: [value] direction from prompt.
15751 When use-default, don't even ask, just use the last
15752 \"[PROPERTY]: [value]\" string from the history."
15753 (interactive "P")
15754 (let* ((completion-ignore-case t)
15755 (pv (or (and use-last org-last-set-property-value)
15756 (org-completing-read
15757 "Enter a \"[Property]: [value]\" pair: "
15758 nil nil nil nil nil
15759 org-last-set-property-value)))
15760 prop val)
15761 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15762 (setq prop (match-string 1 pv)
15763 val (match-string 2 pv))
15764 (org-set-property prop val))))
15766 (defun org-set-property (property value)
15767 "In the current entry, set PROPERTY to VALUE.
15768 When called interactively, this will prompt for a property name, offering
15769 completion on existing and default properties. And then it will prompt
15770 for a value, offering completion either on allowed values (via an inherited
15771 xxx_ALL property) or on existing values in other instances of this property
15772 in the current file."
15773 (interactive (list nil nil))
15774 (let* ((property (or property (org-read-property-name)))
15775 (value (or value (org-read-property-value property)))
15776 (fn (cdr (assoc property org-properties-postprocess-alist))))
15777 (setq org-last-set-property property)
15778 (setq org-last-set-property-value (concat property ": " value))
15779 ;; Possibly postprocess the inserted value:
15780 (when fn (setq value (funcall fn value)))
15781 (unless (equal (org-entry-get nil property) value)
15782 (org-entry-put nil property value))))
15784 (defun org-delete-property (property &optional delete-empty-drawer)
15785 "In the current entry, delete PROPERTY.
15786 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15787 an empty drawer to delete."
15788 (interactive
15789 (let* ((completion-ignore-case t)
15790 (prop (org-icompleting-read "Property: "
15791 (org-entry-properties nil 'standard))))
15792 (list prop)))
15793 (message "Property %s %s" property
15794 (if (org-entry-delete nil property delete-empty-drawer)
15795 "deleted"
15796 "was not present in the entry")))
15798 (defun org-delete-property-globally (property)
15799 "Remove PROPERTY globally, from all entries."
15800 (interactive
15801 (let* ((completion-ignore-case t)
15802 (prop (org-icompleting-read
15803 "Globally remove property: "
15804 (mapcar 'list (org-buffer-property-keys)))))
15805 (list prop)))
15806 (save-excursion
15807 (save-restriction
15808 (widen)
15809 (goto-char (point-min))
15810 (let ((cnt 0))
15811 (while (re-search-forward
15812 (org-re-property property)
15813 nil t)
15814 (setq cnt (1+ cnt))
15815 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15816 (message "Property \"%s\" removed from %d entries" property cnt)))))
15818 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15820 (defun org-compute-property-at-point ()
15821 "Compute the property at point.
15822 This looks for an enclosing column format, extracts the operator and
15823 then applies it to the property in the column format's scope."
15824 (interactive)
15825 (unless (org-at-property-p)
15826 (user-error "Not at a property"))
15827 (let ((prop (org-match-string-no-properties 2)))
15828 (org-columns-get-format-and-top-level)
15829 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15830 (user-error "No operator defined for property %s" prop))
15831 (org-columns-compute prop)))
15833 (defvar org-property-allowed-value-functions nil
15834 "Hook for functions supplying allowed values for a specific property.
15835 The functions must take a single argument, the name of the property, and
15836 return a flat list of allowed values. If \":ETC\" is one of
15837 the values, this means that these values are intended as defaults for
15838 completion, but that other values should be allowed too.
15839 The functions must return nil if they are not responsible for this
15840 property.")
15842 (defun org-property-get-allowed-values (pom property &optional table)
15843 "Get allowed values for the property PROPERTY.
15844 When TABLE is non-nil, return an alist that can directly be used for
15845 completion."
15846 (let (vals)
15847 (cond
15848 ((equal property "TODO")
15849 (setq vals (org-with-point-at pom
15850 (append org-todo-keywords-1 '("")))))
15851 ((equal property "PRIORITY")
15852 (let ((n org-lowest-priority))
15853 (while (>= n org-highest-priority)
15854 (push (char-to-string n) vals)
15855 (setq n (1- n)))))
15856 ((member property org-special-properties))
15857 ((setq vals (run-hook-with-args-until-success
15858 'org-property-allowed-value-functions property)))
15860 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15861 (when (and vals (string-match "\\S-" vals))
15862 (setq vals (car (read-from-string (concat "(" vals ")"))))
15863 (setq vals (mapcar (lambda (x)
15864 (cond ((stringp x) x)
15865 ((numberp x) (number-to-string x))
15866 ((symbolp x) (symbol-name x))
15867 (t "???")))
15868 vals)))))
15869 (when (member ":ETC" vals)
15870 (setq vals (remove ":ETC" vals))
15871 (org-add-props (car vals) '(org-unrestricted t)))
15872 (if table (mapcar 'list vals) vals)))
15874 (defun org-property-previous-allowed-value (&optional previous)
15875 "Switch to the next allowed value for this property."
15876 (interactive)
15877 (org-property-next-allowed-value t))
15879 (defun org-property-next-allowed-value (&optional previous)
15880 "Switch to the next allowed value for this property."
15881 (interactive)
15882 (unless (org-at-property-p)
15883 (user-error "Not at a property"))
15884 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15885 (key (match-string 2))
15886 (value (match-string 3))
15887 (allowed (or (org-property-get-allowed-values (point) key)
15888 (and (member value '("[ ]" "[-]" "[X]"))
15889 '("[ ]" "[X]"))))
15890 (heading (save-match-data (nth 4 (org-heading-components))))
15891 nval)
15892 (unless allowed
15893 (user-error "Allowed values for this property have not been defined"))
15894 (if previous (setq allowed (reverse allowed)))
15895 (if (member value allowed)
15896 (setq nval (car (cdr (member value allowed)))))
15897 (setq nval (or nval (car allowed)))
15898 (if (equal nval value)
15899 (user-error "Only one allowed value for this property"))
15900 (org-at-property-p)
15901 (replace-match (concat " :" key ": " nval) t t)
15902 (org-indent-line)
15903 (beginning-of-line 1)
15904 (skip-chars-forward " \t")
15905 (when (equal prop org-effort-property)
15906 (save-excursion
15907 (org-back-to-heading t)
15908 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
15909 (when (string= org-clock-current-task heading)
15910 (setq org-clock-effort nval)
15911 (org-clock-update-mode-line)))
15912 (run-hook-with-args 'org-property-changed-functions key nval)))
15914 (defun org-find-olp (path &optional this-buffer)
15915 "Return a marker pointing to the entry at outline path OLP.
15916 If anything goes wrong, throw an error.
15917 You can wrap this call to catch the error like this:
15919 (condition-case msg
15920 (org-mobile-locate-entry (match-string 4))
15921 (error (nth 1 msg)))
15923 The return value will then be either a string with the error message,
15924 or a marker if everything is OK.
15926 If THIS-BUFFER is set, the outline path does not contain a file,
15927 only headings."
15928 (let* ((file (if this-buffer buffer-file-name (pop path)))
15929 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15930 (level 1)
15931 (lmin 1)
15932 (lmax 1)
15933 limit re end found pos heading cnt flevel)
15934 (unless buffer (error "File not found :%s" file))
15935 (with-current-buffer buffer
15936 (save-excursion
15937 (save-restriction
15938 (widen)
15939 (setq limit (point-max))
15940 (goto-char (point-min))
15941 (while (setq heading (pop path))
15942 (setq re (format org-complex-heading-regexp-format
15943 (regexp-quote heading)))
15944 (setq cnt 0 pos (point))
15945 (while (re-search-forward re end t)
15946 (setq level (- (match-end 1) (match-beginning 1)))
15947 (if (and (>= level lmin) (<= level lmax))
15948 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15949 (when (= cnt 0) (error "Heading not found on level %d: %s"
15950 lmax heading))
15951 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15952 lmax heading))
15953 (goto-char found)
15954 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15955 (setq end (save-excursion (org-end-of-subtree t t))))
15956 (when (org-at-heading-p)
15957 (point-marker)))))))
15959 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15960 "Find node HEADING in BUFFER.
15961 Return a marker to the heading if it was found, or nil if not.
15962 If POS-ONLY is set, return just the position instead of a marker.
15964 The heading text must match exact, but it may have a TODO keyword,
15965 a priority cookie and tags in the standard locations."
15966 (with-current-buffer (or buffer (current-buffer))
15967 (save-excursion
15968 (save-restriction
15969 (widen)
15970 (goto-char (point-min))
15971 (let (case-fold-search)
15972 (if (re-search-forward
15973 (format org-complex-heading-regexp-format
15974 (regexp-quote heading)) nil t)
15975 (if pos-only
15976 (match-beginning 0)
15977 (move-marker (make-marker) (match-beginning 0)))))))))
15979 (defun org-find-exact-heading-in-directory (heading &optional dir)
15980 "Find Org node headline HEADING in all .org files in directory DIR.
15981 When the target headline is found, return a marker to this location."
15982 (let ((files (directory-files (or dir default-directory)
15983 nil "\\`[^.#].*\\.org\\'"))
15984 file visiting m buffer)
15985 (catch 'found
15986 (while (setq file (pop files))
15987 (message "trying %s" file)
15988 (setq visiting (org-find-base-buffer-visiting file))
15989 (setq buffer (or visiting (find-file-noselect file)))
15990 (setq m (org-find-exact-headline-in-buffer
15991 heading buffer))
15992 (when (and (not m) (not visiting)) (kill-buffer buffer))
15993 (and m (throw 'found m))))))
15995 (defun org-find-entry-with-id (ident)
15996 "Locate the entry that contains the ID property with exact value IDENT.
15997 IDENT can be a string, a symbol or a number, this function will search for
15998 the string representation of it.
15999 Return the position where this entry starts, or nil if there is no such entry."
16000 (interactive "sID: ")
16001 (let ((id (cond
16002 ((stringp ident) ident)
16003 ((symbol-name ident) (symbol-name ident))
16004 ((numberp ident) (number-to-string ident))
16005 (t (error "IDENT %s must be a string, symbol or number" ident))))
16006 (case-fold-search nil))
16007 (save-excursion
16008 (save-restriction
16009 (widen)
16010 (goto-char (point-min))
16011 (when (re-search-forward
16012 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16013 nil t)
16014 (org-back-to-heading t)
16015 (point))))))
16017 ;;;; Timestamps
16019 (defvar org-last-changed-timestamp nil)
16020 (defvar org-last-inserted-timestamp nil
16021 "The last time stamp inserted with `org-insert-time-stamp'.")
16022 (defvar org-ts-what) ; dynamically scoped parameter
16024 (defun org-time-stamp (arg &optional inactive)
16025 "Prompt for a date/time and insert a time stamp.
16026 If the user specifies a time like HH:MM or if this command is
16027 called with at least one prefix argument, the time stamp contains
16028 the date and the time. Otherwise, only the date is be included.
16030 All parts of a date not specified by the user is filled in from
16031 the current date/time. So if you just press return without
16032 typing anything, the time stamp will represent the current
16033 date/time.
16035 If there is already a timestamp at the cursor, it will be
16036 modified.
16038 With two universal prefix arguments, insert an active timestamp
16039 with the current time without prompting the user.
16041 When called from lisp, the timestamp is inactive if INACTIVE is
16042 non-nil."
16043 (interactive "P")
16044 (let* ((ts nil)
16045 (default-time
16046 ;; Default time is either today, or, when entering a range,
16047 ;; the range start.
16048 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16049 (save-excursion
16050 (re-search-backward
16051 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16052 (- (point) 20) t)))
16053 (apply 'encode-time (org-parse-time-string (match-string 1)))
16054 (current-time)))
16055 (default-input (and ts (org-get-compact-tod ts)))
16056 (repeater (save-excursion
16057 (save-match-data
16058 (beginning-of-line)
16059 (when (re-search-forward
16060 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16061 (save-excursion (progn (end-of-line) (point))) t)
16062 (match-string 0)))))
16063 org-time-was-given org-end-time-was-given time)
16064 (cond
16065 ((and (org-at-timestamp-p t)
16066 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16067 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16068 (insert "--")
16069 (setq time (let ((this-command this-command))
16070 (org-read-date arg 'totime nil nil
16071 default-time default-input inactive)))
16072 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16073 ((org-at-timestamp-p t)
16074 (setq time (let ((this-command this-command))
16075 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16076 (when (org-at-timestamp-p t) ; just to get the match data
16077 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16078 (replace-match "")
16079 (setq org-last-changed-timestamp
16080 (org-insert-time-stamp
16081 time (or org-time-was-given arg)
16082 inactive nil nil (list org-end-time-was-given)))
16083 (when repeater (goto-char (1- (point))) (insert " " repeater)
16084 (setq org-last-changed-timestamp
16085 (concat (substring org-last-inserted-timestamp 0 -1)
16086 " " repeater ">"))))
16087 (message "Timestamp updated"))
16088 ((equal arg '(16))
16089 (org-insert-time-stamp (current-time) t inactive))
16091 (setq time (let ((this-command this-command))
16092 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16093 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16094 nil nil (list org-end-time-was-given))))))
16096 ;; FIXME: can we use this for something else, like computing time differences?
16097 (defun org-get-compact-tod (s)
16098 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16099 (let* ((t1 (match-string 1 s))
16100 (h1 (string-to-number (match-string 2 s)))
16101 (m1 (string-to-number (match-string 3 s)))
16102 (t2 (and (match-end 4) (match-string 5 s)))
16103 (h2 (and t2 (string-to-number (match-string 6 s))))
16104 (m2 (and t2 (string-to-number (match-string 7 s))))
16105 dh dm)
16106 (if (not t2)
16108 (setq dh (- h2 h1) dm (- m2 m1))
16109 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16110 (concat t1 "+" (number-to-string dh)
16111 (and (/= 0 dm) (format ":%02d" dm)))))))
16113 (defun org-time-stamp-inactive (&optional arg)
16114 "Insert an inactive time stamp.
16115 An inactive time stamp is enclosed in square brackets instead of angle
16116 brackets. It is inactive in the sense that it does not trigger agenda entries,
16117 does not link to the calendar and cannot be changed with the S-cursor keys.
16118 So these are more for recording a certain time/date."
16119 (interactive "P")
16120 (org-time-stamp arg 'inactive))
16122 (defvar org-date-ovl (make-overlay 1 1))
16123 (overlay-put org-date-ovl 'face 'org-date-selected)
16124 (org-detach-overlay org-date-ovl)
16126 (defvar org-ans1) ; dynamically scoped parameter
16127 (defvar org-ans2) ; dynamically scoped parameter
16129 (defvar org-plain-time-of-day-regexp) ; defined below
16131 (defvar org-overriding-default-time nil) ; dynamically scoped
16132 (defvar org-read-date-overlay nil)
16133 (defvar org-dcst nil) ; dynamically scoped
16134 (defvar org-read-date-history nil)
16135 (defvar org-read-date-final-answer nil)
16136 (defvar org-read-date-analyze-futurep nil)
16137 (defvar org-read-date-analyze-forced-year nil)
16138 (defvar org-read-date-inactive)
16140 (defvar org-read-date-minibuffer-local-map
16141 (let* ((org-replace-disputed-keys nil)
16142 (map (make-sparse-keymap)))
16143 (set-keymap-parent map minibuffer-local-map)
16144 (org-defkey map (kbd ".")
16145 (lambda () (interactive)
16146 ;; Are we at the beginning of the prompt?
16147 (if (looking-back "^[^:]+: ")
16148 (org-eval-in-calendar '(calendar-goto-today))
16149 (insert "."))))
16150 (org-defkey map (kbd "C-.")
16151 (lambda () (interactive)
16152 (org-eval-in-calendar '(calendar-goto-today))))
16153 (org-defkey map [(meta shift left)]
16154 (lambda () (interactive)
16155 (org-eval-in-calendar '(calendar-backward-month 1))))
16156 (org-defkey map [(meta shift right)]
16157 (lambda () (interactive)
16158 (org-eval-in-calendar '(calendar-forward-month 1))))
16159 (org-defkey map [(meta shift up)]
16160 (lambda () (interactive)
16161 (org-eval-in-calendar '(calendar-backward-year 1))))
16162 (org-defkey map [(meta shift down)]
16163 (lambda () (interactive)
16164 (org-eval-in-calendar '(calendar-forward-year 1))))
16165 (org-defkey map [?\e (shift left)]
16166 (lambda () (interactive)
16167 (org-eval-in-calendar '(calendar-backward-month 1))))
16168 (org-defkey map [?\e (shift right)]
16169 (lambda () (interactive)
16170 (org-eval-in-calendar '(calendar-forward-month 1))))
16171 (org-defkey map [?\e (shift up)]
16172 (lambda () (interactive)
16173 (org-eval-in-calendar '(calendar-backward-year 1))))
16174 (org-defkey map [?\e (shift down)]
16175 (lambda () (interactive)
16176 (org-eval-in-calendar '(calendar-forward-year 1))))
16177 (org-defkey map [(shift up)]
16178 (lambda () (interactive)
16179 (org-eval-in-calendar '(calendar-backward-week 1))))
16180 (org-defkey map [(shift down)]
16181 (lambda () (interactive)
16182 (org-eval-in-calendar '(calendar-forward-week 1))))
16183 (org-defkey map [(shift left)]
16184 (lambda () (interactive)
16185 (org-eval-in-calendar '(calendar-backward-day 1))))
16186 (org-defkey map [(shift right)]
16187 (lambda () (interactive)
16188 (org-eval-in-calendar '(calendar-forward-day 1))))
16189 (org-defkey map "!"
16190 (lambda () (interactive)
16191 (org-eval-in-calendar '(diary-view-entries))
16192 (message "")))
16193 (org-defkey map ">"
16194 (lambda () (interactive)
16195 (org-eval-in-calendar '(scroll-calendar-left 1))))
16196 (org-defkey map "<"
16197 (lambda () (interactive)
16198 (org-eval-in-calendar '(scroll-calendar-right 1))))
16199 (org-defkey map "\C-v"
16200 (lambda () (interactive)
16201 (org-eval-in-calendar
16202 '(calendar-scroll-left-three-months 1))))
16203 (org-defkey map "\M-v"
16204 (lambda () (interactive)
16205 (org-eval-in-calendar
16206 '(calendar-scroll-right-three-months 1))))
16207 map)
16208 "Keymap for minibuffer commands when using `org-read-date'.")
16210 (defvar org-def)
16211 (defvar org-defdecode)
16212 (defvar org-with-time)
16214 (defun org-read-date (&optional org-with-time to-time from-string prompt
16215 default-time default-input inactive)
16216 "Read a date, possibly a time, and make things smooth for the user.
16217 The prompt will suggest to enter an ISO date, but you can also enter anything
16218 which will at least partially be understood by `parse-time-string'.
16219 Unrecognized parts of the date will default to the current day, month, year,
16220 hour and minute. If this command is called to replace a timestamp at point,
16221 or to enter the second timestamp of a range, the default time is taken
16222 from the existing stamp. Furthermore, the command prefers the future,
16223 so if you are giving a date where the year is not given, and the day-month
16224 combination is already past in the current year, it will assume you
16225 mean next year. For details, see the manual. A few examples:
16227 3-2-5 --> 2003-02-05
16228 feb 15 --> currentyear-02-15
16229 2/15 --> currentyear-02-15
16230 sep 12 9 --> 2009-09-12
16231 12:45 --> today 12:45
16232 22 sept 0:34 --> currentyear-09-22 0:34
16233 12 --> currentyear-currentmonth-12
16234 Fri --> nearest Friday after today
16235 -Tue --> last Tuesday
16236 etc.
16238 Furthermore you can specify a relative date by giving, as the *first* thing
16239 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16240 change in days weeks, months, years.
16241 With a single plus or minus, the date is relative to today. With a double
16242 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16243 +4d --> four days from today
16244 +4 --> same as above
16245 +2w --> two weeks from today
16246 ++5 --> five days from default date
16248 The function understands only English month and weekday abbreviations.
16250 While prompting, a calendar is popped up - you can also select the
16251 date with the mouse (button 1). The calendar shows a period of three
16252 months. To scroll it to other months, use the keys `>' and `<'.
16253 If you don't like the calendar, turn it off with
16254 \(setq org-read-date-popup-calendar nil)
16256 With optional argument TO-TIME, the date will immediately be converted
16257 to an internal time.
16258 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16259 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16260 still enter a time, and this function will inform the calling routine
16261 about this change. The calling routine may then choose to change the
16262 format used to insert the time stamp into the buffer to include the time.
16263 With optional argument FROM-STRING, read from this string instead from
16264 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16265 the time/date that is used for everything that is not specified by the
16266 user."
16267 (require 'parse-time)
16268 (let* ((org-time-stamp-rounding-minutes
16269 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16270 (org-dcst org-display-custom-times)
16271 (ct (org-current-time))
16272 (org-def (or org-overriding-default-time default-time ct))
16273 (org-defdecode (decode-time org-def))
16274 (dummy (progn
16275 (when (< (nth 2 org-defdecode) org-extend-today-until)
16276 (setcar (nthcdr 2 org-defdecode) -1)
16277 (setcar (nthcdr 1 org-defdecode) 59)
16278 (setq org-def (apply 'encode-time org-defdecode)
16279 org-defdecode (decode-time org-def)))))
16280 (mouse-autoselect-window nil) ; Don't let the mouse jump
16281 (calendar-frame-setup nil)
16282 (calendar-setup nil)
16283 (calendar-move-hook nil)
16284 (calendar-view-diary-initially-flag nil)
16285 (calendar-view-holidays-initially-flag nil)
16286 (timestr (format-time-string
16287 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16288 (prompt (concat (if prompt (concat prompt " ") "")
16289 (format "Date+time [%s]: " timestr)))
16290 ans (org-ans0 "") org-ans1 org-ans2 final)
16292 (cond
16293 (from-string (setq ans from-string))
16294 (org-read-date-popup-calendar
16295 (save-excursion
16296 (save-window-excursion
16297 (calendar)
16298 (org-eval-in-calendar '(setq cursor-type nil) t)
16299 (unwind-protect
16300 (progn
16301 (calendar-forward-day (- (time-to-days org-def)
16302 (calendar-absolute-from-gregorian
16303 (calendar-current-date))))
16304 (org-eval-in-calendar nil t)
16305 (let* ((old-map (current-local-map))
16306 (map (copy-keymap calendar-mode-map))
16307 (minibuffer-local-map
16308 (copy-keymap org-read-date-minibuffer-local-map)))
16309 (org-defkey map (kbd "RET") 'org-calendar-select)
16310 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16311 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16312 (unwind-protect
16313 (progn
16314 (use-local-map map)
16315 (setq org-read-date-inactive inactive)
16316 (add-hook 'post-command-hook 'org-read-date-display)
16317 (setq org-ans0 (read-string prompt default-input
16318 'org-read-date-history nil))
16319 ;; org-ans0: from prompt
16320 ;; org-ans1: from mouse click
16321 ;; org-ans2: from calendar motion
16322 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16323 (remove-hook 'post-command-hook 'org-read-date-display)
16324 (use-local-map old-map)
16325 (when org-read-date-overlay
16326 (delete-overlay org-read-date-overlay)
16327 (setq org-read-date-overlay nil)))))
16328 (bury-buffer "*Calendar*")))))
16330 (t ; Naked prompt only
16331 (unwind-protect
16332 (setq ans (read-string prompt default-input
16333 'org-read-date-history timestr))
16334 (when org-read-date-overlay
16335 (delete-overlay org-read-date-overlay)
16336 (setq org-read-date-overlay nil)))))
16338 (setq final (org-read-date-analyze ans org-def org-defdecode))
16340 (when org-read-date-analyze-forced-year
16341 (message "Year was forced into %s"
16342 (if org-read-date-force-compatible-dates
16343 "compatible range (1970-2037)"
16344 "range representable on this machine"))
16345 (ding))
16347 ;; One round trip to get rid of 34th of August and stuff like that....
16348 (setq final (decode-time (apply 'encode-time final)))
16350 (setq org-read-date-final-answer ans)
16352 (if to-time
16353 (apply 'encode-time final)
16354 (if (and (boundp 'org-time-was-given) org-time-was-given)
16355 (format "%04d-%02d-%02d %02d:%02d"
16356 (nth 5 final) (nth 4 final) (nth 3 final)
16357 (nth 2 final) (nth 1 final))
16358 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16360 (defun org-read-date-display ()
16361 "Display the current date prompt interpretation in the minibuffer."
16362 (when org-read-date-display-live
16363 (when org-read-date-overlay
16364 (delete-overlay org-read-date-overlay))
16365 (when (minibufferp (current-buffer))
16366 (save-excursion
16367 (end-of-line 1)
16368 (while (not (equal (buffer-substring
16369 (max (point-min) (- (point) 4)) (point))
16370 " "))
16371 (insert " ")))
16372 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16373 " " (or org-ans1 org-ans2)))
16374 (org-end-time-was-given nil)
16375 (f (org-read-date-analyze ans org-def org-defdecode))
16376 (fmts (if org-dcst
16377 org-time-stamp-custom-formats
16378 org-time-stamp-formats))
16379 (fmt (if (or org-with-time
16380 (and (boundp 'org-time-was-given) org-time-was-given))
16381 (cdr fmts)
16382 (car fmts)))
16383 (txt (format-time-string fmt (apply 'encode-time f)))
16384 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16385 (txt (concat "=> " txt)))
16386 (when (and org-end-time-was-given
16387 (string-match org-plain-time-of-day-regexp txt))
16388 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16389 org-end-time-was-given
16390 (substring txt (match-end 0)))))
16391 (when org-read-date-analyze-futurep
16392 (setq txt (concat txt " (=>F)")))
16393 (setq org-read-date-overlay
16394 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16395 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16397 (defun org-read-date-analyze (ans org-def org-defdecode)
16398 "Analyze the combined answer of the date prompt."
16399 ;; FIXME: cleanup and comment
16400 (let ((nowdecode (decode-time (current-time)))
16401 delta deltan deltaw deltadef year month day
16402 hour minute second wday pm h2 m2 tl wday1
16403 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16404 (setq org-read-date-analyze-futurep nil
16405 org-read-date-analyze-forced-year nil)
16406 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16407 (setq ans "+0"))
16409 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16410 (setq ans (replace-match "" t t ans)
16411 deltan (car delta)
16412 deltaw (nth 1 delta)
16413 deltadef (nth 2 delta)))
16415 ;; Check if there is an iso week date in there. If yes, store the
16416 ;; info and postpone interpreting it until the rest of the parsing
16417 ;; is done.
16418 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16419 (setq iso-year (if (match-end 1)
16420 (org-small-year-to-year
16421 (string-to-number (match-string 1 ans))))
16422 iso-weekday (if (match-end 3)
16423 (string-to-number (match-string 3 ans)))
16424 iso-week (string-to-number (match-string 2 ans)))
16425 (setq ans (replace-match "" t t ans)))
16427 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16428 (when (string-match
16429 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16430 (setq year (if (match-end 2)
16431 (string-to-number (match-string 2 ans))
16432 (progn (setq kill-year t)
16433 (string-to-number (format-time-string "%Y"))))
16434 month (string-to-number (match-string 3 ans))
16435 day (string-to-number (match-string 4 ans)))
16436 (if (< year 100) (setq year (+ 2000 year)))
16437 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16438 t nil ans)))
16440 ;; Help matching dotted european dates
16441 (when (string-match
16442 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16443 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16444 (setq kill-year t)
16445 (string-to-number (format-time-string "%Y")))
16446 day (string-to-number (match-string 1 ans))
16447 month (string-to-number (match-string 2 ans))
16448 ans (replace-match (format "%04d-%02d-%02d" year month day)
16449 t nil ans)))
16451 ;; Help matching american dates, like 5/30 or 5/30/7
16452 (when (string-match
16453 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16454 (setq year (if (match-end 4)
16455 (string-to-number (match-string 4 ans))
16456 (progn (setq kill-year t)
16457 (string-to-number (format-time-string "%Y"))))
16458 month (string-to-number (match-string 1 ans))
16459 day (string-to-number (match-string 2 ans)))
16460 (if (< year 100) (setq year (+ 2000 year)))
16461 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16462 t nil ans)))
16463 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16464 ;; If there is a time with am/pm, and *no* time without it, we convert
16465 ;; so that matching will be successful.
16466 (loop for i from 1 to 2 do ; twice, for end time as well
16467 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16468 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16469 (setq hour (string-to-number (match-string 1 ans))
16470 minute (if (match-end 3)
16471 (string-to-number (match-string 3 ans))
16473 pm (equal ?p
16474 (string-to-char (downcase (match-string 4 ans)))))
16475 (if (and (= hour 12) (not pm))
16476 (setq hour 0)
16477 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16478 (setq ans (replace-match (format "%02d:%02d" hour minute)
16479 t t ans))))
16481 ;; Check if a time range is given as a duration
16482 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16483 (setq hour (string-to-number (match-string 1 ans))
16484 h2 (+ hour (string-to-number (match-string 3 ans)))
16485 minute (string-to-number (match-string 2 ans))
16486 m2 (+ minute (if (match-end 5) (string-to-number
16487 (match-string 5 ans))0)))
16488 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16489 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16490 t t ans)))
16492 ;; Check if there is a time range
16493 (when (boundp 'org-end-time-was-given)
16494 (setq org-time-was-given nil)
16495 (when (and (string-match org-plain-time-of-day-regexp ans)
16496 (match-end 8))
16497 (setq org-end-time-was-given (match-string 8 ans))
16498 (setq ans (concat (substring ans 0 (match-beginning 7))
16499 (substring ans (match-end 7))))))
16501 (setq tl (parse-time-string ans)
16502 day (or (nth 3 tl) (nth 3 org-defdecode))
16503 month (or (nth 4 tl)
16504 (if (and org-read-date-prefer-future
16505 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16506 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16507 (nth 4 org-defdecode)))
16508 year (or (and (not kill-year) (nth 5 tl))
16509 (if (and org-read-date-prefer-future
16510 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16511 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16512 (nth 5 org-defdecode)))
16513 hour (or (nth 2 tl) (nth 2 org-defdecode))
16514 minute (or (nth 1 tl) (nth 1 org-defdecode))
16515 second (or (nth 0 tl) 0)
16516 wday (nth 6 tl))
16518 (when (and (eq org-read-date-prefer-future 'time)
16519 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16520 (equal day (nth 3 nowdecode))
16521 (equal month (nth 4 nowdecode))
16522 (equal year (nth 5 nowdecode))
16523 (nth 2 tl)
16524 (or (< (nth 2 tl) (nth 2 nowdecode))
16525 (and (= (nth 2 tl) (nth 2 nowdecode))
16526 (nth 1 tl)
16527 (< (nth 1 tl) (nth 1 nowdecode)))))
16528 (setq day (1+ day)
16529 futurep t))
16531 ;; Special date definitions below
16532 (cond
16533 (iso-week
16534 ;; There was an iso week
16535 (require 'cal-iso)
16536 (setq futurep nil)
16537 (setq year (or iso-year year)
16538 day (or iso-weekday wday 1)
16539 wday nil ; to make sure that the trigger below does not match
16540 iso-date (calendar-gregorian-from-absolute
16541 (calendar-absolute-from-iso
16542 (list iso-week day year))))
16543 ; FIXME: Should we also push ISO weeks into the future?
16544 ; (when (and org-read-date-prefer-future
16545 ; (not iso-year)
16546 ; (< (calendar-absolute-from-gregorian iso-date)
16547 ; (time-to-days (current-time))))
16548 ; (setq year (1+ year)
16549 ; iso-date (calendar-gregorian-from-absolute
16550 ; (calendar-absolute-from-iso
16551 ; (list iso-week day year)))))
16552 (setq month (car iso-date)
16553 year (nth 2 iso-date)
16554 day (nth 1 iso-date)))
16555 (deltan
16556 (setq futurep nil)
16557 (unless deltadef
16558 (let ((now (decode-time (current-time))))
16559 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16560 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16561 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16562 ((equal deltaw "m") (setq month (+ month deltan)))
16563 ((equal deltaw "y") (setq year (+ year deltan)))))
16564 ((and wday (not (nth 3 tl)))
16565 ;; Weekday was given, but no day, so pick that day in the week
16566 ;; on or after the derived date.
16567 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16568 (unless (equal wday wday1)
16569 (setq day (+ day (% (- wday wday1 -7) 7))))))
16570 (if (and (boundp 'org-time-was-given)
16571 (nth 2 tl))
16572 (setq org-time-was-given t))
16573 (if (< year 100) (setq year (+ 2000 year)))
16574 ;; Check of the date is representable
16575 (if org-read-date-force-compatible-dates
16576 (progn
16577 (if (< year 1970)
16578 (setq year 1970 org-read-date-analyze-forced-year t))
16579 (if (> year 2037)
16580 (setq year 2037 org-read-date-analyze-forced-year t)))
16581 (condition-case nil
16582 (ignore (encode-time second minute hour day month year))
16583 (error
16584 (setq year (nth 5 org-defdecode))
16585 (setq org-read-date-analyze-forced-year t))))
16586 (setq org-read-date-analyze-futurep futurep)
16587 (list second minute hour day month year)))
16589 (defvar parse-time-weekdays)
16590 (defun org-read-date-get-relative (s today default)
16591 "Check string S for special relative date string.
16592 TODAY and DEFAULT are internal times, for today and for a default.
16593 Return shift list (N what def-flag)
16594 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16595 N is the number of WHATs to shift.
16596 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16597 the DEFAULT date rather than TODAY."
16598 (require 'parse-time)
16599 (when (and
16600 (string-match
16601 (concat
16602 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16603 "\\([0-9]+\\)?"
16604 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16605 "\\([ \t]\\|$\\)") s)
16606 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16607 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16608 (string-to-char (substring (match-string 1 s) -1))
16609 ?+))
16610 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16611 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16612 (what (if (match-end 3) (match-string 3 s) "d"))
16613 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16614 (date (if rel default today))
16615 (wday (nth 6 (decode-time date)))
16616 delta)
16617 (if wday1
16618 (progn
16619 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16620 (if (= delta 0) (setq delta 7))
16621 (if (= dir ?-)
16622 (progn
16623 (setq delta (- delta 7))
16624 (if (= delta 0) (setq delta -7))))
16625 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16626 (list delta "d" rel))
16627 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16629 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16630 "Turn a user-specified date into the internal representation.
16631 The internal representation needed by the calendar is (month day year).
16632 This is a wrapper to handle the brain-dead convention in calendar that
16633 user function argument order change dependent on argument order."
16634 (if (boundp 'calendar-date-style)
16635 (cond
16636 ((eq calendar-date-style 'american)
16637 (list arg1 arg2 arg3))
16638 ((eq calendar-date-style 'european)
16639 (list arg2 arg1 arg3))
16640 ((eq calendar-date-style 'iso)
16641 (list arg2 arg3 arg1)))
16642 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16643 (if (org-bound-and-true-p european-calendar-style)
16644 (list arg2 arg1 arg3)
16645 (list arg1 arg2 arg3)))))
16647 (defun org-eval-in-calendar (form &optional keepdate)
16648 "Eval FORM in the calendar window and return to current window.
16649 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16650 otherwise stick to the current value of `org-ans2'."
16651 (let ((sf (selected-frame))
16652 (sw (selected-window)))
16653 (select-window (get-buffer-window "*Calendar*" t))
16654 (eval form)
16655 (when (and (not keepdate) (calendar-cursor-to-date))
16656 (let* ((date (calendar-cursor-to-date))
16657 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16658 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16659 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16660 (select-window sw)
16661 (org-select-frame-set-input-focus sf)))
16663 (defun org-calendar-select ()
16664 "Return to `org-read-date' with the date currently selected.
16665 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16666 (interactive)
16667 (when (calendar-cursor-to-date)
16668 (let* ((date (calendar-cursor-to-date))
16669 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16670 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16671 (if (active-minibuffer-window) (exit-minibuffer))))
16673 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16674 "Insert a date stamp for the date given by the internal TIME.
16675 WITH-HM means use the stamp format that includes the time of the day.
16676 INACTIVE means use square brackets instead of angular ones, so that the
16677 stamp will not contribute to the agenda.
16678 PRE and POST are optional strings to be inserted before and after the
16679 stamp.
16680 The command returns the inserted time stamp."
16681 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16682 stamp)
16683 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16684 (insert-before-markers (or pre ""))
16685 (when (listp extra)
16686 (setq extra (car extra))
16687 (if (and (stringp extra)
16688 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16689 (setq extra (format "-%02d:%02d"
16690 (string-to-number (match-string 1 extra))
16691 (string-to-number (match-string 2 extra))))
16692 (setq extra nil)))
16693 (when extra
16694 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16695 (insert-before-markers (setq stamp (format-time-string fmt time)))
16696 (insert-before-markers (or post ""))
16697 (setq org-last-inserted-timestamp stamp)))
16699 (defun org-toggle-time-stamp-overlays ()
16700 "Toggle the use of custom time stamp formats."
16701 (interactive)
16702 (setq org-display-custom-times (not org-display-custom-times))
16703 (unless org-display-custom-times
16704 (let ((p (point-min)) (bmp (buffer-modified-p)))
16705 (while (setq p (next-single-property-change p 'display))
16706 (if (and (get-text-property p 'display)
16707 (eq (get-text-property p 'face) 'org-date))
16708 (remove-text-properties
16709 p (setq p (next-single-property-change p 'display))
16710 '(display t))))
16711 (set-buffer-modified-p bmp)))
16712 (if (featurep 'xemacs)
16713 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16714 (org-restart-font-lock)
16715 (setq org-table-may-need-update t)
16716 (if org-display-custom-times
16717 (message "Time stamps are overlaid with custom format")
16718 (message "Time stamp overlays removed")))
16720 (defun org-display-custom-time (beg end)
16721 "Overlay modified time stamp format over timestamp between BEG and END."
16722 (let* ((ts (buffer-substring beg end))
16723 t1 w1 with-hm tf time str w2 (off 0))
16724 (save-match-data
16725 (setq t1 (org-parse-time-string ts t))
16726 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16727 (setq off (- (match-end 0) (match-beginning 0)))))
16728 (setq end (- end off))
16729 (setq w1 (- end beg)
16730 with-hm (and (nth 1 t1) (nth 2 t1))
16731 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16732 time (org-fix-decoded-time t1)
16733 str (org-add-props
16734 (format-time-string
16735 (substring tf 1 -1) (apply 'encode-time time))
16736 nil 'mouse-face 'highlight)
16737 w2 (length str))
16738 (if (not (= w2 w1))
16739 (add-text-properties (1+ beg) (+ 2 beg)
16740 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16741 (if (featurep 'xemacs)
16742 (progn
16743 (put-text-property beg end 'invisible t)
16744 (put-text-property beg end 'end-glyph (make-glyph str)))
16745 (put-text-property beg end 'display str))))
16747 (defun org-translate-time (string)
16748 "Translate all timestamps in STRING to custom format.
16749 But do this only if the variable `org-display-custom-times' is set."
16750 (when org-display-custom-times
16751 (save-match-data
16752 (let* ((start 0)
16753 (re org-ts-regexp-both)
16754 t1 with-hm inactive tf time str beg end)
16755 (while (setq start (string-match re string start))
16756 (setq beg (match-beginning 0)
16757 end (match-end 0)
16758 t1 (save-match-data
16759 (org-parse-time-string (substring string beg end) t))
16760 with-hm (and (nth 1 t1) (nth 2 t1))
16761 inactive (equal (substring string beg (1+ beg)) "[")
16762 tf (funcall (if with-hm 'cdr 'car)
16763 org-time-stamp-custom-formats)
16764 time (org-fix-decoded-time t1)
16765 str (format-time-string
16766 (concat
16767 (if inactive "[" "<") (substring tf 1 -1)
16768 (if inactive "]" ">"))
16769 (apply 'encode-time time))
16770 string (replace-match str t t string)
16771 start (+ start (length str)))))))
16772 string)
16774 (defun org-fix-decoded-time (time)
16775 "Set 0 instead of nil for the first 6 elements of time.
16776 Don't touch the rest."
16777 (let ((n 0))
16778 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16780 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16782 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16783 "Difference between TIMESTAMP-STRING and now in days.
16784 If SECONDS is non-nil, return the difference in seconds."
16785 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16786 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16787 (funcall fdiff (current-time)))))
16789 (defun org-deadline-close (timestamp-string &optional ndays)
16790 "Is the time in TIMESTAMP-STRING close to the current date?"
16791 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16792 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16793 (not (org-entry-is-done-p))))
16795 (defun org-get-wdays (ts &optional delay zero-delay)
16796 "Get the deadline lead time appropriate for timestring TS.
16797 When DELAY is non-nil, get the delay time for scheduled items
16798 instead of the deadline lead time. When ZERO-DELAY is non-nil
16799 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16800 don't try to find the delay cookie in the scheduled timestamp."
16801 (let ((tv (if delay org-scheduled-delay-days
16802 org-deadline-warning-days)))
16803 (cond
16804 ((or (and delay (< tv 0))
16805 (and delay zero-delay (<= tv 0))
16806 (and (not delay) (<= tv 0)))
16807 ;; Enforce this value no matter what
16808 (- tv))
16809 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16810 ;; lead time is specified.
16811 (floor (* (string-to-number (match-string 1 ts))
16812 (cdr (assoc (match-string 2 ts)
16813 '(("d" . 1) ("w" . 7)
16814 ("m" . 30.4) ("y" . 365.25)
16815 ("h" . 0.041667)))))))
16816 ;; go for the default.
16817 (t tv))))
16819 (defun org-calendar-select-mouse (ev)
16820 "Return to `org-read-date' with the date currently selected.
16821 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16822 (interactive "e")
16823 (mouse-set-point ev)
16824 (when (calendar-cursor-to-date)
16825 (let* ((date (calendar-cursor-to-date))
16826 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16827 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16828 (if (active-minibuffer-window) (exit-minibuffer))))
16830 (defun org-check-deadlines (ndays)
16831 "Check if there are any deadlines due or past due.
16832 A deadline is considered due if it happens within `org-deadline-warning-days'
16833 days from today's date. If the deadline appears in an entry marked DONE,
16834 it is not shown. The prefix arg NDAYS can be used to test that many
16835 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16836 (interactive "P")
16837 (let* ((org-warn-days
16838 (cond
16839 ((equal ndays '(4)) 100000)
16840 (ndays (prefix-numeric-value ndays))
16841 (t (abs org-deadline-warning-days))))
16842 (case-fold-search nil)
16843 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16844 (callback
16845 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16847 (message "%d deadlines past-due or due within %d days"
16848 (org-occur regexp nil callback)
16849 org-warn-days)))
16851 (defsubst org-re-timestamp (type)
16852 "Return a regexp for timestamp TYPE.
16853 Allowed values for TYPE are:
16855 all: all timestamps
16856 active: only active timestamps (<...>)
16857 inactive: only inactive timestamps ([...])
16858 scheduled: only scheduled timestamps
16859 deadline: only deadline timestamps
16860 closed: only closed time-stamps
16862 When TYPE is nil, fall back on returning a regexp that matches
16863 both scheduled and deadline timestamps."
16864 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16865 ((eq type 'active) org-ts-regexp)
16866 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16867 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16868 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16869 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
16870 ((eq type 'scheduled-or-deadline)
16871 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16873 (defun org-check-before-date (date)
16874 "Check if there are deadlines or scheduled entries before DATE."
16875 (interactive (list (org-read-date)))
16876 (let ((case-fold-search nil)
16877 (regexp (org-re-timestamp org-ts-type))
16878 (callback
16879 (lambda () (time-less-p
16880 (org-time-string-to-time (match-string 1))
16881 (org-time-string-to-time date)))))
16882 (message "%d entries before %s"
16883 (org-occur regexp nil callback) date)))
16885 (defun org-check-after-date (date)
16886 "Check if there are deadlines or scheduled entries after DATE."
16887 (interactive (list (org-read-date)))
16888 (let ((case-fold-search nil)
16889 (regexp (org-re-timestamp org-ts-type))
16890 (callback
16891 (lambda () (not
16892 (time-less-p
16893 (org-time-string-to-time (match-string 1))
16894 (org-time-string-to-time date))))))
16895 (message "%d entries after %s"
16896 (org-occur regexp nil callback) date)))
16898 (defun org-check-dates-range (start-date end-date)
16899 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16900 (interactive (list (org-read-date nil nil nil "Range starts")
16901 (org-read-date nil nil nil "Range end")))
16902 (let ((case-fold-search nil)
16903 (regexp (org-re-timestamp org-ts-type))
16904 (callback
16905 (lambda ()
16906 (let ((match (match-string 1)))
16907 (and
16908 (not (time-less-p
16909 (org-time-string-to-time match)
16910 (org-time-string-to-time start-date)))
16911 (time-less-p
16912 (org-time-string-to-time match)
16913 (org-time-string-to-time end-date)))))))
16914 (message "%d entries between %s and %s"
16915 (org-occur regexp nil callback) start-date end-date)))
16917 (defun org-evaluate-time-range (&optional to-buffer)
16918 "Evaluate a time range by computing the difference between start and end.
16919 Normally the result is just printed in the echo area, but with prefix arg
16920 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16921 If the time range is actually in a table, the result is inserted into the
16922 next column.
16923 For time difference computation, a year is assumed to be exactly 365
16924 days in order to avoid rounding problems."
16925 (interactive "P")
16927 (org-clock-update-time-maybe)
16928 (save-excursion
16929 (unless (org-at-date-range-p t)
16930 (goto-char (point-at-bol))
16931 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16932 (if (not (org-at-date-range-p t))
16933 (user-error "Not at a time-stamp range, and none found in current line")))
16934 (let* ((ts1 (match-string 1))
16935 (ts2 (match-string 2))
16936 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16937 (match-end (match-end 0))
16938 (time1 (org-time-string-to-time ts1))
16939 (time2 (org-time-string-to-time ts2))
16940 (t1 (org-float-time time1))
16941 (t2 (org-float-time time2))
16942 (diff (abs (- t2 t1)))
16943 (negative (< (- t2 t1) 0))
16944 ;; (ys (floor (* 365 24 60 60)))
16945 (ds (* 24 60 60))
16946 (hs (* 60 60))
16947 (fy "%dy %dd %02d:%02d")
16948 (fy1 "%dy %dd")
16949 (fd "%dd %02d:%02d")
16950 (fd1 "%dd")
16951 (fh "%02d:%02d")
16952 y d h m align)
16953 (if havetime
16954 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16956 d (floor (/ diff ds)) diff (mod diff ds)
16957 h (floor (/ diff hs)) diff (mod diff hs)
16958 m (floor (/ diff 60)))
16959 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16961 d (floor (+ (/ diff ds) 0.5))
16962 h 0 m 0))
16963 (if (not to-buffer)
16964 (message "%s" (org-make-tdiff-string y d h m))
16965 (if (org-at-table-p)
16966 (progn
16967 (goto-char match-end)
16968 (setq align t)
16969 (and (looking-at " *|") (goto-char (match-end 0))))
16970 (goto-char match-end))
16971 (if (looking-at
16972 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16973 (replace-match ""))
16974 (if negative (insert " -"))
16975 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16976 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16977 (insert " " (format fh h m))))
16978 (if align (org-table-align))
16979 (message "Time difference inserted")))))
16981 (defun org-make-tdiff-string (y d h m)
16982 (let ((fmt "")
16983 (l nil))
16984 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16985 l (push y l)))
16986 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16987 l (push d l)))
16988 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16989 l (push h l)))
16990 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16991 l (push m l)))
16992 (apply 'format fmt (nreverse l))))
16994 (defun org-time-string-to-time (s &optional buffer pos)
16995 "Convert a timestamp string into internal time."
16996 (condition-case errdata
16997 (apply 'encode-time (org-parse-time-string s))
16998 (error (error "Bad timestamp `%s'%s\nError was: %s"
16999 s (if (not (and buffer pos))
17001 (format " at %d in buffer `%s'" pos buffer))
17002 (cdr errdata)))))
17004 (defun org-time-string-to-seconds (s)
17005 "Convert a timestamp string to a number of seconds."
17006 (org-float-time (org-time-string-to-time s)))
17008 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17009 "Convert a time stamp to an absolute day number.
17010 If there is a specifier for a cyclic time stamp, get the closest
17011 date to DAYNR.
17012 PREFER and SHOW-ALL are passed through to `org-closest-date'.
17013 The variable `date' is bound by the calendar when this is called."
17014 (cond
17015 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17016 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17017 daynr
17018 (+ daynr 1000)))
17019 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
17020 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17021 (time-to-days (current-time))) (match-string 0 s)
17022 prefer show-all))
17023 (t (time-to-days
17024 (condition-case errdata
17025 (apply 'encode-time (org-parse-time-string s))
17026 (error (error "Bad timestamp `%s'%s\nError was: %s"
17027 s (if (not (and buffer pos))
17029 (format " at %d in buffer `%s'" pos buffer))
17030 (cdr errdata))))))))
17032 (defun org-days-to-iso-week (days)
17033 "Return the iso week number."
17034 (require 'cal-iso)
17035 (car (calendar-iso-from-absolute days)))
17037 (defun org-small-year-to-year (year)
17038 "Convert 2-digit years into 4-digit years.
17039 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
17040 The year 2000 cannot be abbreviated. Any year larger than 99
17041 is returned unchanged."
17042 (if (< year 38)
17043 (setq year (+ 2000 year))
17044 (if (< year 100)
17045 (setq year (+ 1900 year))))
17046 year)
17048 (defun org-time-from-absolute (d)
17049 "Return the time corresponding to date D.
17050 D may be an absolute day number, or a calendar-type list (month day year)."
17051 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17052 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17054 (defun org-calendar-holiday ()
17055 "List of holidays, for Diary display in Org-mode."
17056 (require 'holidays)
17057 (let ((hl (funcall
17058 (if (fboundp 'calendar-check-holidays)
17059 'calendar-check-holidays 'check-calendar-holidays) date)))
17060 (if hl (mapconcat 'identity hl "; "))))
17062 (defun org-diary-sexp-entry (sexp entry date)
17063 "Process a SEXP diary ENTRY for DATE."
17064 (require 'diary-lib)
17065 (let ((result (if calendar-debug-sexp
17066 (let ((stack-trace-on-error t))
17067 (eval (car (read-from-string sexp))))
17068 (condition-case nil
17069 (eval (car (read-from-string sexp)))
17070 (error
17071 (beep)
17072 (message "Bad sexp at line %d in %s: %s"
17073 (org-current-line)
17074 (buffer-file-name) sexp)
17075 (sleep-for 2))))))
17076 (cond ((stringp result) (split-string result "; "))
17077 ((and (consp result)
17078 (not (consp (cdr result)))
17079 (stringp (cdr result))) (cdr result))
17080 ((and (consp result)
17081 (stringp (car result))) result)
17082 (result entry))))
17084 (defun org-diary-to-ical-string (frombuf)
17085 "Get iCalendar entries from diary entries in buffer FROMBUF.
17086 This uses the icalendar.el library."
17087 (let* ((tmpdir (if (featurep 'xemacs)
17088 (temp-directory)
17089 temporary-file-directory))
17090 (tmpfile (make-temp-name
17091 (expand-file-name "orgics" tmpdir)))
17092 buf rtn b e)
17093 (with-current-buffer frombuf
17094 (icalendar-export-region (point-min) (point-max) tmpfile)
17095 (setq buf (find-buffer-visiting tmpfile))
17096 (set-buffer buf)
17097 (goto-char (point-min))
17098 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17099 (setq b (match-beginning 0)))
17100 (goto-char (point-max))
17101 (if (re-search-backward "^END:VEVENT" nil t)
17102 (setq e (match-end 0)))
17103 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17104 (kill-buffer buf)
17105 (delete-file tmpfile)
17106 rtn))
17108 (defun org-closest-date (start current change prefer show-all)
17109 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17110 When PREFER is `past', return a date that is either CURRENT or past.
17111 When PREFER is `future', return a date that is either CURRENT or future.
17112 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17113 ;; Make the proper lists from the dates
17114 (catch 'exit
17115 (let ((a1 '(("h" . hour)
17116 ("d" . day)
17117 ("w" . week)
17118 ("m" . month)
17119 ("y" . year)))
17120 (shour (nth 2 (org-parse-time-string start)))
17121 dn dw sday cday n1 n2 n0
17122 d m y y1 y2 date1 date2 nmonths nm ny m2)
17124 (setq start (org-date-to-gregorian start)
17125 current (org-date-to-gregorian
17126 (if show-all
17127 current
17128 (time-to-days (current-time))))
17129 sday (calendar-absolute-from-gregorian start)
17130 cday (calendar-absolute-from-gregorian current))
17132 (if (<= cday sday) (throw 'exit sday))
17134 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17135 (setq dn (string-to-number (match-string 1 change))
17136 dw (cdr (assoc (match-string 2 change) a1)))
17137 (user-error "Invalid change specifier: %s" change))
17138 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17139 (cond
17140 ((eq dw 'hour)
17141 (let ((missing-hours
17142 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17143 dn)))
17144 (setq n1 (if (zerop missing-hours) cday
17145 (- cday (1+ (floor (/ missing-hours 24)))))
17146 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17147 ((eq dw 'day)
17148 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17149 n2 (+ n1 dn)))
17150 ((eq dw 'year)
17151 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17152 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17153 (setq date1 (list m d y1)
17154 n1 (calendar-absolute-from-gregorian date1)
17155 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17156 n2 (calendar-absolute-from-gregorian date2)))
17157 ((eq dw 'month)
17158 ;; approx number of month between the two dates
17159 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17160 ;; How often does dn fit in there?
17161 (setq d (nth 1 start) m (car start) y (nth 2 start)
17162 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17163 m (+ m nm)
17164 ny (floor (/ m 12))
17165 y (+ y ny)
17166 m (- m (* ny 12)))
17167 (while (> m 12) (setq m (- m 12) y (1+ y)))
17168 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17169 (setq m2 (+ m dn) y2 y)
17170 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17171 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17172 (while (<= n2 cday)
17173 (setq n1 n2 m m2 y y2)
17174 (setq m2 (+ m dn) y2 y)
17175 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17176 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17177 ;; Make sure n1 is the earlier date
17178 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17179 (if show-all
17180 (cond
17181 ((eq prefer 'past) (if (= cday n2) n2 n1))
17182 ((eq prefer 'future) (if (= cday n1) n1 n2))
17183 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17184 (cond
17185 ((eq prefer 'past) (if (= cday n2) n2 n1))
17186 ((eq prefer 'future) (if (= cday n1) n1 n2))
17187 (t (if (= cday n1) n1 n2)))))))
17189 (defun org-date-to-gregorian (date)
17190 "Turn any specification of DATE into a Gregorian date for the calendar."
17191 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17192 ((and (listp date) (= (length date) 3)) date)
17193 ((stringp date)
17194 (setq date (org-parse-time-string date))
17195 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17196 ((listp date)
17197 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17199 (defun org-parse-time-string (s &optional nodefault)
17200 "Parse the standard Org-mode time string.
17201 This should be a lot faster than the normal `parse-time-string'.
17202 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17203 hour and minute fields will be nil if not given."
17204 (cond ((string-match org-ts-regexp0 s)
17205 (list 0
17206 (if (or (match-beginning 8) (not nodefault))
17207 (string-to-number (or (match-string 8 s) "0")))
17208 (if (or (match-beginning 7) (not nodefault))
17209 (string-to-number (or (match-string 7 s) "0")))
17210 (string-to-number (match-string 4 s))
17211 (string-to-number (match-string 3 s))
17212 (string-to-number (match-string 2 s))
17213 nil nil nil))
17214 ((string-match "^<[^>]+>$" s)
17215 (decode-time (seconds-to-time (org-matcher-time s))))
17216 (t (error "Not a standard Org-mode time string: %s" s))))
17218 (defun org-timestamp-up (&optional arg)
17219 "Increase the date item at the cursor by one.
17220 If the cursor is on the year, change the year. If it is on the month,
17221 the day or the time, change that.
17222 With prefix ARG, change by that many units."
17223 (interactive "p")
17224 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17226 (defun org-timestamp-down (&optional arg)
17227 "Decrease the date item at the cursor by one.
17228 If the cursor is on the year, change the year. If it is on the month,
17229 the day or the time, change that.
17230 With prefix ARG, change by that many units."
17231 (interactive "p")
17232 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17234 (defun org-timestamp-up-day (&optional arg)
17235 "Increase the date in the time stamp by one day.
17236 With prefix ARG, change that many days."
17237 (interactive "p")
17238 (if (and (not (org-at-timestamp-p t))
17239 (org-at-heading-p))
17240 (org-todo 'up)
17241 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17243 (defun org-timestamp-down-day (&optional arg)
17244 "Decrease the date in the time stamp by one day.
17245 With prefix ARG, change that many days."
17246 (interactive "p")
17247 (if (and (not (org-at-timestamp-p t))
17248 (org-at-heading-p))
17249 (org-todo 'down)
17250 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17252 (defun org-at-timestamp-p (&optional inactive-ok)
17253 "Determine if the cursor is in or at a timestamp."
17254 (interactive)
17255 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17256 (pos (point))
17257 (ans (or (looking-at tsr)
17258 (save-excursion
17259 (skip-chars-backward "^[<\n\r\t")
17260 (if (> (point) (point-min)) (backward-char 1))
17261 (and (looking-at tsr)
17262 (> (- (match-end 0) pos) -1))))))
17263 (and ans
17264 (boundp 'org-ts-what)
17265 (setq org-ts-what
17266 (cond
17267 ((= pos (match-beginning 0)) 'bracket)
17268 ;; Point is considered to be "on the bracket" whether
17269 ;; it's really on it or right after it.
17270 ((= pos (1- (match-end 0))) 'bracket)
17271 ((= pos (match-end 0)) 'after)
17272 ((org-pos-in-match-range pos 2) 'year)
17273 ((org-pos-in-match-range pos 3) 'month)
17274 ((org-pos-in-match-range pos 7) 'hour)
17275 ((org-pos-in-match-range pos 8) 'minute)
17276 ((or (org-pos-in-match-range pos 4)
17277 (org-pos-in-match-range pos 5)) 'day)
17278 ((and (> pos (or (match-end 8) (match-end 5)))
17279 (< pos (match-end 0)))
17280 (- pos (or (match-end 8) (match-end 5))))
17281 (t 'day))))
17282 ans))
17284 (defun org-toggle-timestamp-type ()
17285 "Toggle the type (<active> or [inactive]) of a time stamp."
17286 (interactive)
17287 (when (org-at-timestamp-p t)
17288 (let ((beg (match-beginning 0)) (end (match-end 0))
17289 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17290 (save-excursion
17291 (goto-char beg)
17292 (while (re-search-forward "[][<>]" end t)
17293 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17294 t t)))
17295 (message "Timestamp is now %sactive"
17296 (if (equal (char-after beg) ?<) "" "in")))))
17298 (defun org-at-clock-log-p nil
17299 "Is the cursor on the clock log line?"
17300 (save-excursion
17301 (move-beginning-of-line 1)
17302 (looking-at "^[ \t]*CLOCK:")))
17304 (defvar org-clock-history) ; defined in org-clock.el
17305 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17306 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17307 "Change the date in the time stamp at point.
17308 The date will be changed by N times WHAT. WHAT can be `day', `month',
17309 `year', `minute', `second'. If WHAT is not given, the cursor position
17310 in the timestamp determines what will be changed.
17311 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17312 (let ((origin (point)) origin-cat
17313 with-hm inactive
17314 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17315 org-ts-what
17316 extra rem
17317 ts time time0 fixnext clrgx)
17318 (if (not (org-at-timestamp-p t))
17319 (user-error "Not at a timestamp"))
17320 (if (and (not what) (eq org-ts-what 'bracket))
17321 (org-toggle-timestamp-type)
17322 ;; Point isn't on brackets. Remember the part of the time-stamp
17323 ;; the point was in. Indeed, size of time-stamps may change,
17324 ;; but point must be kept in the same category nonetheless.
17325 (setq origin-cat org-ts-what)
17326 (if (and (not what) (not (eq org-ts-what 'day))
17327 org-display-custom-times
17328 (get-text-property (point) 'display)
17329 (not (get-text-property (1- (point)) 'display)))
17330 (setq org-ts-what 'day))
17331 (setq org-ts-what (or what org-ts-what)
17332 inactive (= (char-after (match-beginning 0)) ?\[)
17333 ts (match-string 0))
17334 (replace-match "")
17335 (when (string-match
17336 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17338 (setq extra (match-string 1 ts))
17339 (if suppress-tmp-delay
17340 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17341 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17342 (setq with-hm t))
17343 (setq time0 (org-parse-time-string ts))
17344 (when (and updown
17345 (eq org-ts-what 'minute)
17346 (not current-prefix-arg))
17347 ;; This looks like s-up and s-down. Change by one rounding step.
17348 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17349 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17350 (setcar (cdr time0) (+ (nth 1 time0)
17351 (if (> n 0) (- rem) (- dm rem))))))
17352 (setq time
17353 (encode-time (or (car time0) 0)
17354 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17355 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17356 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17357 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17358 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17359 (nthcdr 6 time0)))
17360 (when (and (member org-ts-what '(hour minute))
17361 extra
17362 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17363 (setq extra (org-modify-ts-extra
17364 extra
17365 (if (eq org-ts-what 'hour) 2 5)
17366 n dm)))
17367 (when (integerp org-ts-what)
17368 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17369 (if (eq what 'calendar)
17370 (let ((cal-date (org-get-date-from-calendar)))
17371 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17372 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17373 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17374 (setcar time0 (or (car time0) 0))
17375 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17376 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17377 (setq time (apply 'encode-time time0))))
17378 ;; Insert the new time-stamp, and ensure point stays in the same
17379 ;; category as before (i.e. not after the last position in that
17380 ;; category).
17381 (let ((pos (point)))
17382 ;; Stay before inserted string. `save-excursion' is of no use.
17383 (setq org-last-changed-timestamp
17384 (org-insert-time-stamp time with-hm inactive nil nil extra))
17385 (goto-char pos))
17386 (save-match-data
17387 (looking-at org-ts-regexp3)
17388 (goto-char (cond
17389 ;; `day' category ends before `hour' if any, or at
17390 ;; the end of the day name.
17391 ((eq origin-cat 'day)
17392 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17393 ((eq origin-cat 'hour) (min (match-end 7) origin))
17394 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17395 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17396 ;; `year' and `month' have both fixed size: point
17397 ;; couldn't have moved into another part.
17398 (t origin))))
17399 ;; Update clock if on a CLOCK line.
17400 (org-clock-update-time-maybe)
17401 ;; Maybe adjust the closest clock in `org-clock-history'
17402 (when org-clock-adjust-closest
17403 (if (not (and (org-at-clock-log-p)
17404 (< 1 (length (delq nil (mapcar 'marker-position
17405 org-clock-history))))))
17406 (message "No clock to adjust")
17407 (cond ((save-excursion ; fix previous clock?
17408 (re-search-backward org-ts-regexp0 nil t)
17409 (org-looking-back (concat org-clock-string " \\[")))
17410 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17411 ((save-excursion ; fix next clock?
17412 (re-search-backward org-ts-regexp0 nil t)
17413 (looking-at (concat org-ts-regexp0 "\\] =>")))
17414 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17415 (save-window-excursion
17416 ;; Find closest clock to point, adjust the previous/next one in history
17417 (let* ((p (save-excursion (org-back-to-heading t)))
17418 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17419 (clfixnth
17420 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17421 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17422 (if (not clfixpos)
17423 (message "No clock to adjust")
17424 (save-excursion
17425 (org-goto-marker-or-bmk clfixpos)
17426 (org-show-subtree)
17427 (when (re-search-forward clrgx nil t)
17428 (goto-char (match-beginning 1))
17429 (let (org-clock-adjust-closest)
17430 (org-timestamp-change n org-ts-what updown))
17431 (message "Clock adjusted in %s for heading: %s"
17432 (file-name-nondirectory (buffer-file-name))
17433 (org-get-heading t t)))))))))
17434 ;; Try to recenter the calendar window, if any.
17435 (if (and org-calendar-follow-timestamp-change
17436 (get-buffer-window "*Calendar*" t)
17437 (memq org-ts-what '(day month year)))
17438 (org-recenter-calendar (time-to-days time))))))
17440 (defun org-modify-ts-extra (s pos n dm)
17441 "Change the different parts of the lead-time and repeat fields in timestamp."
17442 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17443 ng h m new rem)
17444 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17445 (cond
17446 ((or (org-pos-in-match-range pos 2)
17447 (org-pos-in-match-range pos 3))
17448 (setq m (string-to-number (match-string 3 s))
17449 h (string-to-number (match-string 2 s)))
17450 (if (org-pos-in-match-range pos 2)
17451 (setq h (+ h n))
17452 (setq n (* dm (org-no-warnings (signum n))))
17453 (when (not (= 0 (setq rem (% m dm))))
17454 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17455 (setq m (+ m n)))
17456 (if (< m 0) (setq m (+ m 60) h (1- h)))
17457 (if (> m 59) (setq m (- m 60) h (1+ h)))
17458 (setq h (min 24 (max 0 h)))
17459 (setq ng 1 new (format "-%02d:%02d" h m)))
17460 ((org-pos-in-match-range pos 6)
17461 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17462 ((org-pos-in-match-range pos 5)
17463 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17465 ((org-pos-in-match-range pos 9)
17466 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17467 ((org-pos-in-match-range pos 8)
17468 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17470 (when ng
17471 (setq s (concat
17472 (substring s 0 (match-beginning ng))
17474 (substring s (match-end ng))))))
17477 (defun org-recenter-calendar (date)
17478 "If the calendar is visible, recenter it to DATE."
17479 (let ((cwin (get-buffer-window "*Calendar*" t)))
17480 (when cwin
17481 (let ((calendar-move-hook nil))
17482 (with-selected-window cwin
17483 (calendar-goto-date (if (listp date) date
17484 (calendar-gregorian-from-absolute date))))))))
17486 (defun org-goto-calendar (&optional arg)
17487 "Go to the Emacs calendar at the current date.
17488 If there is a time stamp in the current line, go to that date.
17489 A prefix ARG can be used to force the current date."
17490 (interactive "P")
17491 (let ((tsr org-ts-regexp) diff
17492 (calendar-move-hook nil)
17493 (calendar-view-holidays-initially-flag nil)
17494 (calendar-view-diary-initially-flag nil))
17495 (if (or (org-at-timestamp-p)
17496 (save-excursion
17497 (beginning-of-line 1)
17498 (looking-at (concat ".*" tsr))))
17499 (let ((d1 (time-to-days (current-time)))
17500 (d2 (time-to-days
17501 (org-time-string-to-time (match-string 1)))))
17502 (setq diff (- d2 d1))))
17503 (calendar)
17504 (calendar-goto-today)
17505 (if (and diff (not arg)) (calendar-forward-day diff))))
17507 (defun org-get-date-from-calendar ()
17508 "Return a list (month day year) of date at point in calendar."
17509 (with-current-buffer "*Calendar*"
17510 (save-match-data
17511 (calendar-cursor-to-date))))
17513 (defun org-date-from-calendar ()
17514 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17515 If there is already a time stamp at the cursor position, update it."
17516 (interactive)
17517 (if (org-at-timestamp-p t)
17518 (org-timestamp-change 0 'calendar)
17519 (let ((cal-date (org-get-date-from-calendar)))
17520 (org-insert-time-stamp
17521 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17523 (defcustom org-effort-durations
17524 `(("h" . 60)
17525 ("d" . ,(* 60 8))
17526 ("w" . ,(* 60 8 5))
17527 ("m" . ,(* 60 8 5 4))
17528 ("y" . ,(* 60 8 5 40)))
17529 "Conversion factor to minutes for an effort modifier.
17531 Each entry has the form (MODIFIER . MINUTES).
17533 In an effort string, a number followed by MODIFIER is multiplied
17534 by the specified number of MINUTES to obtain an effort in
17535 minutes.
17537 For example, if the value of this variable is ((\"hours\" . 60)), then an
17538 effort string \"2hours\" is equivalent to 120 minutes."
17539 :group 'org-agenda
17540 :version "24.1"
17541 :type '(alist :key-type (string :tag "Modifier")
17542 :value-type (number :tag "Minutes")))
17544 (defun org-minutes-to-clocksum-string (m)
17545 "Format number of minutes as a clocksum string.
17546 The format is determined by `org-time-clocksum-format',
17547 `org-time-clocksum-use-fractional' and
17548 `org-time-clocksum-fractional-format' and
17549 `org-time-clocksum-use-effort-durations'."
17550 (let ((clocksum "")
17551 (m (round m)) ; Don't allow fractions of minutes
17552 h d w mo y fmt n)
17553 (setq h (if org-time-clocksum-use-effort-durations
17554 (cdr (assoc "h" org-effort-durations)) 60)
17555 d (if org-time-clocksum-use-effort-durations
17556 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17557 w (if org-time-clocksum-use-effort-durations
17558 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17559 mo (if org-time-clocksum-use-effort-durations
17560 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17561 y (if org-time-clocksum-use-effort-durations
17562 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17563 ;; fractional format
17564 (if org-time-clocksum-use-fractional
17565 (cond
17566 ;; single format string
17567 ((stringp org-time-clocksum-fractional-format)
17568 (format org-time-clocksum-fractional-format (/ m (float h))))
17569 ;; choice of fractional formats for different time units
17570 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17571 (> (/ (truncate m) (* y d h)) 0))
17572 (format fmt (/ m (* y d (float h)))))
17573 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17574 (> (/ (truncate m) (* mo d h)) 0))
17575 (format fmt (/ m (* mo d (float h)))))
17576 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17577 (> (/ (truncate m) (* w d h)) 0))
17578 (format fmt (/ m (* w d (float h)))))
17579 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17580 (> (/ (truncate m) (* d h)) 0))
17581 (format fmt (/ m (* d (float h)))))
17582 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17583 (> (/ (truncate m) h) 0))
17584 (format fmt (/ m (float h))))
17585 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17586 (format fmt m))
17587 ;; fall back to smallest time unit with a format
17588 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17589 (format fmt (/ m (float h))))
17590 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17591 (format fmt (/ m (* d (float h)))))
17592 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17593 (format fmt (/ m (* w d (float h)))))
17594 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17595 (format fmt (/ m (* mo d (float h)))))
17596 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17597 (format fmt (/ m (* y d (float h))))))
17598 ;; standard (non-fractional) format, with single format string
17599 (if (stringp org-time-clocksum-format)
17600 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17601 ;; separate formats components
17602 (and (setq fmt (plist-get org-time-clocksum-format :years))
17603 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17604 (plist-get org-time-clocksum-format :require-years))
17605 (setq clocksum (concat clocksum (format fmt n))
17606 m (- m (* n y d h))))
17607 (and (setq fmt (plist-get org-time-clocksum-format :months))
17608 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17609 (plist-get org-time-clocksum-format :require-months))
17610 (setq clocksum (concat clocksum (format fmt n))
17611 m (- m (* n mo d h))))
17612 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17613 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17614 (plist-get org-time-clocksum-format :require-weeks))
17615 (setq clocksum (concat clocksum (format fmt n))
17616 m (- m (* n w d h))))
17617 (and (setq fmt (plist-get org-time-clocksum-format :days))
17618 (or (> (setq n (/ (truncate m) (* d h))) 0)
17619 (plist-get org-time-clocksum-format :require-days))
17620 (setq clocksum (concat clocksum (format fmt n))
17621 m (- m (* n d h))))
17622 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17623 (or (> (setq n (/ (truncate m) h)) 0)
17624 (plist-get org-time-clocksum-format :require-hours))
17625 (setq clocksum (concat clocksum (format fmt n))
17626 m (- m (* n h))))
17627 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17628 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17629 (setq clocksum (concat clocksum (format fmt m))))
17630 ;; return formatted time duration
17631 clocksum))))
17633 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17634 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17635 "Org mode version 8.0")
17637 (defun org-hours-to-clocksum-string (n)
17638 (org-minutes-to-clocksum-string (* n 60)))
17640 (defun org-hh:mm-string-to-minutes (s)
17641 "Convert a string H:MM to a number of minutes.
17642 If the string is just a number, interpret it as minutes.
17643 In fact, the first hh:mm or number in the string will be taken,
17644 there can be extra stuff in the string.
17645 If no number is found, the return value is 0."
17646 (cond
17647 ((integerp s) s)
17648 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17649 (+ (* (string-to-number (match-string 1 s)) 60)
17650 (string-to-number (match-string 2 s))))
17651 ((string-match "\\([0-9]+\\)" s)
17652 (string-to-number (match-string 1 s)))
17653 (t 0)))
17655 (defcustom org-image-actual-width t
17656 "Should we use the actual width of images when inlining them?
17658 When set to `t', always use the image width.
17660 When set to a number, use imagemagick (when available) to set
17661 the image's width to this value.
17663 When set to a number in a list, try to get the width from any
17664 #+ATTR.* keyword if it matches a width specification like
17666 #+ATTR_HTML: :width 300px
17668 and fall back on that number if none is found.
17670 When set to nil, try to get the width from an #+ATTR.* keyword
17671 and fall back on the original width if none is found.
17673 This requires Emacs >= 24.1, build with imagemagick support."
17674 :group 'org-appearance
17675 :version "24.4"
17676 :package-version '(Org . "8.0")
17677 :type '(choice
17678 (const :tag "Use the image width" t)
17679 (integer :tag "Use a number of pixels")
17680 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17681 (const :tag "Use #+ATTR* or don't resize" nil)))
17683 (defcustom org-agenda-inhibit-startup nil
17684 "Inhibit startup when preparing agenda buffers.
17685 When this variable is `t' (the default), the initialization of
17686 the Org agenda buffers is inhibited: e.g. the visibility state
17687 is not set, the tables are not re-aligned, etc."
17688 :type 'boolean
17689 :version "24.3"
17690 :group 'org-agenda)
17692 (defcustom org-agenda-ignore-drawer-properties nil
17693 "Avoid updating text properties when building the agenda.
17694 Properties are used to prepare buffers for effort estimates, appointments,
17695 and subtree-local categories.
17696 If you don't use these in the agenda, you can add them to this list and
17697 agenda building will be a bit faster.
17698 The value is a list, with zero or more of the symbols `effort', `appt',
17699 or `category'."
17700 :type '(set :greedy t
17701 (const effort)
17702 (const appt)
17703 (const category))
17704 :version "24.3"
17705 :group 'org-agenda)
17707 (defun org-duration-string-to-minutes (s &optional output-to-string)
17708 "Convert a duration string S to minutes.
17710 A bare number is interpreted as minutes, modifiers can be set by
17711 customizing `org-effort-durations' (which see).
17713 Entries containing a colon are interpreted as H:MM by
17714 `org-hh:mm-string-to-minutes'."
17715 (let ((result 0)
17716 (re (concat "\\([0-9.]+\\) *\\("
17717 (regexp-opt (mapcar 'car org-effort-durations))
17718 "\\)")))
17719 (while (string-match re s)
17720 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17721 (string-to-number (match-string 1 s))))
17722 (setq s (replace-match "" nil t s)))
17723 (setq result (floor result))
17724 (incf result (org-hh:mm-string-to-minutes s))
17725 (if output-to-string (number-to-string result) result)))
17727 ;;;; Files
17729 (defun org-save-all-org-buffers ()
17730 "Save all Org-mode buffers without user confirmation."
17731 (interactive)
17732 (message "Saving all Org-mode buffers...")
17733 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17734 (when (featurep 'org-id) (org-id-locations-save))
17735 (message "Saving all Org-mode buffers... done"))
17737 (defun org-revert-all-org-buffers ()
17738 "Revert all Org-mode buffers.
17739 Prompt for confirmation when there are unsaved changes.
17740 Be sure you know what you are doing before letting this function
17741 overwrite your changes.
17743 This function is useful in a setup where one tracks org files
17744 with a version control system, to revert on one machine after pulling
17745 changes from another. I believe the procedure must be like this:
17747 1. M-x org-save-all-org-buffers
17748 2. Pull changes from the other machine, resolve conflicts
17749 3. M-x org-revert-all-org-buffers"
17750 (interactive)
17751 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17752 (user-error "Abort"))
17753 (save-excursion
17754 (save-window-excursion
17755 (mapc
17756 (lambda (b)
17757 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17758 (with-current-buffer b buffer-file-name))
17759 (org-pop-to-buffer-same-window b)
17760 (revert-buffer t 'no-confirm)))
17761 (buffer-list))
17762 (when (and (featurep 'org-id) org-id-track-globally)
17763 (org-id-locations-load)))))
17765 ;;;; Agenda files
17767 ;;;###autoload
17768 (defun org-switchb (&optional arg)
17769 "Switch between Org buffers.
17770 With one prefix argument, restrict available buffers to files.
17771 With two prefix arguments, restrict available buffers to agenda files.
17773 Defaults to `iswitchb' for buffer name completion.
17774 Set `org-completion-use-ido' to make it use ido instead."
17775 (interactive "P")
17776 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17777 ((equal arg '(16)) (org-buffer-list 'agenda))
17778 (t (org-buffer-list))))
17779 (org-completion-use-iswitchb org-completion-use-iswitchb)
17780 (org-completion-use-ido org-completion-use-ido))
17781 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17782 (setq org-completion-use-iswitchb t))
17783 (org-pop-to-buffer-same-window
17784 (org-icompleting-read "Org buffer: "
17785 (mapcar 'list (mapcar 'buffer-name blist))
17786 nil t))))
17788 ;;; Define some older names previously used for this functionality
17789 ;;;###autoload
17790 (defalias 'org-ido-switchb 'org-switchb)
17791 ;;;###autoload
17792 (defalias 'org-iswitchb 'org-switchb)
17794 (defun org-buffer-list (&optional predicate exclude-tmp)
17795 "Return a list of Org buffers.
17796 PREDICATE can be `export', `files' or `agenda'.
17798 export restrict the list to Export buffers.
17799 files restrict the list to buffers visiting Org files.
17800 agenda restrict the list to buffers visiting agenda files.
17802 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17803 (let* ((bfn nil)
17804 (agenda-files (and (eq predicate 'agenda)
17805 (mapcar 'file-truename (org-agenda-files t))))
17806 (filter
17807 (cond
17808 ((eq predicate 'files)
17809 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17810 ((eq predicate 'export)
17811 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17812 ((eq predicate 'agenda)
17813 (lambda (b)
17814 (with-current-buffer b
17815 (and (derived-mode-p 'org-mode)
17816 (setq bfn (buffer-file-name b))
17817 (member (file-truename bfn) agenda-files)))))
17818 (t (lambda (b) (with-current-buffer b
17819 (or (derived-mode-p 'org-mode)
17820 (string-match "\*Org .*Export"
17821 (buffer-name b)))))))))
17822 (delq nil
17823 (mapcar
17824 (lambda(b)
17825 (if (and (funcall filter b)
17826 (or (not exclude-tmp)
17827 (not (string-match "tmp" (buffer-name b)))))
17829 nil))
17830 (buffer-list)))))
17832 (defun org-agenda-files (&optional unrestricted archives)
17833 "Get the list of agenda files.
17834 Optional UNRESTRICTED means return the full list even if a restriction
17835 is currently in place.
17836 When ARCHIVES is t, include all archive files that are really being
17837 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17838 `org-agenda-archives-mode' is t."
17839 (let ((files
17840 (cond
17841 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17842 ((stringp org-agenda-files) (org-read-agenda-file-list))
17843 ((listp org-agenda-files) org-agenda-files)
17844 (t (error "Invalid value of `org-agenda-files'")))))
17845 (setq files (apply 'append
17846 (mapcar (lambda (f)
17847 (if (file-directory-p f)
17848 (directory-files
17849 f t org-agenda-file-regexp)
17850 (list f)))
17851 files)))
17852 (when org-agenda-skip-unavailable-files
17853 (setq files (delq nil
17854 (mapcar (function
17855 (lambda (file)
17856 (and (file-readable-p file) file)))
17857 files))))
17858 (when (or (eq archives t)
17859 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17860 (setq files (org-add-archive-files files)))
17861 files))
17863 (defun org-agenda-file-p (&optional file)
17864 "Return non-nil, if FILE is an agenda file.
17865 If FILE is omitted, use the file associated with the current
17866 buffer."
17867 (member (or file (buffer-file-name))
17868 (org-agenda-files t)))
17870 (defun org-edit-agenda-file-list ()
17871 "Edit the list of agenda files.
17872 Depending on setup, this either uses customize to edit the variable
17873 `org-agenda-files', or it visits the file that is holding the list. In the
17874 latter case, the buffer is set up in a way that saving it automatically kills
17875 the buffer and restores the previous window configuration."
17876 (interactive)
17877 (if (stringp org-agenda-files)
17878 (let ((cw (current-window-configuration)))
17879 (find-file org-agenda-files)
17880 (org-set-local 'org-window-configuration cw)
17881 (org-add-hook 'after-save-hook
17882 (lambda ()
17883 (set-window-configuration
17884 (prog1 org-window-configuration
17885 (kill-buffer (current-buffer))))
17886 (org-install-agenda-files-menu)
17887 (message "New agenda file list installed"))
17888 nil 'local)
17889 (message "%s" (substitute-command-keys
17890 "Edit list and finish with \\[save-buffer]")))
17891 (customize-variable 'org-agenda-files)))
17893 (defun org-store-new-agenda-file-list (list)
17894 "Set new value for the agenda file list and save it correctly."
17895 (if (stringp org-agenda-files)
17896 (let ((fe (org-read-agenda-file-list t)) b u)
17897 (while (setq b (find-buffer-visiting org-agenda-files))
17898 (kill-buffer b))
17899 (with-temp-file org-agenda-files
17900 (insert
17901 (mapconcat
17902 (lambda (f) ;; Keep un-expanded entries.
17903 (if (setq u (assoc f fe))
17904 (cdr u)
17906 list "\n")
17907 "\n")))
17908 (let ((org-mode-hook nil) (org-inhibit-startup t)
17909 (org-insert-mode-line-in-empty-file nil))
17910 (setq org-agenda-files list)
17911 (customize-save-variable 'org-agenda-files org-agenda-files))))
17913 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17914 "Read the list of agenda files from a file.
17915 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17916 filenames, used by `org-store-new-agenda-file-list' to write back
17917 un-expanded file names."
17918 (when (file-directory-p org-agenda-files)
17919 (error "`org-agenda-files' cannot be a single directory"))
17920 (when (stringp org-agenda-files)
17921 (with-temp-buffer
17922 (insert-file-contents org-agenda-files)
17923 (mapcar
17924 (lambda (f)
17925 (let ((e (expand-file-name (substitute-in-file-name f)
17926 org-directory)))
17927 (if pair-with-expansion
17928 (cons e f)
17929 e)))
17930 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17932 ;;;###autoload
17933 (defun org-cycle-agenda-files ()
17934 "Cycle through the files in `org-agenda-files'.
17935 If the current buffer visits an agenda file, find the next one in the list.
17936 If the current buffer does not, find the first agenda file."
17937 (interactive)
17938 (let* ((fs (org-agenda-files t))
17939 (files (append fs (list (car fs))))
17940 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17941 file)
17942 (unless files (user-error "No agenda files"))
17943 (catch 'exit
17944 (while (setq file (pop files))
17945 (if (equal (file-truename file) tcf)
17946 (when (car files)
17947 (find-file (car files))
17948 (throw 'exit t))))
17949 (find-file (car fs)))
17950 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17952 (defun org-agenda-file-to-front (&optional to-end)
17953 "Move/add the current file to the top of the agenda file list.
17954 If the file is not present in the list, it is added to the front. If it is
17955 present, it is moved there. With optional argument TO-END, add/move to the
17956 end of the list."
17957 (interactive "P")
17958 (let ((org-agenda-skip-unavailable-files nil)
17959 (file-alist (mapcar (lambda (x)
17960 (cons (file-truename x) x))
17961 (org-agenda-files t)))
17962 (ctf (file-truename
17963 (or buffer-file-name
17964 (user-error "Please save the current buffer to a file"))))
17965 x had)
17966 (setq x (assoc ctf file-alist) had x)
17968 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17969 (if to-end
17970 (setq file-alist (append (delq x file-alist) (list x)))
17971 (setq file-alist (cons x (delq x file-alist))))
17972 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17973 (org-install-agenda-files-menu)
17974 (message "File %s to %s of agenda file list"
17975 (if had "moved" "added") (if to-end "end" "front"))))
17977 (defun org-remove-file (&optional file)
17978 "Remove current file from the list of files in variable `org-agenda-files'.
17979 These are the files which are being checked for agenda entries.
17980 Optional argument FILE means use this file instead of the current."
17981 (interactive)
17982 (let* ((org-agenda-skip-unavailable-files nil)
17983 (file (or file buffer-file-name
17984 (user-error "Current buffer does not visit a file")))
17985 (true-file (file-truename file))
17986 (afile (abbreviate-file-name file))
17987 (files (delq nil (mapcar
17988 (lambda (x)
17989 (if (equal true-file
17990 (file-truename x))
17991 nil x))
17992 (org-agenda-files t)))))
17993 (if (not (= (length files) (length (org-agenda-files t))))
17994 (progn
17995 (org-store-new-agenda-file-list files)
17996 (org-install-agenda-files-menu)
17997 (message "Removed file: %s" afile))
17998 (message "File was not in list: %s (not removed)" afile))))
18000 (defun org-file-menu-entry (file)
18001 (vector file (list 'find-file file) t))
18003 (defun org-check-agenda-file (file)
18004 "Make sure FILE exists. If not, ask user what to do."
18005 (when (not (file-exists-p file))
18006 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18007 (abbreviate-file-name file))
18008 (let ((r (downcase (read-char-exclusive))))
18009 (cond
18010 ((equal r ?r)
18011 (org-remove-file file)
18012 (throw 'nextfile t))
18013 (t (error "Abort"))))))
18015 (defun org-get-agenda-file-buffer (file)
18016 "Get a buffer visiting FILE. If the buffer needs to be created, add
18017 it to the list of buffers which might be released later."
18018 (let ((buf (org-find-base-buffer-visiting file)))
18019 (if buf
18020 buf ; just return it
18021 ;; Make a new buffer and remember it
18022 (setq buf (find-file-noselect file))
18023 (if buf (push buf org-agenda-new-buffers))
18024 buf)))
18026 (defun org-release-buffers (blist)
18027 "Release all buffers in list, asking the user for confirmation when needed.
18028 When a buffer is unmodified, it is just killed. When modified, it is saved
18029 \(if the user agrees) and then killed."
18030 (let (buf file)
18031 (while (setq buf (pop blist))
18032 (setq file (buffer-file-name buf))
18033 (when (and (buffer-modified-p buf)
18034 file
18035 (y-or-n-p (format "Save file %s? " file)))
18036 (with-current-buffer buf (save-buffer)))
18037 (kill-buffer buf))))
18039 (defun org-agenda-prepare-buffers (files)
18040 "Create buffers for all agenda files, protect archived trees and comments."
18041 (interactive)
18042 (let ((pa '(:org-archived t))
18043 (pc '(:org-comment t))
18044 (pall '(:org-archived t :org-comment t))
18045 (inhibit-read-only t)
18046 (org-inhibit-startup org-agenda-inhibit-startup)
18047 (rea (concat ":" org-archive-tag ":"))
18048 file re pos)
18049 (setq org-tag-alist-for-agenda nil
18050 org-tag-groups-alist-for-agenda nil)
18051 (save-window-excursion
18052 (save-restriction
18053 (while (setq file (pop files))
18054 (catch 'nextfile
18055 (if (bufferp file)
18056 (set-buffer file)
18057 (org-check-agenda-file file)
18058 (set-buffer (org-get-agenda-file-buffer file)))
18059 (widen)
18060 (org-set-regexps-and-options-for-tags)
18061 (setq pos (point))
18062 (goto-char (point-min))
18063 (let ((case-fold-search t))
18064 (when (search-forward "#+setupfile" nil t)
18065 ;; Don't set all regexps and options systematically as
18066 ;; this is only run for setting agenda tags from setup
18067 ;; file
18068 (org-set-regexps-and-options)))
18069 (or (memq 'category org-agenda-ignore-drawer-properties)
18070 (org-refresh-category-properties))
18071 (or (memq 'effort org-agenda-ignore-drawer-properties)
18072 (org-refresh-properties org-effort-property 'org-effort))
18073 (or (memq 'appt org-agenda-ignore-drawer-properties)
18074 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18075 (setq org-todo-keywords-for-agenda
18076 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18077 (setq org-done-keywords-for-agenda
18078 (append org-done-keywords-for-agenda org-done-keywords))
18079 (setq org-todo-keyword-alist-for-agenda
18080 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18081 (setq org-drawers-for-agenda
18082 (append org-drawers-for-agenda org-drawers))
18083 (setq org-tag-alist-for-agenda
18084 (org-uniquify
18085 (append org-tag-alist-for-agenda
18086 org-tag-alist
18087 org-tag-persistent-alist)))
18088 (if org-group-tags
18089 (setq org-tag-groups-alist-for-agenda
18090 (org-uniquify-alist
18091 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18092 (org-with-silent-modifications
18093 (save-excursion
18094 (remove-text-properties (point-min) (point-max) pall)
18095 (when org-agenda-skip-archived-trees
18096 (goto-char (point-min))
18097 (while (re-search-forward rea nil t)
18098 (if (org-at-heading-p t)
18099 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18100 (goto-char (point-min))
18101 (setq re (format org-heading-keyword-regexp-format
18102 org-comment-string))
18103 (while (re-search-forward re nil t)
18104 (add-text-properties
18105 (match-beginning 0) (org-end-of-subtree t) pc))))
18106 (goto-char pos)))))
18107 (setq org-todo-keywords-for-agenda
18108 (org-uniquify org-todo-keywords-for-agenda))
18109 (setq org-todo-keyword-alist-for-agenda
18110 (org-uniquify org-todo-keyword-alist-for-agenda))))
18113 ;;;; CDLaTeX minor mode
18115 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18116 "Keymap for the minor `org-cdlatex-mode'.")
18118 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18119 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18120 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18121 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18122 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
18124 (defvar org-cdlatex-texmathp-advice-is-done nil
18125 "Flag remembering if we have applied the advice to texmathp already.")
18127 (define-minor-mode org-cdlatex-mode
18128 "Toggle the minor `org-cdlatex-mode'.
18129 This mode supports entering LaTeX environment and math in LaTeX fragments
18130 in Org-mode.
18131 \\{org-cdlatex-mode-map}"
18132 nil " OCDL" nil
18133 (when org-cdlatex-mode
18134 (require 'cdlatex)
18135 (run-hooks 'cdlatex-mode-hook)
18136 (cdlatex-compute-tables))
18137 (unless org-cdlatex-texmathp-advice-is-done
18138 (setq org-cdlatex-texmathp-advice-is-done t)
18139 (defadvice texmathp (around org-math-always-on activate)
18140 "Always return t in org-mode buffers.
18141 This is because we want to insert math symbols without dollars even outside
18142 the LaTeX math segments. If Orgmode thinks that point is actually inside
18143 an embedded LaTeX fragment, let texmathp do its job.
18144 \\[org-cdlatex-mode-map]"
18145 (interactive)
18146 (let (p)
18147 (cond
18148 ((not (derived-mode-p 'org-mode)) ad-do-it)
18149 ((eq this-command 'cdlatex-math-symbol)
18150 (setq ad-return-value t
18151 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18153 (let ((p (org-inside-LaTeX-fragment-p)))
18154 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18155 (setq ad-return-value t
18156 texmathp-why '("Org-mode embedded math" . 0))
18157 (if p ad-do-it)))))))))
18159 (defun turn-on-org-cdlatex ()
18160 "Unconditionally turn on `org-cdlatex-mode'."
18161 (org-cdlatex-mode 1))
18163 (defun org-try-cdlatex-tab ()
18164 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18165 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18166 - inside a LaTeX fragment, or
18167 - after the first word in a line, where an abbreviation expansion could
18168 insert a LaTeX environment."
18169 (when org-cdlatex-mode
18170 (cond
18171 ;; Before any word on the line: No expansion possible.
18172 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18173 ;; Just after first word on the line: Expand it. Make sure it
18174 ;; cannot happen on headlines, though.
18175 ((save-excursion
18176 (skip-chars-backward "a-zA-Z0-9*")
18177 (skip-chars-backward " \t")
18178 (and (bolp) (not (org-at-heading-p))))
18179 (cdlatex-tab) t)
18180 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18182 (defun org-cdlatex-underscore-caret (&optional arg)
18183 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18184 Revert to the normal definition outside of these fragments."
18185 (interactive "P")
18186 (if (org-inside-LaTeX-fragment-p)
18187 (call-interactively 'cdlatex-sub-superscript)
18188 (let (org-cdlatex-mode)
18189 (call-interactively (key-binding (vector last-input-event))))))
18191 (defun org-cdlatex-math-modify (&optional arg)
18192 "Execute `cdlatex-math-modify' in LaTeX fragments.
18193 Revert to the normal definition outside of these fragments."
18194 (interactive "P")
18195 (if (org-inside-LaTeX-fragment-p)
18196 (call-interactively 'cdlatex-math-modify)
18197 (let (org-cdlatex-mode)
18198 (call-interactively (key-binding (vector last-input-event))))))
18202 ;;;; LaTeX fragments
18204 (defvar org-latex-regexps
18205 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
18206 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
18207 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
18208 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18209 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18210 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
18211 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
18212 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
18213 "Regular expressions for matching embedded LaTeX.")
18215 (defun org-inside-LaTeX-fragment-p ()
18216 "Test if point is inside a LaTeX fragment.
18217 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18218 sequence appearing also before point.
18219 Even though the matchers for math are configurable, this function assumes
18220 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18221 delimiters are skipped when they have been removed by customization.
18222 The return value is nil, or a cons cell with the delimiter and the
18223 position of this delimiter.
18225 This function does a reasonably good job, but can locally be fooled by
18226 for example currency specifications. For example it will assume being in
18227 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18228 fragments that are properly closed, but during editing, we have to live
18229 with the uncertainty caused by missing closing delimiters. This function
18230 looks only before point, not after."
18231 (catch 'exit
18232 (let ((pos (point))
18233 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18234 (lim (progn
18235 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18236 (point)))
18237 dd-on str (start 0) m re)
18238 (goto-char pos)
18239 (when dodollar
18240 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18241 re (nth 1 (assoc "$" org-latex-regexps)))
18242 (while (string-match re str start)
18243 (cond
18244 ((= (match-end 0) (length str))
18245 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18246 ((= (match-end 0) (- (length str) 5))
18247 (throw 'exit nil))
18248 (t (setq start (match-end 0))))))
18249 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18250 (goto-char pos)
18251 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18252 (and (match-beginning 2) (throw 'exit nil))
18253 ;; count $$
18254 (while (re-search-backward "\\$\\$" lim t)
18255 (setq dd-on (not dd-on)))
18256 (goto-char pos)
18257 (if dd-on (cons "$$" m))))))
18259 (defun org-inside-latex-macro-p ()
18260 "Is point inside a LaTeX macro or its arguments?"
18261 (save-match-data
18262 (org-in-regexp
18263 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18265 (defvar org-latex-fragment-image-overlays nil
18266 "List of overlays carrying the images of latex fragments.")
18267 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18269 (defun org-remove-latex-fragment-image-overlays ()
18270 "Remove all overlays with LaTeX fragment images in current buffer."
18271 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18272 (setq org-latex-fragment-image-overlays nil))
18274 (defun org-preview-latex-fragment (&optional subtree)
18275 "Preview the LaTeX fragment at point, or all locally or globally.
18276 If the cursor is in a LaTeX fragment, create the image and overlay
18277 it over the source code. If there is no fragment at point, display
18278 all fragments in the current text, from one headline to the next. With
18279 prefix SUBTREE, display all fragments in the current subtree. With a
18280 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18281 the cursor is before the first headline,
18282 display all fragments in the buffer.
18283 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18284 (interactive "P")
18285 (unless buffer-file-name
18286 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18287 (when (display-graphic-p)
18288 (org-remove-latex-fragment-image-overlays)
18289 (save-excursion
18290 (save-restriction
18291 (let (beg end at msg)
18292 (cond
18293 ((or (equal subtree '(16))
18294 (not (save-excursion
18295 (re-search-backward org-outline-regexp-bol nil t))))
18296 (setq beg (point-min) end (point-max)
18297 msg "Creating images for buffer...%s"))
18298 ((equal subtree '(4))
18299 (org-back-to-heading)
18300 (setq beg (point) end (org-end-of-subtree t)
18301 msg "Creating images for subtree...%s"))
18303 (if (setq at (org-inside-LaTeX-fragment-p))
18304 (goto-char (max (point-min) (- (cdr at) 2)))
18305 (org-back-to-heading))
18306 (setq beg (point) end (progn (outline-next-heading) (point))
18307 msg (if at "Creating image...%s"
18308 "Creating images for entry...%s"))))
18309 (message msg "")
18310 (narrow-to-region beg end)
18311 (goto-char beg)
18312 (org-format-latex
18313 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18314 (file-name-nondirectory
18315 buffer-file-name)))
18316 default-directory 'overlays msg at 'forbuffer
18317 org-latex-create-formula-image-program)
18318 (message msg "done. Use `C-c C-c' to remove images."))))))
18320 (defun org-format-latex (prefix &optional dir overlays msg at
18321 forbuffer processing-type)
18322 "Replace LaTeX fragments with links to an image, and produce images.
18323 Some of the options can be changed using the variable
18324 `org-format-latex-options'."
18325 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18326 (let* ((prefixnodir (file-name-nondirectory prefix))
18327 (absprefix (expand-file-name prefix dir))
18328 (todir (file-name-directory absprefix))
18329 (opt org-format-latex-options)
18330 (optnew org-format-latex-options)
18331 (matchers (plist-get opt :matchers))
18332 (re-list org-latex-regexps)
18333 (cnt 0) txt hash link beg end re e checkdir
18334 string
18335 m n block-type block linkfile movefile ov)
18336 ;; Check the different regular expressions
18337 (while (setq e (pop re-list))
18338 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18339 block (if block-type "\n\n" ""))
18340 (when (member m matchers)
18341 (goto-char (point-min))
18342 (while (re-search-forward re nil t)
18343 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18344 (or (not overlays)
18345 (not (eq (get-char-property (match-beginning n)
18346 'org-overlay-type)
18347 'org-latex-overlay))))
18348 (cond
18349 ((eq processing-type 'verbatim))
18350 ((eq processing-type 'mathjax)
18351 ;; Prepare for MathJax processing.
18352 (setq string (match-string n))
18353 (when (member m '("$" "$1"))
18354 (save-excursion
18355 (delete-region (match-beginning n) (match-end n))
18356 (goto-char (match-beginning n))
18357 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18358 ((or (eq processing-type 'dvipng)
18359 (eq processing-type 'imagemagick))
18360 ;; Process to an image.
18361 (setq txt (match-string n)
18362 beg (match-beginning n) end (match-end n)
18363 cnt (1+ cnt))
18364 (let ((face (face-at-point))
18365 (fg (plist-get opt :foreground))
18366 (bg (plist-get opt :background))
18367 ;; Ensure full list is printed.
18368 print-length print-level)
18369 (when forbuffer
18370 ;; Get the colors from the face at point.
18371 (goto-char beg)
18372 (when (eq fg 'auto)
18373 (setq fg (face-attribute face :foreground nil 'default)))
18374 (when (eq bg 'auto)
18375 (setq bg (face-attribute face :background nil 'default)))
18376 (setq optnew (copy-sequence opt))
18377 (plist-put optnew :foreground fg)
18378 (plist-put optnew :background bg))
18379 (setq hash (sha1 (prin1-to-string
18380 (list org-format-latex-header
18381 org-latex-default-packages-alist
18382 org-latex-packages-alist
18383 org-format-latex-options
18384 forbuffer txt fg bg)))
18385 linkfile (format "%s_%s.png" prefix hash)
18386 movefile (format "%s_%s.png" absprefix hash)))
18387 (setq link (concat block "[[file:" linkfile "]]" block))
18388 (if msg (message msg cnt))
18389 (goto-char beg)
18390 (unless checkdir ; Ensure the directory exists.
18391 (setq checkdir t)
18392 (or (file-directory-p todir) (make-directory todir t)))
18393 (unless (file-exists-p movefile)
18394 (org-create-formula-image
18395 txt movefile optnew forbuffer processing-type))
18396 (if overlays
18397 (progn
18398 (mapc (lambda (o)
18399 (if (eq (overlay-get o 'org-overlay-type)
18400 'org-latex-overlay)
18401 (delete-overlay o)))
18402 (overlays-in beg end))
18403 (setq ov (make-overlay beg end))
18404 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18405 (if (featurep 'xemacs)
18406 (progn
18407 (overlay-put ov 'invisible t)
18408 (overlay-put
18409 ov 'end-glyph
18410 (make-glyph (vector 'png :file movefile))))
18411 (overlay-put
18412 ov 'display
18413 (list 'image :type 'png :file movefile :ascent 'center)))
18414 (push ov org-latex-fragment-image-overlays)
18415 (goto-char end))
18416 (delete-region beg end)
18417 (insert (org-add-props link
18418 (list 'org-latex-src
18419 (replace-regexp-in-string
18420 "\"" "" txt)
18421 'org-latex-src-embed-type
18422 (if block-type 'paragraph 'character))))))
18423 ((eq processing-type 'mathml)
18424 ;; Process to MathML
18425 (unless (save-match-data (org-format-latex-mathml-available-p))
18426 (user-error "LaTeX to MathML converter not configured"))
18427 (setq txt (match-string n)
18428 beg (match-beginning n) end (match-end n)
18429 cnt (1+ cnt))
18430 (if msg (message msg cnt))
18431 (goto-char beg)
18432 (delete-region beg end)
18433 (insert (org-format-latex-as-mathml
18434 txt block-type prefix dir)))
18436 (error "Unknown conversion type %s for LaTeX fragments"
18437 processing-type)))))))))
18439 (defun org-create-math-formula (latex-frag &optional mathml-file)
18440 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18441 Use `org-latex-to-mathml-convert-command'. If the conversion is
18442 sucessful, return the portion between \"<math...> </math>\"
18443 elements otherwise return nil. When MATHML-FILE is specified,
18444 write the results in to that file. When invoked as an
18445 interactive command, prompt for LATEX-FRAG, with initial value
18446 set to the current active region and echo the results for user
18447 inspection."
18448 (interactive (list (let ((frag (when (org-region-active-p)
18449 (buffer-substring-no-properties
18450 (region-beginning) (region-end)))))
18451 (read-string "LaTeX Fragment: " frag nil frag))))
18452 (unless latex-frag (error "Invalid LaTeX fragment"))
18453 (let* ((tmp-in-file (file-relative-name
18454 (make-temp-name (expand-file-name "ltxmathml-in"))))
18455 (ignore (write-region latex-frag nil tmp-in-file))
18456 (tmp-out-file (file-relative-name
18457 (make-temp-name (expand-file-name "ltxmathml-out"))))
18458 (cmd (format-spec
18459 org-latex-to-mathml-convert-command
18460 `((?j . ,(shell-quote-argument
18461 (expand-file-name org-latex-to-mathml-jar-file)))
18462 (?I . ,(shell-quote-argument tmp-in-file))
18463 (?o . ,(shell-quote-argument tmp-out-file)))))
18464 mathml shell-command-output)
18465 (when (org-called-interactively-p 'any)
18466 (unless (org-format-latex-mathml-available-p)
18467 (user-error "LaTeX to MathML converter not configured")))
18468 (message "Running %s" cmd)
18469 (setq shell-command-output (shell-command-to-string cmd))
18470 (setq mathml
18471 (when (file-readable-p tmp-out-file)
18472 (with-current-buffer (find-file-noselect tmp-out-file t)
18473 (goto-char (point-min))
18474 (when (re-search-forward
18475 (concat
18476 (regexp-quote
18477 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18478 "\\(.\\|\n\\)*"
18479 (regexp-quote "</math>")) nil t)
18480 (prog1 (match-string 0) (kill-buffer))))))
18481 (cond
18482 (mathml
18483 (setq mathml
18484 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18485 (when mathml-file
18486 (write-region mathml nil mathml-file))
18487 (when (org-called-interactively-p 'any)
18488 (message mathml)))
18489 ((message "LaTeX to MathML conversion failed")
18490 (message shell-command-output)))
18491 (delete-file tmp-in-file)
18492 (when (file-exists-p tmp-out-file)
18493 (delete-file tmp-out-file))
18494 mathml))
18496 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18497 prefix &optional dir)
18498 "Use `org-create-math-formula' but check local cache first."
18499 (let* ((absprefix (expand-file-name prefix dir))
18500 (print-length nil) (print-level nil)
18501 (formula-id (concat
18502 "formula-"
18503 (sha1
18504 (prin1-to-string
18505 (list latex-frag
18506 org-latex-to-mathml-convert-command)))))
18507 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18508 (formula-cache-dir (file-name-directory formula-cache)))
18510 (unless (file-directory-p formula-cache-dir)
18511 (make-directory formula-cache-dir t))
18513 (unless (file-exists-p formula-cache)
18514 (org-create-math-formula latex-frag formula-cache))
18516 (if (file-exists-p formula-cache)
18517 ;; Successful conversion. Return the link to MathML file.
18518 (org-add-props
18519 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18520 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18521 'org-latex-src-embed-type (if latex-frag-type
18522 'paragraph 'character)))
18523 ;; Failed conversion. Return the LaTeX fragment verbatim
18524 latex-frag)))
18526 (defun org-create-formula-image (string tofile options buffer &optional type)
18527 "Create an image from LaTeX source using dvipng or convert.
18528 This function calls either `org-create-formula-image-with-dvipng'
18529 or `org-create-formula-image-with-imagemagick' depending on the
18530 value of `org-latex-create-formula-image-program' or on the value
18531 of the optional TYPE variable.
18533 Note: ultimately these two function should be combined as they
18534 share a good deal of logic."
18535 (org-check-external-command
18536 "latex" "needed to convert LaTeX fragments to images")
18537 (funcall
18538 (case (or type org-latex-create-formula-image-program)
18539 ('dvipng
18540 (org-check-external-command
18541 "dvipng" "needed to convert LaTeX fragments to images")
18542 #'org-create-formula-image-with-dvipng)
18543 ('imagemagick
18544 (org-check-external-command
18545 "convert" "you need to install imagemagick")
18546 #'org-create-formula-image-with-imagemagick)
18547 (t (error
18548 "Invalid value of `org-latex-create-formula-image-program'")))
18549 string tofile options buffer))
18551 (declare-function org-export-get-backend "ox" (name))
18552 (declare-function org-export--get-global-options "ox" (&optional backend))
18553 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18554 (declare-function org-latex-guess-inputenc "ox-latex" (header))
18555 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
18556 (defun org-create-formula--latex-header ()
18557 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18558 (let ((info (org-combine-plists (org-export--get-global-options
18559 (org-export-get-backend 'latex))
18560 (org-export--get-inbuffer-options
18561 (org-export-get-backend 'latex)))))
18562 (org-latex-guess-babel-language
18563 (org-latex-guess-inputenc
18564 (org-splice-latex-header
18565 org-format-latex-header
18566 org-latex-default-packages-alist
18567 org-latex-packages-alist t
18568 (plist-get info :latex-header)))
18569 info)))
18571 ;; This function borrows from Ganesh Swami's latex2png.el
18572 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18573 "This calls dvipng."
18574 (require 'ox-latex)
18575 (let* ((tmpdir (if (featurep 'xemacs)
18576 (temp-directory)
18577 temporary-file-directory))
18578 (texfilebase (make-temp-name
18579 (expand-file-name "orgtex" tmpdir)))
18580 (texfile (concat texfilebase ".tex"))
18581 (dvifile (concat texfilebase ".dvi"))
18582 (pngfile (concat texfilebase ".png"))
18583 (fnh (if (featurep 'xemacs)
18584 (font-height (face-font 'default))
18585 (face-attribute 'default :height nil)))
18586 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18587 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18588 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18589 "Black"))
18590 (bg (or (plist-get options (if buffer :background :html-background))
18591 "Transparent")))
18592 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18593 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18594 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18595 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18596 (let ((latex-header (org-create-formula--latex-header)))
18597 (with-temp-file texfile
18598 (insert latex-header)
18599 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18600 (let ((dir default-directory))
18601 (condition-case nil
18602 (progn
18603 (cd tmpdir)
18604 (call-process "latex" nil nil nil texfile))
18605 (error nil))
18606 (cd dir))
18607 (if (not (file-exists-p dvifile))
18608 (progn (message "Failed to create dvi file from %s" texfile) nil)
18609 (condition-case nil
18610 (if (featurep 'xemacs)
18611 (call-process "dvipng" nil nil nil
18612 "-fg" fg "-bg" bg
18613 "-T" "tight"
18614 "-o" pngfile
18615 dvifile)
18616 (call-process "dvipng" nil nil nil
18617 "-fg" fg "-bg" bg
18618 "-D" dpi
18619 ;;"-x" scale "-y" scale
18620 "-T" "tight"
18621 "-o" pngfile
18622 dvifile))
18623 (error nil))
18624 (if (not (file-exists-p pngfile))
18625 (if org-format-latex-signal-error
18626 (error "Failed to create png file from %s" texfile)
18627 (message "Failed to create png file from %s" texfile)
18628 nil)
18629 ;; Use the requested file name and clean up
18630 (copy-file pngfile tofile 'replace)
18631 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18632 (if (file-exists-p (concat texfilebase e))
18633 (delete-file (concat texfilebase e))))
18634 pngfile))))
18636 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18637 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18638 "This calls convert, which is included into imagemagick."
18639 (require 'ox-latex)
18640 (let* ((tmpdir (if (featurep 'xemacs)
18641 (temp-directory)
18642 temporary-file-directory))
18643 (texfilebase (make-temp-name
18644 (expand-file-name "orgtex" tmpdir)))
18645 (texfile (concat texfilebase ".tex"))
18646 (pdffile (concat texfilebase ".pdf"))
18647 (pngfile (concat texfilebase ".png"))
18648 (fnh (if (featurep 'xemacs)
18649 (font-height (face-font 'default))
18650 (face-attribute 'default :height nil)))
18651 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18652 (dpi (number-to-string (* scale (floor (if buffer fnh 120.)))))
18653 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18654 "black"))
18655 (bg (or (plist-get options (if buffer :background :html-background))
18656 "white")))
18657 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18658 (setq fg (org-latex-color-format fg)))
18659 (if (eq bg 'default) (setq bg (org-latex-color :background))
18660 (setq bg (org-latex-color-format
18661 (if (string= bg "Transparent") "white" bg))))
18662 (let ((latex-header (org-create-formula--latex-header)))
18663 (with-temp-file texfile
18664 (insert latex-header)
18665 (insert "\n\\begin{document}\n"
18666 "\\definecolor{fg}{rgb}{" fg "}\n"
18667 "\\definecolor{bg}{rgb}{" bg "}\n"
18668 "\n\\pagecolor{bg}\n"
18669 "\n{\\color{fg}\n"
18670 string
18671 "\n}\n"
18672 "\n\\end{document}\n")))
18673 (org-latex-compile texfile t)
18674 (if (not (file-exists-p pdffile))
18675 (progn (message "Failed to create pdf file from %s" texfile) nil)
18676 (condition-case nil
18677 (if (featurep 'xemacs)
18678 (call-process "convert" nil nil nil
18679 "-density" "96"
18680 "-trim"
18681 "-antialias"
18682 pdffile
18683 "-quality" "100"
18684 ;; "-sharpen" "0x1.0"
18685 pngfile)
18686 (call-process "convert" nil nil nil
18687 "-density" dpi
18688 "-trim"
18689 "-antialias"
18690 pdffile
18691 "-quality" "100"
18692 ;; "-sharpen" "0x1.0"
18693 pngfile))
18694 (error nil))
18695 (if (not (file-exists-p pngfile))
18696 (if org-format-latex-signal-error
18697 (error "Failed to create png file from %s" texfile)
18698 (message "Failed to create png file from %s" texfile)
18699 nil)
18700 ;; Use the requested file name and clean up
18701 (copy-file pngfile tofile 'replace)
18702 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18703 (if (file-exists-p (concat texfilebase e))
18704 (delete-file (concat texfilebase e))))
18705 pngfile))))
18707 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18708 "Fill a LaTeX header template TPL.
18709 In the template, the following place holders will be recognized:
18711 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18712 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18713 [PACKAGES] \\usepackage statements for PKG
18714 [NO-PACKAGES] do not include PKG
18715 [EXTRA] the string EXTRA
18716 [NO-EXTRA] do not include EXTRA
18718 For backward compatibility, if both the positive and the negative place
18719 holder is missing, the positive one (without the \"NO-\") will be
18720 assumed to be present at the end of the template.
18721 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18722 EXTRA is a string.
18723 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18724 (let (rpl (end ""))
18725 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18726 (setq rpl (if (or (match-end 1) (not def-pkg))
18727 "" (org-latex-packages-to-string def-pkg snippets-p t))
18728 tpl (replace-match rpl t t tpl))
18729 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18731 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18732 (setq rpl (if (or (match-end 1) (not pkg))
18733 "" (org-latex-packages-to-string pkg snippets-p t))
18734 tpl (replace-match rpl t t tpl))
18735 (if pkg (setq end
18736 (concat end "\n"
18737 (org-latex-packages-to-string pkg snippets-p)))))
18739 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18740 (setq rpl (if (or (match-end 1) (not extra))
18741 "" (concat extra "\n"))
18742 tpl (replace-match rpl t t tpl))
18743 (if (and extra (string-match "\\S-" extra))
18744 (setq end (concat end "\n" extra))))
18746 (if (string-match "\\S-" end)
18747 (concat tpl "\n" end)
18748 tpl)))
18750 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18751 "Turn an alist of packages into a string with the \\usepackage macros."
18752 (setq pkg (mapconcat (lambda(p)
18753 (cond
18754 ((stringp p) p)
18755 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18756 (format "%% Package %s omitted" (cadr p)))
18757 ((equal "" (car p))
18758 (format "\\usepackage{%s}" (cadr p)))
18760 (format "\\usepackage[%s]{%s}"
18761 (car p) (cadr p)))))
18763 "\n"))
18764 (if newline (concat pkg "\n") pkg))
18766 (defun org-dvipng-color (attr)
18767 "Return a RGB color specification for dvipng."
18768 (apply 'format "rgb %s %s %s"
18769 (mapcar 'org-normalize-color
18770 (if (featurep 'xemacs)
18771 (color-rgb-components
18772 (face-property 'default
18773 (cond ((eq attr :foreground) 'foreground)
18774 ((eq attr :background) 'background))))
18775 (color-values (face-attribute 'default attr nil))))))
18777 (defun org-dvipng-color-format (color-name)
18778 "Convert COLOR-NAME to a RGB color value for dvipng."
18779 (apply 'format "rgb %s %s %s"
18780 (mapcar 'org-normalize-color
18781 (color-values color-name))))
18783 (defun org-latex-color (attr)
18784 "Return a RGB color for the LaTeX color package."
18785 (apply 'format "%s,%s,%s"
18786 (mapcar 'org-normalize-color
18787 (if (featurep 'xemacs)
18788 (color-rgb-components
18789 (face-property 'default
18790 (cond ((eq attr :foreground) 'foreground)
18791 ((eq attr :background) 'background))))
18792 (color-values (face-attribute 'default attr nil))))))
18794 (defun org-latex-color-format (color-name)
18795 "Convert COLOR-NAME to a RGB color value."
18796 (apply 'format "%s,%s,%s"
18797 (mapcar 'org-normalize-color
18798 (color-values color-name))))
18800 (defun org-normalize-color (value)
18801 "Return string to be used as color value for an RGB component."
18802 (format "%g" (/ value 65535.0)))
18806 ;; Image display
18808 (defvar org-inline-image-overlays nil)
18809 (make-variable-buffer-local 'org-inline-image-overlays)
18811 (defun org-toggle-inline-images (&optional include-linked)
18812 "Toggle the display of inline images.
18813 INCLUDE-LINKED is passed to `org-display-inline-images'."
18814 (interactive "P")
18815 (if org-inline-image-overlays
18816 (progn
18817 (org-remove-inline-images)
18818 (message "Inline image display turned off"))
18819 (org-display-inline-images include-linked)
18820 (if (and (org-called-interactively-p)
18821 org-inline-image-overlays)
18822 (message "%d images displayed inline"
18823 (length org-inline-image-overlays))
18824 (message "No images to display inline"))))
18826 (defun org-redisplay-inline-images ()
18827 "Refresh the display of inline images."
18828 (interactive)
18829 (if (not org-inline-image-overlays)
18830 (org-toggle-inline-images)
18831 (org-toggle-inline-images)
18832 (org-toggle-inline-images)))
18834 (defun org-display-inline-images (&optional include-linked refresh beg end)
18835 "Display inline images.
18836 Normally only links without a description part are inlined, because this
18837 is how it will work for export. When INCLUDE-LINKED is set, also links
18838 with a description part will be inlined. This can be nice for a quick
18839 look at those images, but it does not reflect what exported files will look
18840 like.
18841 When REFRESH is set, refresh existing images between BEG and END.
18842 This will create new image displays only if necessary.
18843 BEG and END default to the buffer boundaries."
18844 (interactive "P")
18845 (when (display-graphic-p)
18846 (unless refresh
18847 (org-remove-inline-images)
18848 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18849 (save-excursion
18850 (save-restriction
18851 (widen)
18852 (setq beg (or beg (point-min)) end (or end (point-max)))
18853 (goto-char beg)
18854 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18855 (substring (org-image-file-name-regexp) 0 -2)
18856 "\\)\\]" (if include-linked "" "\\]")))
18857 (case-fold-search t)
18858 old file ov img type attrwidth width)
18859 (while (re-search-forward re end t)
18860 (setq old (get-char-property-and-overlay (match-beginning 1)
18861 'org-image-overlay)
18862 file (expand-file-name
18863 (concat (or (match-string 3) "") (match-string 4))))
18864 (when (image-type-available-p 'imagemagick)
18865 (setq attrwidth (if (or (listp org-image-actual-width)
18866 (null org-image-actual-width))
18867 (save-excursion
18868 (save-match-data
18869 (when (re-search-backward
18870 "#\\+attr.*:width[ \t]+\\([^ ]+\\)"
18871 (save-excursion
18872 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18873 (string-to-number (match-string 1))))))
18874 width (cond ((eq org-image-actual-width t) nil)
18875 ((null org-image-actual-width) attrwidth)
18876 ((numberp org-image-actual-width)
18877 org-image-actual-width)
18878 ((listp org-image-actual-width)
18879 (or attrwidth (car org-image-actual-width))))
18880 type (if width 'imagemagick)))
18881 (when (file-exists-p file)
18882 (if (and (car-safe old) refresh)
18883 (image-refresh (overlay-get (cdr old) 'display))
18884 (setq img (save-match-data (create-image file type nil :width width)))
18885 (when img
18886 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18887 (overlay-put ov 'display img)
18888 (overlay-put ov 'face 'default)
18889 (overlay-put ov 'org-image-overlay t)
18890 (overlay-put ov 'modification-hooks
18891 (list 'org-display-inline-remove-overlay))
18892 (push ov org-inline-image-overlays))))))))))
18894 (define-obsolete-function-alias
18895 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18897 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18898 "Remove inline-display overlay if a corresponding region is modified."
18899 (let ((inhibit-modification-hooks t))
18900 (when (and ov after)
18901 (delete ov org-inline-image-overlays)
18902 (delete-overlay ov))))
18904 (defun org-remove-inline-images ()
18905 "Remove inline display of images."
18906 (interactive)
18907 (mapc 'delete-overlay org-inline-image-overlays)
18908 (setq org-inline-image-overlays nil))
18910 ;;;; Key bindings
18912 ;; Outline functions from `outline-mode-prefix-map'
18913 ;; that can be remapped in Org:
18914 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18915 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18916 (define-key org-mode-map [remap outline-forward-same-level]
18917 'org-forward-heading-same-level)
18918 (define-key org-mode-map [remap outline-backward-same-level]
18919 'org-backward-heading-same-level)
18920 (define-key org-mode-map [remap show-branches]
18921 'org-kill-note-or-show-branches)
18922 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18923 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18924 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18926 ;; Outline functions from `outline-mode-prefix-map' that can not
18927 ;; be remapped in Org:
18929 ;; - the column "key binding" shows whether the Outline function is still
18930 ;; available in Org mode on the same key that it has been bound to in
18931 ;; Outline mode:
18932 ;; - "overridden": key used for a different functionality in Org mode
18933 ;; - else: key still bound to the same Outline function in Org mode
18935 ;; | Outline function | key binding | Org replacement |
18936 ;; |------------------------------------+-------------+-----------------------|
18937 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18938 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18939 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18940 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18941 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18942 ;; | `show-entry' | overridden | no replacement |
18943 ;; | `show-children' | `C-c C-i' | visibility cycling |
18944 ;; | `show-branches' | `C-c C-k' | still same function |
18945 ;; | `show-subtree' | overridden | visibility cycling |
18946 ;; | `show-all' | overridden | no replacement |
18947 ;; | `hide-subtree' | overridden | visibility cycling |
18948 ;; | `hide-body' | overridden | no replacement |
18949 ;; | `hide-entry' | overridden | visibility cycling |
18950 ;; | `hide-leaves' | overridden | no replacement |
18951 ;; | `hide-sublevels' | overridden | no replacement |
18952 ;; | `hide-other' | overridden | no replacement |
18954 ;; Make `C-c C-x' a prefix key
18955 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18957 ;; TAB key with modifiers
18958 (org-defkey org-mode-map "\C-i" 'org-cycle)
18959 (org-defkey org-mode-map [(tab)] 'org-cycle)
18960 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18961 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18962 ;; The following line is necessary under Suse GNU/Linux
18963 (unless (featurep 'xemacs)
18964 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18965 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18966 (define-key org-mode-map [backtab] 'org-shifttab)
18968 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18969 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18970 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18972 ;; Cursor keys with modifiers
18973 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18974 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18975 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18976 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18978 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18979 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18980 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18981 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18983 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18984 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18985 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18986 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18988 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18989 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18990 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18991 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18993 ;; Babel keys
18994 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18995 (mapc (lambda (pair)
18996 (define-key org-babel-map (car pair) (cdr pair)))
18997 org-babel-key-bindings)
18999 ;;; Extra keys for tty access.
19000 ;; We only set them when really needed because otherwise the
19001 ;; menus don't show the simple keys
19003 (when (or org-use-extra-keys
19004 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19005 (not window-system))
19006 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19007 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19008 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19009 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19010 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19011 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19012 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19013 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19014 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19015 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19016 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19017 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19018 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19019 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19020 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19021 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19022 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19023 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19024 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19025 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19026 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19027 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19028 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
19029 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19030 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19031 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19032 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19033 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19035 ;; All the other keys
19037 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
19038 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19039 (if (boundp 'narrow-map)
19040 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19041 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19042 (if (boundp 'narrow-map)
19043 (org-defkey narrow-map "b" 'org-narrow-to-block)
19044 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19045 (if (boundp 'narrow-map)
19046 (org-defkey narrow-map "e" 'org-narrow-to-element)
19047 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19048 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19049 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19050 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19051 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19052 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19053 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19054 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19055 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19056 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19057 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19058 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
19059 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19060 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19061 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19062 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19063 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19064 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19065 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19066 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19067 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19068 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19069 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19070 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19071 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19072 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19073 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19074 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19075 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19076 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19077 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19078 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19079 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19080 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19081 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19082 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19083 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19084 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19085 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19086 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19087 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19088 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19089 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19090 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19091 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19092 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19093 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19094 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19095 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19096 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19097 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19098 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19099 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19100 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19101 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19102 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19103 (org-defkey org-mode-map "\C-c^" 'org-sort)
19104 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19105 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19106 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19107 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19108 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19109 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19110 (org-defkey org-mode-map "\C-m" 'org-return)
19111 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19112 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19113 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19114 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19115 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19116 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19117 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19118 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19119 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19120 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19121 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19122 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19123 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19124 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19125 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
19126 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19127 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19128 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19129 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19130 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19131 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19132 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19133 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19135 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19136 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19137 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19139 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19140 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19141 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19142 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19143 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19144 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19145 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19146 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19147 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19148 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19149 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
19150 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19151 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19152 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19153 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19154 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19155 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19156 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19157 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19158 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19159 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19160 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19161 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19163 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19164 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19165 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19166 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19167 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19169 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19171 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19173 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19174 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19176 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19179 (when (featurep 'xemacs)
19180 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19183 (defconst org-speed-commands-default
19185 ("Outline Navigation")
19186 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19187 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19188 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19189 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19190 ("F" . org-next-block)
19191 ("B" . org-previous-block)
19192 ("u" . (org-speed-move-safe 'outline-up-heading))
19193 ("j" . org-goto)
19194 ("g" . (org-refile t))
19195 ("Outline Visibility")
19196 ("c" . org-cycle)
19197 ("C" . org-shifttab)
19198 (" " . org-display-outline-path)
19199 ("s" . org-narrow-to-subtree)
19200 ("=" . org-columns)
19201 ("Outline Structure Editing")
19202 ("U" . org-shiftmetaup)
19203 ("D" . org-shiftmetadown)
19204 ("r" . org-metaright)
19205 ("l" . org-metaleft)
19206 ("R" . org-shiftmetaright)
19207 ("L" . org-shiftmetaleft)
19208 ("i" . (progn (forward-char 1) (call-interactively
19209 'org-insert-heading-respect-content)))
19210 ("^" . org-sort)
19211 ("w" . org-refile)
19212 ("a" . org-archive-subtree-default-with-confirmation)
19213 ("@" . org-mark-subtree)
19214 ("#" . org-toggle-comment)
19215 ("Clock Commands")
19216 ("I" . org-clock-in)
19217 ("O" . org-clock-out)
19218 ("Meta Data Editing")
19219 ("t" . org-todo)
19220 ("," . (org-priority))
19221 ("0" . (org-priority ?\ ))
19222 ("1" . (org-priority ?A))
19223 ("2" . (org-priority ?B))
19224 ("3" . (org-priority ?C))
19225 (":" . org-set-tags-command)
19226 ("e" . org-set-effort)
19227 ("E" . org-inc-effort)
19228 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19229 (org-entry-put (point) "APPT_WARNTIME" m)))
19230 ("Agenda Views etc")
19231 ("v" . org-agenda)
19232 ("/" . org-sparse-tree)
19233 ("Misc")
19234 ("o" . org-open-at-point)
19235 ("?" . org-speed-command-help)
19236 ("<" . (org-agenda-set-restriction-lock 'subtree))
19237 (">" . (org-agenda-remove-restriction-lock))
19239 "The default speed commands.")
19241 (defun org-print-speed-command (e)
19242 (if (> (length (car e)) 1)
19243 (progn
19244 (princ "\n")
19245 (princ (car e))
19246 (princ "\n")
19247 (princ (make-string (length (car e)) ?-))
19248 (princ "\n"))
19249 (princ (car e))
19250 (princ " ")
19251 (if (symbolp (cdr e))
19252 (princ (symbol-name (cdr e)))
19253 (prin1 (cdr e)))
19254 (princ "\n")))
19256 (defun org-speed-command-help ()
19257 "Show the available speed commands."
19258 (interactive)
19259 (if (not org-use-speed-commands)
19260 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19261 (with-output-to-temp-buffer "*Help*"
19262 (princ "User-defined Speed commands\n===========================\n")
19263 (mapc 'org-print-speed-command org-speed-commands-user)
19264 (princ "\n")
19265 (princ "Built-in Speed commands\n=======================\n")
19266 (mapc 'org-print-speed-command org-speed-commands-default))
19267 (with-current-buffer "*Help*"
19268 (setq truncate-lines t))))
19270 (defun org-speed-move-safe (cmd)
19271 "Execute CMD, but make sure that the cursor always ends up in a headline.
19272 If not, return to the original position and throw an error."
19273 (interactive)
19274 (let ((pos (point)))
19275 (call-interactively cmd)
19276 (unless (and (bolp) (org-at-heading-p))
19277 (goto-char pos)
19278 (error "Boundary reached while executing %s" cmd))))
19280 (defvar org-self-insert-command-undo-counter 0)
19282 (defvar org-table-auto-blank-field) ; defined in org-table.el
19283 (defvar org-speed-command nil)
19285 (define-obsolete-function-alias
19286 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19288 (defun org-speed-command-activate (keys)
19289 "Hook for activating single-letter speed commands.
19290 `org-speed-commands-default' specifies a minimal command set.
19291 Use `org-speed-commands-user' for further customization."
19292 (when (or (and (bolp) (looking-at org-outline-regexp))
19293 (and (functionp org-use-speed-commands)
19294 (funcall org-use-speed-commands)))
19295 (cdr (assoc keys (append org-speed-commands-user
19296 org-speed-commands-default)))))
19298 (define-obsolete-function-alias
19299 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19301 (defun org-babel-speed-command-activate (keys)
19302 "Hook for activating single-letter code block commands."
19303 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19304 (cdr (assoc keys org-babel-key-bindings))))
19306 (defcustom org-speed-command-hook
19307 '(org-speed-command-default-hook org-babel-speed-command-hook)
19308 "Hook for activating speed commands at strategic locations.
19309 Hook functions are called in sequence until a valid handler is
19310 found.
19312 Each hook takes a single argument, a user-pressed command key
19313 which is also a `self-insert-command' from the global map.
19315 Within the hook, examine the cursor position and the command key
19316 and return nil or a valid handler as appropriate. Handler could
19317 be one of an interactive command, a function, or a form.
19319 Set `org-use-speed-commands' to non-nil value to enable this
19320 hook. The default setting is `org-speed-command-activate'."
19321 :group 'org-structure
19322 :version "24.1"
19323 :type 'hook)
19325 (defun org-self-insert-command (N)
19326 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19327 If the cursor is in a table looking at whitespace, the whitespace is
19328 overwritten, and the table is not marked as requiring realignment."
19329 (interactive "p")
19330 (org-check-before-invisible-edit 'insert)
19331 (cond
19332 ((and org-use-speed-commands
19333 (setq org-speed-command
19334 (run-hook-with-args-until-success
19335 'org-speed-command-hook (this-command-keys))))
19336 (cond
19337 ((commandp org-speed-command)
19338 (setq this-command org-speed-command)
19339 (call-interactively org-speed-command))
19340 ((functionp org-speed-command)
19341 (funcall org-speed-command))
19342 ((and org-speed-command (listp org-speed-command))
19343 (eval org-speed-command))
19344 (t (let (org-use-speed-commands)
19345 (call-interactively 'org-self-insert-command)))))
19346 ((and
19347 (org-table-p)
19348 (progn
19349 ;; check if we blank the field, and if that triggers align
19350 (and (featurep 'org-table) org-table-auto-blank-field
19351 (member last-command
19352 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19353 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19354 ;; got extra space, this field does not determine column width
19355 (let (org-table-may-need-update) (org-table-blank-field))
19356 ;; no extra space, this field may determine column width
19357 (org-table-blank-field)))
19359 (eq N 1)
19360 (looking-at "[^|\n]* |"))
19361 (let (org-table-may-need-update)
19362 (goto-char (1- (match-end 0)))
19363 (backward-delete-char 1)
19364 (goto-char (match-beginning 0))
19365 (self-insert-command N)))
19367 (setq org-table-may-need-update t)
19368 (self-insert-command N)
19369 (org-fix-tags-on-the-fly)
19370 (if org-self-insert-cluster-for-undo
19371 (if (not (eq last-command 'org-self-insert-command))
19372 (setq org-self-insert-command-undo-counter 1)
19373 (if (>= org-self-insert-command-undo-counter 20)
19374 (setq org-self-insert-command-undo-counter 1)
19375 (and (> org-self-insert-command-undo-counter 0)
19376 buffer-undo-list (listp buffer-undo-list)
19377 (not (cadr buffer-undo-list)) ; remove nil entry
19378 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19379 (setq org-self-insert-command-undo-counter
19380 (1+ org-self-insert-command-undo-counter))))))))
19382 (defun org-check-before-invisible-edit (kind)
19383 "Check is editing if kind KIND would be dangerous with invisible text around.
19384 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19385 ;; First, try to get out of here as quickly as possible, to reduce overhead
19386 (if (and org-catch-invisible-edits
19387 (or (not (boundp 'visible-mode)) (not visible-mode))
19388 (or (get-char-property (point) 'invisible)
19389 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19390 ;; OK, we need to take a closer look
19391 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19392 (invisible-before-point (if (bobp) nil (get-char-property
19393 (1- (point)) 'invisible)))
19394 (border-and-ok-direction
19396 ;; Check if we are acting predictably before invisible text
19397 (and invisible-at-point (not invisible-before-point)
19398 (memq kind '(insert delete-backward)))
19399 ;; Check if we are acting predictably after invisible text
19400 ;; This works not well, and I have turned it off. It seems
19401 ;; better to always show and stop after invisible text.
19402 ;; (and (not invisible-at-point) invisible-before-point
19403 ;; (memq kind '(insert delete)))
19405 (when (or (memq invisible-at-point '(outline org-hide-block t))
19406 (memq invisible-before-point '(outline org-hide-block t)))
19407 (if (eq org-catch-invisible-edits 'error)
19408 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19409 (if (and org-custom-properties-overlays
19410 (y-or-n-p "Display invisible properties in this buffer? "))
19411 (org-toggle-custom-properties-visibility)
19412 ;; Make the area visible
19413 (save-excursion
19414 (if invisible-before-point
19415 (goto-char (previous-single-char-property-change
19416 (point) 'invisible)))
19417 (org-cycle))
19418 (cond
19419 ((eq org-catch-invisible-edits 'show)
19420 ;; That's it, we do the edit after showing
19421 (message
19422 "Unfolding invisible region around point before editing")
19423 (sit-for 1))
19424 ((and (eq org-catch-invisible-edits 'smart)
19425 border-and-ok-direction)
19426 (message "Unfolding invisible region around point before editing"))
19428 ;; Don't do the edit, make the user repeat it in full visibility
19429 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19431 (defun org-fix-tags-on-the-fly ()
19432 (when (and (equal (char-after (point-at-bol)) ?*)
19433 (org-at-heading-p))
19434 (org-align-tags-here org-tags-column)))
19436 (defun org-delete-backward-char (N)
19437 "Like `delete-backward-char', insert whitespace at field end in tables.
19438 When deleting backwards, in tables this function will insert whitespace in
19439 front of the next \"|\" separator, to keep the table aligned. The table will
19440 still be marked for re-alignment if the field did fill the entire column,
19441 because, in this case the deletion might narrow the column."
19442 (interactive "p")
19443 (save-match-data
19444 (org-check-before-invisible-edit 'delete-backward)
19445 (if (and (org-table-p)
19446 (eq N 1)
19447 (string-match "|" (buffer-substring (point-at-bol) (point)))
19448 (looking-at ".*?|"))
19449 (let ((pos (point))
19450 (noalign (looking-at "[^|\n\r]* |"))
19451 (c org-table-may-need-update))
19452 (backward-delete-char N)
19453 (if (not overwrite-mode)
19454 (progn
19455 (skip-chars-forward "^|")
19456 (insert " ")
19457 (goto-char (1- pos))))
19458 ;; noalign: if there were two spaces at the end, this field
19459 ;; does not determine the width of the column.
19460 (if noalign (setq org-table-may-need-update c)))
19461 (backward-delete-char N)
19462 (org-fix-tags-on-the-fly))))
19464 (defun org-delete-char (N)
19465 "Like `delete-char', but insert whitespace at field end in tables.
19466 When deleting characters, in tables this function will insert whitespace in
19467 front of the next \"|\" separator, to keep the table aligned. The table will
19468 still be marked for re-alignment if the field did fill the entire column,
19469 because, in this case the deletion might narrow the column."
19470 (interactive "p")
19471 (save-match-data
19472 (org-check-before-invisible-edit 'delete)
19473 (if (and (org-table-p)
19474 (not (bolp))
19475 (not (= (char-after) ?|))
19476 (eq N 1))
19477 (if (looking-at ".*?|")
19478 (let ((pos (point))
19479 (noalign (looking-at "[^|\n\r]* |"))
19480 (c org-table-may-need-update))
19481 (replace-match
19482 (concat (substring (match-string 0) 1 -1) " |") nil t)
19483 (goto-char pos)
19484 ;; noalign: if there were two spaces at the end, this field
19485 ;; does not determine the width of the column.
19486 (if noalign (setq org-table-may-need-update c)))
19487 (delete-char N))
19488 (delete-char N)
19489 (org-fix-tags-on-the-fly))))
19491 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19492 (put 'org-self-insert-command 'delete-selection t)
19493 (put 'orgtbl-self-insert-command 'delete-selection t)
19494 (put 'org-delete-char 'delete-selection 'supersede)
19495 (put 'org-delete-backward-char 'delete-selection 'supersede)
19496 (put 'org-yank 'delete-selection 'yank)
19498 ;; Make `flyspell-mode' delay after some commands
19499 (put 'org-self-insert-command 'flyspell-delayed t)
19500 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19501 (put 'org-delete-char 'flyspell-delayed t)
19502 (put 'org-delete-backward-char 'flyspell-delayed t)
19504 ;; Make pabbrev-mode expand after org-mode commands
19505 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19506 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19508 (defun org-remap (map &rest commands)
19509 "In MAP, remap the functions given in COMMANDS.
19510 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19511 (let (new old)
19512 (while commands
19513 (setq old (pop commands) new (pop commands))
19514 (if (fboundp 'command-remapping)
19515 (org-defkey map (vector 'remap old) new)
19516 (substitute-key-definition old new map global-map)))))
19518 (defun org-transpose-words ()
19519 "Transpose words for Org.
19520 This uses the `org-mode-transpose-word-syntax-table' syntax
19521 table, which interprets characters in `org-emphasis-alist' as
19522 word constituents."
19523 (interactive)
19524 (with-syntax-table org-mode-transpose-word-syntax-table
19525 (call-interactively 'transpose-words)))
19526 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19528 (when (eq org-enable-table-editor 'optimized)
19529 ;; If the user wants maximum table support, we need to hijack
19530 ;; some standard editing functions
19531 (org-remap org-mode-map
19532 'self-insert-command 'org-self-insert-command
19533 'delete-char 'org-delete-char
19534 'delete-backward-char 'org-delete-backward-char)
19535 (org-defkey org-mode-map "|" 'org-force-self-insert))
19537 (defvar org-ctrl-c-ctrl-c-hook nil
19538 "Hook for functions attaching themselves to `C-c C-c'.
19540 This can be used to add additional functionality to the C-c C-c
19541 key which executes context-dependent commands. This hook is run
19542 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19543 run after the last test.
19545 Each function will be called with no arguments. The function
19546 must check if the context is appropriate for it to act. If yes,
19547 it should do its thing and then return a non-nil value. If the
19548 context is wrong, just do nothing and return nil.")
19550 (defvar org-ctrl-c-ctrl-c-final-hook nil
19551 "Hook for functions attaching themselves to `C-c C-c'.
19553 This can be used to add additional functionality to the C-c C-c
19554 key which executes context-dependent commands. This hook is run
19555 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19556 before the first test.
19558 Each function will be called with no arguments. The function
19559 must check if the context is appropriate for it to act. If yes,
19560 it should do its thing and then return a non-nil value. If the
19561 context is wrong, just do nothing and return nil.")
19563 (defvar org-tab-first-hook nil
19564 "Hook for functions to attach themselves to TAB.
19565 See `org-ctrl-c-ctrl-c-hook' for more information.
19566 This hook runs as the first action when TAB is pressed, even before
19567 `org-cycle' messes around with the `outline-regexp' to cater for
19568 inline tasks and plain list item folding.
19569 If any function in this hook returns t, any other actions that
19570 would have been caused by TAB (such as table field motion or visibility
19571 cycling) will not occur.")
19573 (defvar org-tab-after-check-for-table-hook nil
19574 "Hook for functions to attach themselves to TAB.
19575 See `org-ctrl-c-ctrl-c-hook' for more information.
19576 This hook runs after it has been established that the cursor is not in a
19577 table, but before checking if the cursor is in a headline or if global cycling
19578 should be done.
19579 If any function in this hook returns t, not other actions like visibility
19580 cycling will be done.")
19582 (defvar org-tab-after-check-for-cycling-hook nil
19583 "Hook for functions to attach themselves to TAB.
19584 See `org-ctrl-c-ctrl-c-hook' for more information.
19585 This hook runs after it has been established that not table field motion and
19586 not visibility should be done because of current context. This is probably
19587 the place where a package like yasnippets can hook in.")
19589 (defvar org-tab-before-tab-emulation-hook nil
19590 "Hook for functions to attach themselves to TAB.
19591 See `org-ctrl-c-ctrl-c-hook' for more information.
19592 This hook runs after every other options for TAB have been exhausted, but
19593 before indentation and \t insertion takes place.")
19595 (defvar org-metaleft-hook nil
19596 "Hook for functions attaching themselves to `M-left'.
19597 See `org-ctrl-c-ctrl-c-hook' for more information.")
19598 (defvar org-metaright-hook nil
19599 "Hook for functions attaching themselves to `M-right'.
19600 See `org-ctrl-c-ctrl-c-hook' for more information.")
19601 (defvar org-metaup-hook nil
19602 "Hook for functions attaching themselves to `M-up'.
19603 See `org-ctrl-c-ctrl-c-hook' for more information.")
19604 (defvar org-metadown-hook nil
19605 "Hook for functions attaching themselves to `M-down'.
19606 See `org-ctrl-c-ctrl-c-hook' for more information.")
19607 (defvar org-shiftmetaleft-hook nil
19608 "Hook for functions attaching themselves to `M-S-left'.
19609 See `org-ctrl-c-ctrl-c-hook' for more information.")
19610 (defvar org-shiftmetaright-hook nil
19611 "Hook for functions attaching themselves to `M-S-right'.
19612 See `org-ctrl-c-ctrl-c-hook' for more information.")
19613 (defvar org-shiftmetaup-hook nil
19614 "Hook for functions attaching themselves to `M-S-up'.
19615 See `org-ctrl-c-ctrl-c-hook' for more information.")
19616 (defvar org-shiftmetadown-hook nil
19617 "Hook for functions attaching themselves to `M-S-down'.
19618 See `org-ctrl-c-ctrl-c-hook' for more information.")
19619 (defvar org-metareturn-hook nil
19620 "Hook for functions attaching themselves to `M-RET'.
19621 See `org-ctrl-c-ctrl-c-hook' for more information.")
19622 (defvar org-shiftup-hook nil
19623 "Hook for functions attaching themselves to `S-up'.
19624 See `org-ctrl-c-ctrl-c-hook' for more information.")
19625 (defvar org-shiftup-final-hook nil
19626 "Hook for functions attaching themselves to `S-up'.
19627 This one runs after all other options except shift-select have been excluded.
19628 See `org-ctrl-c-ctrl-c-hook' for more information.")
19629 (defvar org-shiftdown-hook nil
19630 "Hook for functions attaching themselves to `S-down'.
19631 See `org-ctrl-c-ctrl-c-hook' for more information.")
19632 (defvar org-shiftdown-final-hook nil
19633 "Hook for functions attaching themselves to `S-down'.
19634 This one runs after all other options except shift-select have been excluded.
19635 See `org-ctrl-c-ctrl-c-hook' for more information.")
19636 (defvar org-shiftleft-hook nil
19637 "Hook for functions attaching themselves to `S-left'.
19638 See `org-ctrl-c-ctrl-c-hook' for more information.")
19639 (defvar org-shiftleft-final-hook nil
19640 "Hook for functions attaching themselves to `S-left'.
19641 This one runs after all other options except shift-select have been excluded.
19642 See `org-ctrl-c-ctrl-c-hook' for more information.")
19643 (defvar org-shiftright-hook nil
19644 "Hook for functions attaching themselves to `S-right'.
19645 See `org-ctrl-c-ctrl-c-hook' for more information.")
19646 (defvar org-shiftright-final-hook nil
19647 "Hook for functions attaching themselves to `S-right'.
19648 This one runs after all other options except shift-select have been excluded.
19649 See `org-ctrl-c-ctrl-c-hook' for more information.")
19651 (defun org-modifier-cursor-error ()
19652 "Throw an error, a modified cursor command was applied in wrong context."
19653 (user-error "This command is active in special context like tables, headlines or items"))
19655 (defun org-shiftselect-error ()
19656 "Throw an error because Shift-Cursor command was applied in wrong context."
19657 (if (and (boundp 'shift-select-mode) shift-select-mode)
19658 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19659 (user-error "This command works only in special context like headlines or timestamps")))
19661 (defun org-call-for-shift-select (cmd)
19662 (let ((this-command-keys-shift-translated t))
19663 (call-interactively cmd)))
19665 (defun org-shifttab (&optional arg)
19666 "Global visibility cycling or move to previous table field.
19667 Call `org-table-previous-field' within a table.
19668 When ARG is nil, cycle globally through visibility states.
19669 When ARG is a numeric prefix, show contents of this level."
19670 (interactive "P")
19671 (cond
19672 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19673 ((integerp arg)
19674 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19675 (message "Content view to level: %d" arg)
19676 (org-content (prefix-numeric-value arg2))
19677 (org-cycle-show-empty-lines t)
19678 (setq org-cycle-global-status 'overview)))
19679 (t (call-interactively 'org-global-cycle))))
19681 (defun org-shiftmetaleft ()
19682 "Promote subtree or delete table column.
19683 Calls `org-promote-subtree', `org-outdent-item-tree', or
19684 `org-table-delete-column', depending on context. See the
19685 individual commands for more information."
19686 (interactive)
19687 (cond
19688 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19689 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19690 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19691 ((if (not (org-region-active-p)) (org-at-item-p)
19692 (save-excursion (goto-char (region-beginning))
19693 (org-at-item-p)))
19694 (call-interactively 'org-outdent-item-tree))
19695 (t (org-modifier-cursor-error))))
19697 (defun org-shiftmetaright ()
19698 "Demote subtree or insert table column.
19699 Calls `org-demote-subtree', `org-indent-item-tree', or
19700 `org-table-insert-column', depending on context. See the
19701 individual commands for more information."
19702 (interactive)
19703 (cond
19704 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19705 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19706 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19707 ((if (not (org-region-active-p)) (org-at-item-p)
19708 (save-excursion (goto-char (region-beginning))
19709 (org-at-item-p)))
19710 (call-interactively 'org-indent-item-tree))
19711 (t (org-modifier-cursor-error))))
19713 (defun org-shiftmetaup (&optional arg)
19714 "Move subtree up or kill table row.
19715 Calls `org-move-subtree-up' or `org-table-kill-row' or
19716 `org-move-item-up' or `org-timestamp-up', depending on context.
19717 See the individual commands for more information."
19718 (interactive "P")
19719 (cond
19720 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19721 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19722 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19723 ((org-at-item-p) (call-interactively 'org-move-item-up))
19724 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19725 (call-interactively 'org-timestamp-up)))
19726 (t (call-interactively 'org-drag-line-backward))))
19728 (defun org-shiftmetadown (&optional arg)
19729 "Move subtree down or insert table row.
19730 Calls `org-move-subtree-down' or `org-table-insert-row' or
19731 `org-move-item-down' or `org-timestamp-up', depending on context.
19732 See the individual commands for more information."
19733 (interactive "P")
19734 (cond
19735 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19736 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19737 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19738 ((org-at-item-p) (call-interactively 'org-move-item-down))
19739 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19740 (call-interactively 'org-timestamp-down)))
19741 (t (call-interactively 'org-drag-line-forward))))
19743 (defsubst org-hidden-tree-error ()
19744 (user-error
19745 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19747 (defun org-metaleft (&optional arg)
19748 "Promote heading or move table column to left.
19749 Calls `org-do-promote' or `org-table-move-column', depending on context.
19750 With no specific context, calls the Emacs default `backward-word'.
19751 See the individual commands for more information."
19752 (interactive "P")
19753 (cond
19754 ((run-hook-with-args-until-success 'org-metaleft-hook))
19755 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19756 ((org-with-limited-levels
19757 (or (org-at-heading-p)
19758 (and (org-region-active-p)
19759 (save-excursion
19760 (goto-char (region-beginning))
19761 (org-at-heading-p)))))
19762 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19763 (call-interactively 'org-do-promote))
19764 ;; At an inline task.
19765 ((org-at-heading-p)
19766 (call-interactively 'org-inlinetask-promote))
19767 ((or (org-at-item-p)
19768 (and (org-region-active-p)
19769 (save-excursion
19770 (goto-char (region-beginning))
19771 (org-at-item-p))))
19772 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19773 (call-interactively 'org-outdent-item))
19774 (t (call-interactively 'backward-word))))
19776 (defun org-metaright (&optional arg)
19777 "Demote a subtree, a list item or move table column to right.
19778 In front of a drawer or a block keyword, indent it correctly.
19779 With no specific context, calls the Emacs default `forward-word'.
19780 See the individual commands for more information."
19781 (interactive "P")
19782 (cond
19783 ((run-hook-with-args-until-success 'org-metaright-hook))
19784 ((org-at-table-p) (call-interactively 'org-table-move-column))
19785 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19786 ((org-at-block-p) (call-interactively 'org-indent-block))
19787 ((org-with-limited-levels
19788 (or (org-at-heading-p)
19789 (and (org-region-active-p)
19790 (save-excursion
19791 (goto-char (region-beginning))
19792 (org-at-heading-p)))))
19793 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19794 (call-interactively 'org-do-demote))
19795 ;; At an inline task.
19796 ((org-at-heading-p)
19797 (call-interactively 'org-inlinetask-demote))
19798 ((or (org-at-item-p)
19799 (and (org-region-active-p)
19800 (save-excursion
19801 (goto-char (region-beginning))
19802 (org-at-item-p))))
19803 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19804 (call-interactively 'org-indent-item))
19805 (t (call-interactively 'forward-word))))
19807 (defun org-check-for-hidden (what)
19808 "Check if there are hidden headlines/items in the current visual line.
19809 WHAT can be either `headlines' or `items'. If the current line is
19810 an outline or item heading and it has a folded subtree below it,
19811 this function returns t, nil otherwise."
19812 (let ((re (cond
19813 ((eq what 'headlines) org-outline-regexp-bol)
19814 ((eq what 'items) (org-item-beginning-re))
19815 (t (error "This should not happen"))))
19816 beg end)
19817 (save-excursion
19818 (catch 'exit
19819 (unless (org-region-active-p)
19820 (setq beg (point-at-bol))
19821 (beginning-of-line 2)
19822 (while (and (not (eobp)) ;; this is like `next-line'
19823 (get-char-property (1- (point)) 'invisible))
19824 (beginning-of-line 2))
19825 (setq end (point))
19826 (goto-char beg)
19827 (goto-char (point-at-eol))
19828 (setq end (max end (point)))
19829 (while (re-search-forward re end t)
19830 (if (get-char-property (match-beginning 0) 'invisible)
19831 (throw 'exit t))))
19832 nil))))
19834 (defun org-metaup (&optional arg)
19835 "Move subtree up or move table row up.
19836 Calls `org-move-subtree-up' or `org-table-move-row' or
19837 `org-move-item-up', depending on context. See the individual commands
19838 for more information."
19839 (interactive "P")
19840 (cond
19841 ((run-hook-with-args-until-success 'org-metaup-hook))
19842 ((org-region-active-p)
19843 (let* ((a (min (region-beginning) (region-end)))
19844 (b (1- (max (region-beginning) (region-end))))
19845 (c (save-excursion (goto-char a)
19846 (move-beginning-of-line 0)))
19847 (d (save-excursion (goto-char a)
19848 (move-end-of-line 0) (point))))
19849 (transpose-regions a b c d)
19850 (goto-char c)))
19851 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19852 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19853 ((org-at-item-p) (call-interactively 'org-move-item-up))
19854 (t (org-drag-element-backward))))
19856 (defun org-metadown (&optional arg)
19857 "Move subtree down or move table row down.
19858 Calls `org-move-subtree-down' or `org-table-move-row' or
19859 `org-move-item-down', depending on context. See the individual
19860 commands for more information."
19861 (interactive "P")
19862 (cond
19863 ((run-hook-with-args-until-success 'org-metadown-hook))
19864 ((org-region-active-p)
19865 (let* ((a (min (region-beginning) (region-end)))
19866 (b (max (region-beginning) (region-end)))
19867 (c (save-excursion (goto-char b)
19868 (move-beginning-of-line 1)))
19869 (d (save-excursion (goto-char b)
19870 (move-end-of-line 1) (1+ (point)))))
19871 (transpose-regions a b c d)
19872 (goto-char d)))
19873 ((org-at-table-p) (call-interactively 'org-table-move-row))
19874 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19875 ((org-at-item-p) (call-interactively 'org-move-item-down))
19876 (t (org-drag-element-forward))))
19878 (defun org-shiftup (&optional arg)
19879 "Increase item in timestamp or increase priority of current headline.
19880 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19881 depending on context. See the individual commands for more information."
19882 (interactive "P")
19883 (cond
19884 ((run-hook-with-args-until-success 'org-shiftup-hook))
19885 ((and org-support-shift-select (org-region-active-p))
19886 (org-call-for-shift-select 'previous-line))
19887 ((org-at-timestamp-p t)
19888 (call-interactively (if org-edit-timestamp-down-means-later
19889 'org-timestamp-down 'org-timestamp-up)))
19890 ((and (not (eq org-support-shift-select 'always))
19891 org-enable-priority-commands
19892 (org-at-heading-p))
19893 (call-interactively 'org-priority-up))
19894 ((and (not org-support-shift-select) (org-at-item-p))
19895 (call-interactively 'org-previous-item))
19896 ((org-clocktable-try-shift 'up arg))
19897 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19898 (org-support-shift-select
19899 (org-call-for-shift-select 'previous-line))
19900 (t (org-shiftselect-error))))
19902 (defun org-shiftdown (&optional arg)
19903 "Decrease item in timestamp or decrease priority of current headline.
19904 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19905 depending on context. See the individual commands for more information."
19906 (interactive "P")
19907 (cond
19908 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19909 ((and org-support-shift-select (org-region-active-p))
19910 (org-call-for-shift-select 'next-line))
19911 ((org-at-timestamp-p t)
19912 (call-interactively (if org-edit-timestamp-down-means-later
19913 'org-timestamp-up 'org-timestamp-down)))
19914 ((and (not (eq org-support-shift-select 'always))
19915 org-enable-priority-commands
19916 (org-at-heading-p))
19917 (call-interactively 'org-priority-down))
19918 ((and (not org-support-shift-select) (org-at-item-p))
19919 (call-interactively 'org-next-item))
19920 ((org-clocktable-try-shift 'down arg))
19921 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19922 (org-support-shift-select
19923 (org-call-for-shift-select 'next-line))
19924 (t (org-shiftselect-error))))
19926 (defun org-shiftright (&optional arg)
19927 "Cycle the thing at point or in the current line, depending on context.
19928 Depending on context, this does one of the following:
19930 - switch a timestamp at point one day into the future
19931 - on a headline, switch to the next TODO keyword.
19932 - on an item, switch entire list to the next bullet type
19933 - on a property line, switch to the next allowed value
19934 - on a clocktable definition line, move time block into the future"
19935 (interactive "P")
19936 (cond
19937 ((run-hook-with-args-until-success 'org-shiftright-hook))
19938 ((and org-support-shift-select (org-region-active-p))
19939 (org-call-for-shift-select 'forward-char))
19940 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19941 ((and (not (eq org-support-shift-select 'always))
19942 (org-at-heading-p))
19943 (let ((org-inhibit-logging
19944 (not org-treat-S-cursor-todo-selection-as-state-change))
19945 (org-inhibit-blocking
19946 (not org-treat-S-cursor-todo-selection-as-state-change)))
19947 (org-call-with-arg 'org-todo 'right)))
19948 ((or (and org-support-shift-select
19949 (not (eq org-support-shift-select 'always))
19950 (org-at-item-bullet-p))
19951 (and (not org-support-shift-select) (org-at-item-p)))
19952 (org-call-with-arg 'org-cycle-list-bullet nil))
19953 ((and (not (eq org-support-shift-select 'always))
19954 (org-at-property-p))
19955 (call-interactively 'org-property-next-allowed-value))
19956 ((org-clocktable-try-shift 'right arg))
19957 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19958 (org-support-shift-select
19959 (org-call-for-shift-select 'forward-char))
19960 (t (org-shiftselect-error))))
19962 (defun org-shiftleft (&optional arg)
19963 "Cycle the thing at point or in the current line, depending on context.
19964 Depending on context, this does one of the following:
19966 - switch a timestamp at point one day into the past
19967 - on a headline, switch to the previous TODO keyword.
19968 - on an item, switch entire list to the previous bullet type
19969 - on a property line, switch to the previous allowed value
19970 - on a clocktable definition line, move time block into the past"
19971 (interactive "P")
19972 (cond
19973 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19974 ((and org-support-shift-select (org-region-active-p))
19975 (org-call-for-shift-select 'backward-char))
19976 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19977 ((and (not (eq org-support-shift-select 'always))
19978 (org-at-heading-p))
19979 (let ((org-inhibit-logging
19980 (not org-treat-S-cursor-todo-selection-as-state-change))
19981 (org-inhibit-blocking
19982 (not org-treat-S-cursor-todo-selection-as-state-change)))
19983 (org-call-with-arg 'org-todo 'left)))
19984 ((or (and org-support-shift-select
19985 (not (eq org-support-shift-select 'always))
19986 (org-at-item-bullet-p))
19987 (and (not org-support-shift-select) (org-at-item-p)))
19988 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19989 ((and (not (eq org-support-shift-select 'always))
19990 (org-at-property-p))
19991 (call-interactively 'org-property-previous-allowed-value))
19992 ((org-clocktable-try-shift 'left arg))
19993 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19994 (org-support-shift-select
19995 (org-call-for-shift-select 'backward-char))
19996 (t (org-shiftselect-error))))
19998 (defun org-shiftcontrolright ()
19999 "Switch to next TODO set."
20000 (interactive)
20001 (cond
20002 ((and org-support-shift-select (org-region-active-p))
20003 (org-call-for-shift-select 'forward-word))
20004 ((and (not (eq org-support-shift-select 'always))
20005 (org-at-heading-p))
20006 (org-call-with-arg 'org-todo 'nextset))
20007 (org-support-shift-select
20008 (org-call-for-shift-select 'forward-word))
20009 (t (org-shiftselect-error))))
20011 (defun org-shiftcontrolleft ()
20012 "Switch to previous TODO set."
20013 (interactive)
20014 (cond
20015 ((and org-support-shift-select (org-region-active-p))
20016 (org-call-for-shift-select 'backward-word))
20017 ((and (not (eq org-support-shift-select 'always))
20018 (org-at-heading-p))
20019 (org-call-with-arg 'org-todo 'previousset))
20020 (org-support-shift-select
20021 (org-call-for-shift-select 'backward-word))
20022 (t (org-shiftselect-error))))
20024 (defun org-shiftcontrolup (&optional n)
20025 "Change timestamps synchronously up in CLOCK log lines.
20026 Optional argument N tells to change by that many units."
20027 (interactive "P")
20028 (cond ((and (not org-support-shift-select)
20029 (org-at-clock-log-p)
20030 (org-at-timestamp-p t))
20031 (org-clock-timestamps-up n))
20032 (t (org-shiftselect-error))))
20034 (defun org-shiftcontroldown (&optional n)
20035 "Change timestamps synchronously down in CLOCK log lines.
20036 Optional argument N tells to change by that many units."
20037 (interactive "P")
20038 (cond ((and (not org-support-shift-select)
20039 (org-at-clock-log-p)
20040 (org-at-timestamp-p t))
20041 (org-clock-timestamps-down n))
20042 (t (org-shiftselect-error))))
20044 (defun org-ctrl-c-ret ()
20045 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20046 (interactive)
20047 (cond
20048 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20049 (t (call-interactively 'org-insert-heading))))
20051 (defun org-find-visible ()
20052 (let ((s (point)))
20053 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20054 (get-char-property s 'invisible)))
20056 (defun org-find-invisible ()
20057 (let ((s (point)))
20058 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20059 (not (get-char-property s 'invisible))))
20062 (defun org-copy-visible (beg end)
20063 "Copy the visible parts of the region."
20064 (interactive "r")
20065 (let (snippets s)
20066 (save-excursion
20067 (save-restriction
20068 (narrow-to-region beg end)
20069 (setq s (goto-char (point-min)))
20070 (while (not (= (point) (point-max)))
20071 (goto-char (org-find-invisible))
20072 (push (buffer-substring s (point)) snippets)
20073 (setq s (goto-char (org-find-visible))))))
20074 (kill-new (apply 'concat (nreverse snippets)))))
20076 (defun org-copy-special ()
20077 "Copy region in table or copy current subtree.
20078 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20079 See the individual commands for more information."
20080 (interactive)
20081 (call-interactively
20082 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20084 (defun org-cut-special ()
20085 "Cut region in table or cut current subtree.
20086 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20087 See the individual commands for more information."
20088 (interactive)
20089 (call-interactively
20090 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20092 (defun org-paste-special (arg)
20093 "Paste rectangular region into table, or past subtree relative to level.
20094 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20095 See the individual commands for more information."
20096 (interactive "P")
20097 (if (org-at-table-p)
20098 (org-table-paste-rectangle)
20099 (org-paste-subtree arg)))
20101 (defsubst org-in-fixed-width-region-p ()
20102 "Is point in a fixed-width region?"
20103 (save-match-data
20104 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20106 (defun org-edit-special (&optional arg)
20107 "Call a special editor for the element at point.
20108 When at a table, call the formula editor with `org-table-edit-formulas'.
20109 When in a source code block, call `org-edit-src-code'.
20110 When in a fixed-width region, call `org-edit-fixed-width-region'.
20111 When at an #+INCLUDE keyword, visit the included file.
20112 On a link, call `ffap' to visit the link at point.
20113 Otherwise, return a user error."
20114 (interactive "P")
20115 (let ((element (org-element-at-point)))
20116 (assert (not buffer-read-only) nil
20117 "Buffer is read-only: %s" (buffer-name))
20118 (case (org-element-type element)
20119 (src-block
20120 (if (not arg) (org-edit-src-code)
20121 (let* ((info (org-babel-get-src-block-info))
20122 (lang (nth 0 info))
20123 (params (nth 2 info))
20124 (session (cdr (assq :session params))))
20125 (if (not session) (org-edit-src-code)
20126 ;; At a src-block with a session and function called with
20127 ;; an ARG: switch to the buffer related to the inferior
20128 ;; process.
20129 (switch-to-buffer
20130 (funcall (intern (concat "org-babel-prep-session:" lang))
20131 session params))))))
20132 (keyword
20133 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20134 (find-file
20135 (org-remove-double-quotes
20136 (car (org-split-string (org-element-property :value element)))))
20137 (user-error "No special environment to edit here")))
20138 (table
20139 (if (eq (org-element-property :type element) 'table.el)
20140 (org-edit-src-code)
20141 (call-interactively 'org-table-edit-formulas)))
20142 ;; Only Org tables contain `table-row' type elements.
20143 (table-row (call-interactively 'org-table-edit-formulas))
20144 ((example-block export-block) (org-edit-src-code))
20145 (fixed-width (org-edit-fixed-width-region))
20146 (otherwise
20147 ;; No notable element at point. Though, we may be at a link,
20148 ;; which is an object. Thus, scan deeper.
20149 (if (eq (org-element-type (org-element-context element)) 'link)
20150 (call-interactively 'ffap)
20151 (user-error "No special environment to edit here"))))))
20153 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20154 (defun org-ctrl-c-ctrl-c (&optional arg)
20155 "Set tags in headline, or update according to changed information at point.
20157 This command does many different things, depending on context:
20159 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20160 this is what we do.
20162 - If the cursor is on a statistics cookie, update it.
20164 - If the cursor is in a headline, prompt for tags and insert them
20165 into the current line, aligned to `org-tags-column'. When called
20166 with prefix arg, realign all tags in the current buffer.
20168 - If the cursor is in one of the special #+KEYWORD lines, this
20169 triggers scanning the buffer for these lines and updating the
20170 information.
20172 - If the cursor is inside a table, realign the table. This command
20173 works even if the automatic table editor has been turned off.
20175 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20176 the entire table.
20178 - If the cursor is at a footnote reference or definition, jump to
20179 the corresponding definition or references, respectively.
20181 - If the cursor is a the beginning of a dynamic block, update it.
20183 - If the current buffer is a capture buffer, close note and file it.
20185 - If the cursor is on a <<<target>>>, update radio targets and
20186 corresponding links in this buffer.
20188 - If the cursor is on a numbered item in a plain list, renumber the
20189 ordered list.
20191 - If the cursor is on a checkbox, toggle it.
20193 - If the cursor is on a code block, evaluate it. The variable
20194 `org-confirm-babel-evaluate' can be used to control prompting
20195 before code block evaluation, by default every code block
20196 evaluation requires confirmation. Code block evaluation can be
20197 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20198 (interactive "P")
20199 (cond
20200 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20201 org-occur-highlights
20202 org-latex-fragment-image-overlays)
20203 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20204 (org-remove-occur-highlights)
20205 (org-remove-latex-fragment-image-overlays)
20206 (message "Temporary highlights/overlays removed from current buffer"))
20207 ((and (local-variable-p 'org-finish-function (current-buffer))
20208 (fboundp org-finish-function))
20209 (funcall org-finish-function))
20210 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20212 (let* ((context (org-element-context)) (type (org-element-type context)))
20213 ;; Test if point is within a blank line.
20214 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20215 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20216 (user-error "C-c C-c can do nothing useful at this location"))
20217 (case type
20218 ;; When at a link, act according to the parent instead.
20219 (link (setq context (org-element-property :parent context))
20220 (setq type (org-element-type context)))
20221 ;; Unsupported object types: check parent element instead.
20222 ((bold code entity export-snippet inline-babel-call inline-src-block
20223 italic latex-fragment line-break macro strike-through subscript
20224 superscript underline verbatim)
20225 (while (and (setq context (org-element-property :parent context))
20226 (not (memq (setq type (org-element-type context))
20227 '(paragraph verse-block)))))))
20228 ;; For convenience: at the first line of a paragraph on the
20229 ;; same line as an item, apply function on that item instead.
20230 (when (eq type 'paragraph)
20231 (let ((parent (org-element-property :parent context)))
20232 (when (and (eq (org-element-type parent) 'item)
20233 (= (point-at-bol) (org-element-property :begin parent)))
20234 (setq context parent type 'item))))
20235 ;; Act according to type of element or object at point.
20236 (case type
20237 (clock (org-clock-update-time-maybe))
20238 (dynamic-block
20239 (save-excursion
20240 (goto-char (org-element-property :post-affiliated context))
20241 (org-update-dblock)))
20242 (footnote-definition
20243 (goto-char (org-element-property :post-affiliated context))
20244 (call-interactively 'org-footnote-action))
20245 (footnote-reference (call-interactively 'org-footnote-action))
20246 ((headline inlinetask)
20247 (save-excursion (goto-char (org-element-property :begin context))
20248 (call-interactively 'org-set-tags)))
20249 (item
20250 ;; At an item: a double C-u set checkbox to "[-]"
20251 ;; unconditionally, whereas a single one will toggle its
20252 ;; presence. Without an universal argument, if the item
20253 ;; has a checkbox, toggle it. Otherwise repair the list.
20254 (let* ((box (org-element-property :checkbox context))
20255 (struct (org-element-property :structure context))
20256 (old-struct (copy-tree struct))
20257 (parents (org-list-parents-alist struct))
20258 (prevs (org-list-prevs-alist struct))
20259 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20260 (org-list-set-checkbox
20261 (org-element-property :begin context) struct
20262 (cond ((equal arg '(16)) "[-]")
20263 ((and (not box) (equal arg '(4))) "[ ]")
20264 ((or (not box) (equal arg '(4))) nil)
20265 ((eq box 'on) "[ ]")
20266 (t "[X]")))
20267 ;; Mimic `org-list-write-struct' but with grabbing
20268 ;; a return value from `org-list-struct-fix-box'.
20269 (org-list-struct-fix-ind struct parents 2)
20270 (org-list-struct-fix-item-end struct)
20271 (org-list-struct-fix-bul struct prevs)
20272 (org-list-struct-fix-ind struct parents)
20273 (let ((block-item
20274 (org-list-struct-fix-box struct parents prevs orderedp)))
20275 (if (and box (equal struct old-struct))
20276 (if (equal arg '(16))
20277 (message "Checkboxes already reset")
20278 (user-error "Cannot toggle this checkbox: %s"
20279 (if (eq box 'on)
20280 "all subitems checked"
20281 "unchecked subitems")))
20282 (org-list-struct-apply-struct struct old-struct)
20283 (org-update-checkbox-count-maybe))
20284 (when block-item
20285 (message "Checkboxes were removed due to empty box at line %d"
20286 (org-current-line block-item))))))
20287 (keyword
20288 (let ((org-inhibit-startup-visibility-stuff t)
20289 (org-startup-align-all-tables nil))
20290 (when (boundp 'org-table-coordinate-overlays)
20291 (mapc 'delete-overlay org-table-coordinate-overlays)
20292 (setq org-table-coordinate-overlays nil))
20293 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20294 (message "Local setup has been refreshed"))
20295 (plain-list
20296 ;; At a plain list, with a double C-u argument, set
20297 ;; checkboxes of each item to "[-]", whereas a single one
20298 ;; will toggle their presence according to the state of the
20299 ;; first item in the list. Without an argument, repair the
20300 ;; list.
20301 (let* ((begin (org-element-property :contents-begin context))
20302 (beginm (move-marker (make-marker) begin))
20303 (struct (org-element-property :structure context))
20304 (old-struct (copy-tree struct))
20305 (first-box (save-excursion
20306 (goto-char begin)
20307 (looking-at org-list-full-item-re)
20308 (match-string-no-properties 3)))
20309 (new-box (cond ((equal arg '(16)) "[-]")
20310 ((equal arg '(4)) (unless first-box "[ ]"))
20311 ((equal first-box "[X]") "[ ]")
20312 (t "[X]"))))
20313 (cond
20314 (arg
20315 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20316 (org-list-get-all-items
20317 begin struct (org-list-prevs-alist struct))))
20318 ((and first-box (eq (point) begin))
20319 ;; For convenience, when point is at bol on the first
20320 ;; item of the list and no argument is provided, simply
20321 ;; toggle checkbox of that item, if any.
20322 (org-list-set-checkbox begin struct new-box)))
20323 (org-list-write-struct
20324 struct (org-list-parents-alist struct) old-struct)
20325 (org-update-checkbox-count-maybe)
20326 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20327 ((property-drawer node-property)
20328 (call-interactively 'org-property-action))
20329 ((radio-target target)
20330 (call-interactively 'org-update-radio-target-regexp))
20331 (statistics-cookie
20332 (call-interactively 'org-update-statistics-cookies))
20333 ((table table-cell table-row)
20334 ;; At a table, recalculate every field and align it. Also
20335 ;; send the table if necessary. If the table has
20336 ;; a `table.el' type, just give up. At a table row or
20337 ;; cell, maybe recalculate line but always align table.
20338 (if (eq (org-element-property :type context) 'table.el)
20339 (message "Use C-c ' to edit table.el tables")
20340 (let ((org-enable-table-editor t))
20341 (if (or (eq type 'table)
20342 ;; Check if point is at a TBLFM line.
20343 (and (eq type 'table-row)
20344 (= (point) (org-element-property :end context))))
20345 (save-excursion
20346 (if (org-at-TBLFM-p)
20347 (progn (require 'org-table)
20348 (org-table-calc-current-TBLFM))
20349 (goto-char (org-element-property :contents-begin context))
20350 (org-call-with-arg 'org-table-recalculate (or arg t))
20351 (orgtbl-send-table 'maybe)))
20352 (org-table-maybe-eval-formula)
20353 (cond (arg (call-interactively 'org-table-recalculate))
20354 ((org-table-maybe-recalculate-line))
20355 (t (org-table-align)))))))
20356 (timestamp (org-timestamp-change 0 'day))
20357 (otherwise
20358 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20359 (user-error
20360 "C-c C-c can do nothing useful at this location")))))))))
20362 (defun org-mode-restart ()
20363 "Restart Org-mode, to scan again for special lines.
20364 Also updates the keyword regular expressions."
20365 (interactive)
20366 (org-mode)
20367 (message "Org-mode restarted"))
20369 (defun org-kill-note-or-show-branches ()
20370 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20371 (interactive)
20372 (if (not org-finish-function)
20373 (progn
20374 (hide-subtree)
20375 (call-interactively 'show-branches))
20376 (let ((org-note-abort t))
20377 (funcall org-finish-function))))
20379 (defun org-open-line (n)
20380 "Insert a new row in tables, call `open-line' elsewhere.
20381 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
20382 (interactive "*p")
20383 (cond
20384 ((not org-special-ctrl-o)
20385 (open-line n))
20386 ((org-at-table-p)
20387 (org-table-insert-row))
20389 (open-line n))))
20391 (defun org-return (&optional indent)
20392 "Goto next table row or insert a newline.
20393 Calls `org-table-next-row' or `newline', depending on context.
20394 See the individual commands for more information."
20395 (interactive)
20396 (let (org-ts-what)
20397 (cond
20398 ((or (bobp) (org-in-src-block-p))
20399 (if indent (newline-and-indent) (newline)))
20400 ((org-at-table-p)
20401 (org-table-justify-field-maybe)
20402 (call-interactively 'org-table-next-row))
20403 ;; when `newline-and-indent' is called within a list, make sure
20404 ;; text moved stays inside the item.
20405 ((and (org-in-item-p) indent)
20406 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20407 (progn
20408 (save-match-data (newline))
20409 (org-indent-line-to (length (match-string 0))))
20410 (let ((ind (org-get-indentation)))
20411 (newline)
20412 (if (org-looking-back org-list-end-re)
20413 (org-indent-line)
20414 (org-indent-line-to ind)))))
20415 ((and org-return-follows-link
20416 (org-at-timestamp-p t)
20417 (not (eq org-ts-what 'after)))
20418 (org-follow-timestamp-link))
20419 ((and org-return-follows-link
20420 (let ((tprop (get-text-property (point) 'face)))
20421 (or (eq tprop 'org-link)
20422 (and (listp tprop) (memq 'org-link tprop)))))
20423 (call-interactively 'org-open-at-point))
20424 ((and (org-at-heading-p)
20425 (looking-at
20426 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20427 (org-show-entry)
20428 (end-of-line 1)
20429 (newline))
20430 (t (if indent (newline-and-indent) (newline))))))
20432 (defun org-return-indent ()
20433 "Goto next table row or insert a newline and indent.
20434 Calls `org-table-next-row' or `newline-and-indent', depending on
20435 context. See the individual commands for more information."
20436 (interactive)
20437 (org-return t))
20439 (defun org-ctrl-c-star ()
20440 "Compute table, or change heading status of lines.
20441 Calls `org-table-recalculate' or `org-toggle-heading',
20442 depending on context."
20443 (interactive)
20444 (cond
20445 ((org-at-table-p)
20446 (call-interactively 'org-table-recalculate))
20448 ;; Convert all lines in region to list items
20449 (call-interactively 'org-toggle-heading))))
20451 (defun org-ctrl-c-minus ()
20452 "Insert separator line in table or modify bullet status of line.
20453 Also turns a plain line or a region of lines into list items.
20454 Calls `org-table-insert-hline', `org-toggle-item', or
20455 `org-cycle-list-bullet', depending on context."
20456 (interactive)
20457 (cond
20458 ((org-at-table-p)
20459 (call-interactively 'org-table-insert-hline))
20460 ((org-region-active-p)
20461 (call-interactively 'org-toggle-item))
20462 ((org-in-item-p)
20463 (call-interactively 'org-cycle-list-bullet))
20465 (call-interactively 'org-toggle-item))))
20467 (defun org-toggle-item (arg)
20468 "Convert headings or normal lines to items, items to normal lines.
20469 If there is no active region, only the current line is considered.
20471 If the first non blank line in the region is a headline, convert
20472 all headlines to items, shifting text accordingly.
20474 If it is an item, convert all items to normal lines.
20476 If it is normal text, change region into a list of items.
20477 With a prefix argument ARG, change the region in a single item."
20478 (interactive "P")
20479 (let ((shift-text
20480 (function
20481 ;; Shift text in current section to IND, from point to END.
20482 ;; The function leaves point to END line.
20483 (lambda (ind end)
20484 (let ((min-i 1000) (end (copy-marker end)))
20485 ;; First determine the minimum indentation (MIN-I) of
20486 ;; the text.
20487 (save-excursion
20488 (catch 'exit
20489 (while (< (point) end)
20490 (let ((i (org-get-indentation)))
20491 (cond
20492 ;; Skip blank lines and inline tasks.
20493 ((looking-at "^[ \t]*$"))
20494 ((looking-at org-outline-regexp-bol))
20495 ;; We can't find less than 0 indentation.
20496 ((zerop i) (throw 'exit (setq min-i 0)))
20497 ((< i min-i) (setq min-i i))))
20498 (forward-line))))
20499 ;; Then indent each line so that a line indented to
20500 ;; MIN-I becomes indented to IND. Ignore blank lines
20501 ;; and inline tasks in the process.
20502 (let ((delta (- ind min-i)))
20503 (while (< (point) end)
20504 (unless (or (looking-at "^[ \t]*$")
20505 (looking-at org-outline-regexp-bol))
20506 (org-indent-line-to (+ (org-get-indentation) delta)))
20507 (forward-line)))))))
20508 (skip-blanks
20509 (function
20510 ;; Return beginning of first non-blank line, starting from
20511 ;; line at POS.
20512 (lambda (pos)
20513 (save-excursion
20514 (goto-char pos)
20515 (skip-chars-forward " \r\t\n")
20516 (point-at-bol)))))
20517 beg end)
20518 ;; Determine boundaries of changes.
20519 (if (org-region-active-p)
20520 (setq beg (funcall skip-blanks (region-beginning))
20521 end (copy-marker (region-end)))
20522 (setq beg (funcall skip-blanks (point-at-bol))
20523 end (copy-marker (point-at-eol))))
20524 ;; Depending on the starting line, choose an action on the text
20525 ;; between BEG and END.
20526 (org-with-limited-levels
20527 (save-excursion
20528 (goto-char beg)
20529 (cond
20530 ;; Case 1. Start at an item: de-itemize. Note that it only
20531 ;; happens when a region is active: `org-ctrl-c-minus'
20532 ;; would call `org-cycle-list-bullet' otherwise.
20533 ((org-at-item-p)
20534 (while (< (point) end)
20535 (when (org-at-item-p)
20536 (skip-chars-forward " \t")
20537 (delete-region (point) (match-end 0)))
20538 (forward-line)))
20539 ;; Case 2. Start at an heading: convert to items.
20540 ((org-at-heading-p)
20541 (let* ((bul (org-list-bullet-string "-"))
20542 (bul-len (length bul))
20543 ;; Indentation of the first heading. It should be
20544 ;; relative to the indentation of its parent, if any.
20545 (start-ind (save-excursion
20546 (cond
20547 ((not org-adapt-indentation) 0)
20548 ((not (outline-previous-heading)) 0)
20549 (t (length (match-string 0))))))
20550 ;; Level of first heading. Further headings will be
20551 ;; compared to it to determine hierarchy in the list.
20552 (ref-level (org-reduced-level (org-outline-level))))
20553 (while (< (point) end)
20554 (let* ((level (org-reduced-level (org-outline-level)))
20555 (delta (max 0 (- level ref-level))))
20556 ;; If current headline is less indented than the first
20557 ;; one, set it as reference, in order to preserve
20558 ;; subtrees.
20559 (when (< level ref-level) (setq ref-level level))
20560 (replace-match bul t t)
20561 (org-indent-line-to (+ start-ind (* delta bul-len)))
20562 ;; Ensure all text down to END (or SECTION-END) belongs
20563 ;; to the newly created item.
20564 (let ((section-end (save-excursion
20565 (or (outline-next-heading) (point)))))
20566 (forward-line)
20567 (funcall shift-text
20568 (+ start-ind (* (1+ delta) bul-len))
20569 (min end section-end)))))))
20570 ;; Case 3. Normal line with ARG: make the first line of region
20571 ;; an item, and shift indentation of others lines to
20572 ;; set them as item's body.
20573 (arg (let* ((bul (org-list-bullet-string "-"))
20574 (bul-len (length bul))
20575 (ref-ind (org-get-indentation)))
20576 (skip-chars-forward " \t")
20577 (insert bul)
20578 (forward-line)
20579 (while (< (point) end)
20580 ;; Ensure that lines less indented than first one
20581 ;; still get included in item body.
20582 (funcall shift-text
20583 (+ ref-ind bul-len)
20584 (min end (save-excursion (or (outline-next-heading)
20585 (point)))))
20586 (forward-line))))
20587 ;; Case 4. Normal line without ARG: turn each non-item line
20588 ;; into an item.
20590 (while (< (point) end)
20591 (unless (or (org-at-heading-p) (org-at-item-p))
20592 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20593 (replace-match
20594 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20595 (forward-line))))))))
20597 (defun org-toggle-heading (&optional nstars)
20598 "Convert headings to normal text, or items or text to headings.
20599 If there is no active region, only convert the current line.
20601 With a \\[universal-argument] prefix, convert the whole list at
20602 point into heading.
20604 In a region:
20606 - If the first non blank line is a headline, remove the stars
20607 from all headlines in the region.
20609 - If it is a normal line, turn each and every normal line (i.e.,
20610 not an heading or an item) in the region into headings. If you
20611 want to convert only the first line of this region, use one
20612 universal prefix argument.
20614 - If it is a plain list item, turn all plain list items into headings.
20616 When converting a line into a heading, the number of stars is chosen
20617 such that the lines become children of the current entry. However,
20618 when a numeric prefix argument is given, its value determines the
20619 number of stars to add."
20620 (interactive "P")
20621 (let ((skip-blanks
20622 (function
20623 ;; Return beginning of first non-blank line, starting from
20624 ;; line at POS.
20625 (lambda (pos)
20626 (save-excursion
20627 (goto-char pos)
20628 (while (org-at-comment-p) (forward-line))
20629 (skip-chars-forward " \r\t\n")
20630 (point-at-bol)))))
20631 beg end toggled)
20632 ;; Determine boundaries of changes. If a universal prefix has
20633 ;; been given, put the list in a region. If region ends at a bol,
20634 ;; do not consider the last line to be in the region.
20636 (when (and current-prefix-arg (org-at-item-p))
20637 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20638 (org-mark-element))
20640 (if (org-region-active-p)
20641 (setq beg (funcall skip-blanks (region-beginning))
20642 end (copy-marker (save-excursion
20643 (goto-char (region-end))
20644 (if (bolp) (point) (point-at-eol)))))
20645 (setq beg (funcall skip-blanks (point-at-bol))
20646 end (copy-marker (point-at-eol))))
20647 ;; Ensure inline tasks don't count as headings.
20648 (org-with-limited-levels
20649 (save-excursion
20650 (goto-char beg)
20651 (cond
20652 ;; Case 1. Started at an heading: de-star headings.
20653 ((org-at-heading-p)
20654 (while (< (point) end)
20655 (when (org-at-heading-p t)
20656 (looking-at org-outline-regexp) (replace-match "")
20657 (setq toggled t))
20658 (forward-line)))
20659 ;; Case 2. Started at an item: change items into headlines.
20660 ;; One star will be added by `org-list-to-subtree'.
20661 ((org-at-item-p)
20662 (let* ((stars (make-string
20663 ;; subtract the star that will be added again by
20664 ;; `org-list-to-subtree'
20665 (if (numberp nstars) (1- nstars)
20666 (or (org-current-level) 0))
20667 ?*))
20668 (add-stars
20669 (cond (nstars "") ; stars from prefix only
20670 ((equal stars "") "") ; before first heading
20671 (org-odd-levels-only "*") ; inside heading, odd
20672 (t "")))) ; inside heading, oddeven
20673 (while (< (point) end)
20674 (when (org-at-item-p)
20675 ;; Pay attention to cases when region ends before list.
20676 (let* ((struct (org-list-struct))
20677 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20678 (save-restriction
20679 (narrow-to-region (point) list-end)
20680 (insert
20681 (org-list-to-subtree
20682 (org-list-parse-list t)
20683 '(:istart (concat stars add-stars (funcall get-stars depth))
20684 :icount (concat stars add-stars (funcall get-stars depth)))))))
20685 (setq toggled t))
20686 (forward-line))))
20687 ;; Case 3. Started at normal text: make every line an heading,
20688 ;; skipping headlines and items.
20689 (t (let* ((stars
20690 (make-string
20691 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20692 (add-stars
20693 (cond (nstars "") ; stars from prefix only
20694 ((equal stars "") "*") ; before first heading
20695 (org-odd-levels-only "**") ; inside heading, odd
20696 (t "*"))) ; inside heading, oddeven
20697 (rpl (concat stars add-stars " "))
20698 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20699 (while (< (point) (if (equal nstars '(4)) lend end))
20700 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20701 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20702 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20703 (forward-line)))))))
20704 (unless toggled (message "Cannot toggle heading from here"))))
20706 (defun org-meta-return (&optional arg)
20707 "Insert a new heading or wrap a region in a table.
20708 Calls `org-insert-heading' or `org-table-wrap-region', depending
20709 on context. See the individual commands for more information."
20710 (interactive "P")
20711 (org-check-before-invisible-edit 'insert)
20712 (or (run-hook-with-args-until-success 'org-metareturn-hook)
20713 (let* ((element (org-element-at-point))
20714 (type (org-element-type element)))
20715 (when (eq type 'table-row)
20716 (setq element (org-element-property :parent element))
20717 (setq type 'table))
20718 (if (and (eq type 'table)
20719 (eq (org-element-property :type element) 'org)
20720 (>= (point) (org-element-property :contents-begin element))
20721 (< (point) (org-element-property :contents-end element)))
20722 (call-interactively 'org-table-wrap-region)
20723 (call-interactively 'org-insert-heading)))))
20725 ;;; Menu entries
20727 (defsubst org-in-subtree-not-table-p ()
20728 "Are we in a subtree and not in a table?"
20729 (and (not (org-before-first-heading-p))
20730 (not (org-at-table-p))))
20732 ;; Define the Org-mode menus
20733 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20734 '("Tbl"
20735 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20736 ["Next Field" org-cycle (org-at-table-p)]
20737 ["Previous Field" org-shifttab (org-at-table-p)]
20738 ["Next Row" org-return (org-at-table-p)]
20739 "--"
20740 ["Blank Field" org-table-blank-field (org-at-table-p)]
20741 ["Edit Field" org-table-edit-field (org-at-table-p)]
20742 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20743 "--"
20744 ("Column"
20745 ["Move Column Left" org-metaleft (org-at-table-p)]
20746 ["Move Column Right" org-metaright (org-at-table-p)]
20747 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20748 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20749 ("Row"
20750 ["Move Row Up" org-metaup (org-at-table-p)]
20751 ["Move Row Down" org-metadown (org-at-table-p)]
20752 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20753 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20754 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20755 "--"
20756 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20757 ("Rectangle"
20758 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20759 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20760 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20761 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20762 "--"
20763 ("Calculate"
20764 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20765 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20766 ["Edit Formulas" org-edit-special (org-at-table-p)]
20767 "--"
20768 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20769 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20770 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20771 "--"
20772 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20773 "--"
20774 ["Sum Column/Rectangle" org-table-sum
20775 (or (org-at-table-p) (org-region-active-p))]
20776 ["Which Column?" org-table-current-column (org-at-table-p)])
20777 ["Debug Formulas"
20778 org-table-toggle-formula-debugger
20779 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20780 ["Show Col/Row Numbers"
20781 org-table-toggle-coordinate-overlays
20782 :style toggle
20783 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20784 "--"
20785 ["Create" org-table-create (and (not (org-at-table-p))
20786 org-enable-table-editor)]
20787 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20788 ["Import from File" org-table-import (not (org-at-table-p))]
20789 ["Export to File" org-table-export (org-at-table-p)]
20790 "--"
20791 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20793 (easy-menu-define org-org-menu org-mode-map "Org menu"
20794 '("Org"
20795 ("Show/Hide"
20796 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20797 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20798 ["Sparse Tree..." org-sparse-tree t]
20799 ["Reveal Context" org-reveal t]
20800 ["Show All" show-all t]
20801 "--"
20802 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20803 "--"
20804 ["New Heading" org-insert-heading t]
20805 ("Navigate Headings"
20806 ["Up" outline-up-heading t]
20807 ["Next" outline-next-visible-heading t]
20808 ["Previous" outline-previous-visible-heading t]
20809 ["Next Same Level" outline-forward-same-level t]
20810 ["Previous Same Level" outline-backward-same-level t]
20811 "--"
20812 ["Jump" org-goto t])
20813 ("Edit Structure"
20814 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20815 "--"
20816 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20817 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20818 "--"
20819 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20820 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20821 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20822 "--"
20823 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20824 "--"
20825 ["Copy visible text" org-copy-visible t]
20826 "--"
20827 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20828 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20829 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20830 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20831 "--"
20832 ["Sort Region/Children" org-sort t]
20833 "--"
20834 ["Convert to odd levels" org-convert-to-odd-levels t]
20835 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20836 ("Editing"
20837 ["Emphasis..." org-emphasize t]
20838 ["Edit Source Example" org-edit-special t]
20839 "--"
20840 ["Footnote new/jump" org-footnote-action t]
20841 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20842 ("Archive"
20843 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20844 "--"
20845 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20846 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20847 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20849 "--"
20850 ("Hyperlinks"
20851 ["Store Link (Global)" org-store-link t]
20852 ["Find existing link to here" org-occur-link-in-agenda-files t]
20853 ["Insert Link" org-insert-link t]
20854 ["Follow Link" org-open-at-point t]
20855 "--"
20856 ["Next link" org-next-link t]
20857 ["Previous link" org-previous-link t]
20858 "--"
20859 ["Descriptive Links"
20860 org-toggle-link-display
20861 :style radio
20862 :selected org-descriptive-links
20864 ["Literal Links"
20865 org-toggle-link-display
20866 :style radio
20867 :selected (not org-descriptive-links)])
20868 "--"
20869 ("TODO Lists"
20870 ["TODO/DONE/-" org-todo t]
20871 ("Select keyword"
20872 ["Next keyword" org-shiftright (org-at-heading-p)]
20873 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20874 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20875 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20876 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20877 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20878 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20879 "--"
20880 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20881 :selected org-enforce-todo-dependencies :style toggle :active t]
20882 "Settings for tree at point"
20883 ["Do Children sequentially" org-toggle-ordered-property :style radio
20884 :selected (org-entry-get nil "ORDERED")
20885 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20886 ["Do Children parallel" org-toggle-ordered-property :style radio
20887 :selected (not (org-entry-get nil "ORDERED"))
20888 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20889 "--"
20890 ["Set Priority" org-priority t]
20891 ["Priority Up" org-shiftup t]
20892 ["Priority Down" org-shiftdown t]
20893 "--"
20894 ["Get news from all feeds" org-feed-update-all t]
20895 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20896 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20897 ("TAGS and Properties"
20898 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20899 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20900 "--"
20901 ["Set property" org-set-property (not (org-before-first-heading-p))]
20902 ["Column view of properties" org-columns t]
20903 ["Insert Column View DBlock" org-insert-columns-dblock t])
20904 ("Dates and Scheduling"
20905 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20906 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20907 ("Change Date"
20908 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20909 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20910 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20911 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20912 ["Compute Time Range" org-evaluate-time-range t]
20913 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20914 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20915 "--"
20916 ["Custom time format" org-toggle-time-stamp-overlays
20917 :style radio :selected org-display-custom-times]
20918 "--"
20919 ["Goto Calendar" org-goto-calendar t]
20920 ["Date from Calendar" org-date-from-calendar t]
20921 "--"
20922 ["Start/Restart Timer" org-timer-start t]
20923 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20924 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20925 ["Insert Timer String" org-timer t]
20926 ["Insert Timer Item" org-timer-item t])
20927 ("Logging work"
20928 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20929 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20930 ["Clock out" org-clock-out t]
20931 ["Clock cancel" org-clock-cancel t]
20932 "--"
20933 ["Mark as default task" org-clock-mark-default-task t]
20934 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20935 ["Goto running clock" org-clock-goto t]
20936 "--"
20937 ["Display times" org-clock-display t]
20938 ["Create clock table" org-clock-report t]
20939 "--"
20940 ["Record DONE time"
20941 (progn (setq org-log-done (not org-log-done))
20942 (message "Switching to %s will %s record a timestamp"
20943 (car org-done-keywords)
20944 (if org-log-done "automatically" "not")))
20945 :style toggle :selected org-log-done])
20946 "--"
20947 ["Agenda Command..." org-agenda t]
20948 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20949 ("File List for Agenda")
20950 ("Special views current file"
20951 ["TODO Tree" org-show-todo-tree t]
20952 ["Check Deadlines" org-check-deadlines t]
20953 ["Timeline" org-timeline t]
20954 ["Tags/Property tree" org-match-sparse-tree t])
20955 "--"
20956 ["Export/Publish..." org-export-dispatch t]
20957 ("LaTeX"
20958 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20959 :selected org-cdlatex-mode]
20960 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20961 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20962 ["Modify math symbol" org-cdlatex-math-modify
20963 (org-inside-LaTeX-fragment-p)]
20964 ["Insert citation" org-reftex-citation t]
20965 "--"
20966 ["Template for BEAMER" (org-beamer-insert-options-template) t])
20967 "--"
20968 ("MobileOrg"
20969 ["Push Files and Views" org-mobile-push t]
20970 ["Get Captured and Flagged" org-mobile-pull t]
20971 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20972 "--"
20973 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20974 "--"
20975 ("Documentation"
20976 ["Show Version" org-version t]
20977 ["Info Documentation" org-info t])
20978 ("Customize"
20979 ["Browse Org Group" org-customize t]
20980 "--"
20981 ["Expand This Menu" org-create-customize-menu
20982 (fboundp 'customize-menu-create)])
20983 ["Send bug report" org-submit-bug-report t]
20984 "--"
20985 ("Refresh/Reload"
20986 ["Refresh setup current buffer" org-mode-restart t]
20987 ["Reload Org (after update)" org-reload t]
20988 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
20991 (defun org-info (&optional node)
20992 "Read documentation for Org-mode in the info system.
20993 With optional NODE, go directly to that node."
20994 (interactive)
20995 (info (format "(org)%s" (or node ""))))
20997 ;;;###autoload
20998 (defun org-submit-bug-report ()
20999 "Submit a bug report on Org-mode via mail.
21001 Don't hesitate to report any problems or inaccurate documentation.
21003 If you don't have setup sending mail from (X)Emacs, please copy the
21004 output buffer into your mail program, as it gives us important
21005 information about your Org-mode version and configuration."
21006 (interactive)
21007 (require 'reporter)
21008 (org-load-modules-maybe)
21009 (org-require-autoloaded-modules)
21010 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21011 (reporter-submit-bug-report
21012 "emacs-orgmode@gnu.org"
21013 (org-version nil 'full)
21014 (let (list)
21015 (save-window-excursion
21016 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21017 (delete-other-windows)
21018 (erase-buffer)
21019 (insert "You are about to submit a bug report to the Org-mode mailing list.
21021 We would like to add your full Org-mode and Outline configuration to the
21022 bug report. This greatly simplifies the work of the maintainer and
21023 other experts on the mailing list.
21025 HOWEVER, some variables you have customized may contain private
21026 information. The names of customers, colleagues, or friends, might
21027 appear in the form of file names, tags, todo states, or search strings.
21028 If you answer yes to the prompt, you might want to check and remove
21029 such private information before sending the email.")
21030 (add-text-properties (point-min) (point-max) '(face org-warning))
21031 (when (yes-or-no-p "Include your Org-mode configuration ")
21032 (mapatoms
21033 (lambda (v)
21034 (and (boundp v)
21035 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21036 (or (and (symbol-value v)
21037 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21038 (and
21039 (get v 'custom-type) (get v 'standard-value)
21040 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21041 (push v list)))))
21042 (kill-buffer (get-buffer "*Warn about privacy*"))
21043 list))
21044 nil nil
21045 "Remember to cover the basics, that is, what you expected to happen and
21046 what in fact did happen. You don't know how to make a good report? See
21048 http://orgmode.org/manual/Feedback.html#Feedback
21050 Your bug report will be posted to the Org-mode mailing list.
21051 ------------------------------------------------------------------------")
21052 (save-excursion
21053 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21054 (replace-match "\\1Bug: \\3 [\\2]")))))
21057 (defun org-install-agenda-files-menu ()
21058 (let ((bl (buffer-list)))
21059 (save-excursion
21060 (while bl
21061 (set-buffer (pop bl))
21062 (if (derived-mode-p 'org-mode) (setq bl nil)))
21063 (when (derived-mode-p 'org-mode)
21064 (easy-menu-change
21065 '("Org") "File List for Agenda"
21066 (append
21067 (list
21068 ["Edit File List" (org-edit-agenda-file-list) t]
21069 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21070 ["Remove Current File from List" org-remove-file t]
21071 ["Cycle through agenda files" org-cycle-agenda-files t]
21072 ["Occur in all agenda files" org-occur-in-agenda-files t]
21073 "--")
21074 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21076 ;;;; Documentation
21078 (defun org-require-autoloaded-modules ()
21079 (interactive)
21080 (mapc 'require
21081 '(org-agenda org-archive org-attach org-clock org-colview org-id
21082 org-table org-timer)))
21084 ;;;###autoload
21085 (defun org-reload (&optional uncompiled)
21086 "Reload all org lisp files.
21087 With prefix arg UNCOMPILED, load the uncompiled versions."
21088 (interactive "P")
21089 (require 'loadhist)
21090 (let* ((org-dir (org-find-library-dir "org"))
21091 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21092 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21093 (remove-re (mapconcat 'identity
21094 (mapcar (lambda (f) (concat "^" f "$"))
21095 (list (if (featurep 'xemacs)
21096 "org-colview"
21097 "org-colview-xemacs")
21098 "org" "org-loaddefs" "org-version"))
21099 "\\|"))
21100 (feats (delete-dups
21101 (mapcar 'file-name-sans-extension
21102 (mapcar 'file-name-nondirectory
21103 (delq nil
21104 (mapcar 'feature-file
21105 features))))))
21106 (lfeat (append
21107 (sort
21108 (setq feats
21109 (delq nil (mapcar
21110 (lambda (f)
21111 (if (and (string-match feature-re f)
21112 (not (string-match remove-re f)))
21113 f nil))
21114 feats)))
21115 'string-lessp)
21116 (list "org-version" "org")))
21117 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21118 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21119 load-uncore load-misses)
21120 (setq load-misses
21121 (delq 't
21122 (mapcar (lambda (f)
21123 (or (org-load-noerror-mustsuffix (concat org-dir f))
21124 (and (string= org-dir contrib-dir)
21125 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21126 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21127 (add-to-list 'load-uncore f 'append)
21130 lfeat)))
21131 (if load-uncore
21132 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21133 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21134 (if load-misses
21135 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21136 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21137 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21139 ;;;###autoload
21140 (defun org-customize ()
21141 "Call the customize function with org as argument."
21142 (interactive)
21143 (org-load-modules-maybe)
21144 (org-require-autoloaded-modules)
21145 (customize-browse 'org))
21147 (defun org-create-customize-menu ()
21148 "Create a full customization menu for Org-mode, insert it into the menu."
21149 (interactive)
21150 (org-load-modules-maybe)
21151 (org-require-autoloaded-modules)
21152 (if (fboundp 'customize-menu-create)
21153 (progn
21154 (easy-menu-change
21155 '("Org") "Customize"
21156 `(["Browse Org group" org-customize t]
21157 "--"
21158 ,(customize-menu-create 'org)
21159 ["Set" Custom-set t]
21160 ["Save" Custom-save t]
21161 ["Reset to Current" Custom-reset-current t]
21162 ["Reset to Saved" Custom-reset-saved t]
21163 ["Reset to Standard Settings" Custom-reset-standard t]))
21164 (message "\"Org\"-menu now contains full customization menu"))
21165 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21167 ;;;; Miscellaneous stuff
21169 ;;; Generally useful functions
21171 (defun org-get-at-bol (property)
21172 "Get text property PROPERTY at beginning of line."
21173 (get-text-property (point-at-bol) property))
21175 (defun org-find-text-property-in-string (prop s)
21176 "Return the first non-nil value of property PROP in string S."
21177 (or (get-text-property 0 prop s)
21178 (get-text-property (or (next-single-property-change 0 prop s) 0)
21179 prop s)))
21181 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21182 "Display the given MESSAGE as a warning."
21183 (if (fboundp 'display-warning)
21184 (display-warning 'org message
21185 (if (featurep 'xemacs) 'warning :warning))
21186 (let ((buf (get-buffer-create "*Org warnings*")))
21187 (with-current-buffer buf
21188 (goto-char (point-max))
21189 (insert "Warning (Org): " message)
21190 (unless (bolp)
21191 (newline)))
21192 (display-buffer buf)
21193 (sit-for 0))))
21195 (defun org-eval (form)
21196 "Eval FORM and return result."
21197 (condition-case error
21198 (eval form)
21199 (error (format "%%![Error: %s]" error))))
21201 (defun org-in-clocktable-p ()
21202 "Check if the cursor is in a clocktable."
21203 (let ((pos (point)) start)
21204 (save-excursion
21205 (end-of-line 1)
21206 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21207 (setq start (match-beginning 0))
21208 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21209 (>= (match-end 0) pos)
21210 start))))
21212 (defun org-in-commented-line ()
21213 "Is point in a line starting with `#'?"
21214 (equal (char-after (point-at-bol)) ?#))
21216 (defun org-in-indented-comment-line ()
21217 "Is point in a line starting with `#' after some white space?"
21218 (save-excursion
21219 (save-match-data
21220 (goto-char (point-at-bol))
21221 (looking-at "[ \t]*#"))))
21223 (defun org-in-verbatim-emphasis ()
21224 (save-match-data
21225 (and (org-in-regexp org-emph-re 2)
21226 (>= (point) (match-beginning 3))
21227 (<= (point) (match-end 4))
21228 (member (match-string 3) '("=" "~")))))
21230 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21231 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21232 (if (and marker (marker-buffer marker)
21233 (buffer-live-p (marker-buffer marker)))
21234 (progn
21235 (org-pop-to-buffer-same-window (marker-buffer marker))
21236 (if (or (> marker (point-max)) (< marker (point-min)))
21237 (widen))
21238 (goto-char marker)
21239 (org-show-context 'org-goto))
21240 (if bookmark
21241 (bookmark-jump bookmark)
21242 (error "Cannot find location"))))
21244 (defun org-quote-csv-field (s)
21245 "Quote field for inclusion in CSV material."
21246 (if (string-match "[\",]" s)
21247 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21250 (defun org-force-self-insert (N)
21251 "Needed to enforce self-insert under remapping."
21252 (interactive "p")
21253 (self-insert-command N))
21255 (defun org-string-width (s)
21256 "Compute width of string, ignoring invisible characters.
21257 This ignores character with invisibility property `org-link', and also
21258 characters with property `org-cwidth', because these will become invisible
21259 upon the next fontification round."
21260 (let (b l)
21261 (when (or (eq t buffer-invisibility-spec)
21262 (assq 'org-link buffer-invisibility-spec))
21263 (while (setq b (text-property-any 0 (length s)
21264 'invisible 'org-link s))
21265 (setq s (concat (substring s 0 b)
21266 (substring s (or (next-single-property-change
21267 b 'invisible s) (length s)))))))
21268 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21269 (setq s (concat (substring s 0 b)
21270 (substring s (or (next-single-property-change
21271 b 'org-cwidth s) (length s))))))
21272 (setq l (string-width s) b -1)
21273 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21274 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21277 (defun org-shorten-string (s maxlength)
21278 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21279 If the string is shorter or has length MAXLENGTH, just return the
21280 original string. If it is longer, the functions finds a space in the
21281 string, breaks this string off at that locations and adds three dots
21282 as ellipsis. Including the ellipsis, the string will not be longer
21283 than MAXLENGTH. If finding a good breaking point in the string does
21284 not work, the string is just chopped off in the middle of a word
21285 if necessary."
21286 (if (<= (length s) maxlength)
21288 (let* ((n (max (- maxlength 4) 1))
21289 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21290 (if (string-match re s)
21291 (concat (match-string 1 s) "...")
21292 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21294 (defun org-get-indentation (&optional line)
21295 "Get the indentation of the current line, interpreting tabs.
21296 When LINE is given, assume it represents a line and compute its indentation."
21297 (if line
21298 (if (string-match "^ *" (org-remove-tabs line))
21299 (match-end 0))
21300 (save-excursion
21301 (beginning-of-line 1)
21302 (skip-chars-forward " \t")
21303 (current-column))))
21305 (defun org-get-string-indentation (s)
21306 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21307 (let ((n -1) (i 0) (w tab-width) c)
21308 (catch 'exit
21309 (while (< (setq n (1+ n)) (length s))
21310 (setq c (aref s n))
21311 (cond ((= c ?\ ) (setq i (1+ i)))
21312 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21313 (t (throw 'exit t)))))
21316 (defun org-remove-tabs (s &optional width)
21317 "Replace tabulators in S with spaces.
21318 Assumes that s is a single line, starting in column 0."
21319 (setq width (or width tab-width))
21320 (while (string-match "\t" s)
21321 (setq s (replace-match
21322 (make-string
21323 (- (* width (/ (+ (match-beginning 0) width) width))
21324 (match-beginning 0)) ?\ )
21325 t t s)))
21328 (defun org-fix-indentation (line ind)
21329 "Fix indentation in LINE.
21330 IND is a cons cell with target and minimum indentation.
21331 If the current indentation in LINE is smaller than the minimum,
21332 leave it alone. If it is larger than ind, set it to the target."
21333 (let* ((l (org-remove-tabs line))
21334 (i (org-get-indentation l))
21335 (i1 (car ind)) (i2 (cdr ind)))
21336 (if (>= i i2) (setq l (substring line i2)))
21337 (if (> i1 0)
21338 (concat (make-string i1 ?\ ) l)
21339 l)))
21341 (defun org-remove-indentation (code &optional n)
21342 "Remove the maximum common indentation from the lines in CODE.
21343 N may optionally be the number of spaces to remove."
21344 (with-temp-buffer
21345 (insert code)
21346 (org-do-remove-indentation n)
21347 (buffer-string)))
21349 (defun org-do-remove-indentation (&optional n)
21350 "Remove the maximum common indentation from the buffer."
21351 (untabify (point-min) (point-max))
21352 (let ((min 10000) re)
21353 (if n
21354 (setq min n)
21355 (goto-char (point-min))
21356 (while (re-search-forward "^ *[^ \n]" nil t)
21357 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21358 (unless (or (= min 0) (= min 10000))
21359 (setq re (format "^ \\{%d\\}" min))
21360 (goto-char (point-min))
21361 (while (re-search-forward re nil t)
21362 (replace-match "")
21363 (end-of-line 1))
21364 min)))
21366 (defun org-fill-template (template alist)
21367 "Find each %key of ALIST in TEMPLATE and replace it."
21368 (let ((case-fold-search nil)
21369 entry key value)
21370 (setq alist (sort (copy-sequence alist)
21371 (lambda (a b) (< (length (car a)) (length (car b))))))
21372 (while (setq entry (pop alist))
21373 (setq template
21374 (replace-regexp-in-string
21375 (concat "%" (regexp-quote (car entry)))
21376 (or (cdr entry) "") template t t)))
21377 template))
21379 (defun org-base-buffer (buffer)
21380 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21381 (if (not buffer)
21382 buffer
21383 (or (buffer-base-buffer buffer)
21384 buffer)))
21386 (defun org-trim (s)
21387 "Remove whitespace at beginning and end of string."
21388 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
21389 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
21392 (defun org-wrap (string &optional width lines)
21393 "Wrap string to either a number of lines, or a width in characters.
21394 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21395 that costs. If there is a word longer than WIDTH, the text is actually
21396 wrapped to the length of that word.
21397 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21398 many lines, whatever width that takes.
21399 The return value is a list of lines, without newlines at the end."
21400 (let* ((words (org-split-string string "[ \t\n]+"))
21401 (maxword (apply 'max (mapcar 'org-string-width words)))
21402 w ll)
21403 (cond (width
21404 (org-do-wrap words (max maxword width)))
21405 (lines
21406 (setq w maxword)
21407 (setq ll (org-do-wrap words maxword))
21408 (if (<= (length ll) lines)
21410 (setq ll words)
21411 (while (> (length ll) lines)
21412 (setq w (1+ w))
21413 (setq ll (org-do-wrap words w)))
21414 ll))
21415 (t (error "Cannot wrap this")))))
21417 (defun org-do-wrap (words width)
21418 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21419 (let (lines line)
21420 (while words
21421 (setq line (pop words))
21422 (while (and words (< (+ (length line) (length (car words))) width))
21423 (setq line (concat line " " (pop words))))
21424 (setq lines (push line lines)))
21425 (nreverse lines)))
21427 (defun org-split-string (string &optional separators)
21428 "Splits STRING into substrings at SEPARATORS.
21429 No empty strings are returned if there are matches at the beginning
21430 and end of string."
21431 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21432 (start 0)
21433 notfirst
21434 (list nil))
21435 (while (and (string-match rexp string
21436 (if (and notfirst
21437 (= start (match-beginning 0))
21438 (< start (length string)))
21439 (1+ start) start))
21440 (< (match-beginning 0) (length string)))
21441 (setq notfirst t)
21442 (or (eq (match-beginning 0) 0)
21443 (and (eq (match-beginning 0) (match-end 0))
21444 (eq (match-beginning 0) start))
21445 (setq list
21446 (cons (substring string start (match-beginning 0))
21447 list)))
21448 (setq start (match-end 0)))
21449 (or (eq start (length string))
21450 (setq list
21451 (cons (substring string start)
21452 list)))
21453 (nreverse list)))
21455 (defun org-quote-vert (s)
21456 "Replace \"|\" with \"\\vert\"."
21457 (while (string-match "|" s)
21458 (setq s (replace-match "\\vert" t t s)))
21461 (defun org-uuidgen-p (s)
21462 "Is S an ID created by UUIDGEN?"
21463 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21465 (defun org-in-src-block-p (&optional inside)
21466 "Whether point is in a code source block.
21467 When INSIDE is non-nil, don't consider we are within a src block
21468 when point is at #+BEGIN_SRC or #+END_SRC."
21469 (let ((case-fold-search t) ov)
21470 (or (and (setq ov (overlays-at (point)))
21471 (memq 'org-block-background
21472 (overlay-properties (car ov))))
21473 (and (not inside)
21474 (save-match-data
21475 (save-excursion
21476 (beginning-of-line)
21477 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21479 (defun org-context ()
21480 "Return a list of contexts of the current cursor position.
21481 If several contexts apply, all are returned.
21482 Each context entry is a list with a symbol naming the context, and
21483 two positions indicating start and end of the context. Possible
21484 contexts are:
21486 :headline anywhere in a headline
21487 :headline-stars on the leading stars in a headline
21488 :todo-keyword on a TODO keyword (including DONE) in a headline
21489 :tags on the TAGS in a headline
21490 :priority on the priority cookie in a headline
21491 :item on the first line of a plain list item
21492 :item-bullet on the bullet/number of a plain list item
21493 :checkbox on the checkbox in a plain list item
21494 :table in an org-mode table
21495 :table-special on a special filed in a table
21496 :table-table in a table.el table
21497 :clocktable in a clocktable
21498 :src-block in a source block
21499 :link on a hyperlink
21500 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21501 :target on a <<target>>
21502 :radio-target on a <<<radio-target>>>
21503 :latex-fragment on a LaTeX fragment
21504 :latex-preview on a LaTeX fragment with overlaid preview image
21506 This function expects the position to be visible because it uses font-lock
21507 faces as a help to recognize the following contexts: :table-special, :link,
21508 and :keyword."
21509 (let* ((f (get-text-property (point) 'face))
21510 (faces (if (listp f) f (list f)))
21511 (case-fold-search t)
21512 (p (point)) clist o)
21513 ;; First the large context
21514 (cond
21515 ((org-at-heading-p t)
21516 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21517 (when (progn
21518 (beginning-of-line 1)
21519 (looking-at org-todo-line-tags-regexp))
21520 (push (org-point-in-group p 1 :headline-stars) clist)
21521 (push (org-point-in-group p 2 :todo-keyword) clist)
21522 (push (org-point-in-group p 4 :tags) clist))
21523 (goto-char p)
21524 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21525 (if (looking-at "\\[#[A-Z0-9]\\]")
21526 (push (org-point-in-group p 0 :priority) clist)))
21528 ((org-at-item-p)
21529 (push (org-point-in-group p 2 :item-bullet) clist)
21530 (push (list :item (point-at-bol)
21531 (save-excursion (org-end-of-item) (point)))
21532 clist)
21533 (and (org-at-item-checkbox-p)
21534 (push (org-point-in-group p 0 :checkbox) clist)))
21536 ((org-at-table-p)
21537 (push (list :table (org-table-begin) (org-table-end)) clist)
21538 (if (memq 'org-formula faces)
21539 (push (list :table-special
21540 (previous-single-property-change p 'face)
21541 (next-single-property-change p 'face)) clist)))
21542 ((org-at-table-p 'any)
21543 (push (list :table-table) clist)))
21544 (goto-char p)
21546 (let ((case-fold-search t))
21547 ;; New the "medium" contexts: clocktables, source blocks
21548 (cond ((org-in-clocktable-p)
21549 (push (list :clocktable
21550 (and (or (looking-at "#\\+BEGIN: clocktable")
21551 (search-backward "#+BEGIN: clocktable" nil t))
21552 (match-beginning 0))
21553 (and (re-search-forward "#\\+END:?" nil t)
21554 (match-end 0))) clist))
21555 ((org-in-src-block-p)
21556 (push (list :src-block
21557 (and (or (looking-at "#\\+BEGIN_SRC")
21558 (search-backward "#+BEGIN_SRC" nil t))
21559 (match-beginning 0))
21560 (and (search-forward "#+END_SRC" nil t)
21561 (match-beginning 0))) clist))))
21562 (goto-char p)
21564 ;; Now the small context
21565 (cond
21566 ((org-at-timestamp-p)
21567 (push (org-point-in-group p 0 :timestamp) clist))
21568 ((memq 'org-link faces)
21569 (push (list :link
21570 (previous-single-property-change p 'face)
21571 (next-single-property-change p 'face)) clist))
21572 ((memq 'org-special-keyword faces)
21573 (push (list :keyword
21574 (previous-single-property-change p 'face)
21575 (next-single-property-change p 'face)) clist))
21576 ((org-at-target-p)
21577 (push (org-point-in-group p 0 :target) clist)
21578 (goto-char (1- (match-beginning 0)))
21579 (if (looking-at org-radio-target-regexp)
21580 (push (org-point-in-group p 0 :radio-target) clist))
21581 (goto-char p))
21582 ((setq o (car (delq nil
21583 (mapcar
21584 (lambda (x)
21585 (if (memq x org-latex-fragment-image-overlays) x))
21586 (overlays-at (point))))))
21587 (push (list :latex-fragment
21588 (overlay-start o) (overlay-end o)) clist)
21589 (push (list :latex-preview
21590 (overlay-start o) (overlay-end o)) clist))
21591 ((org-inside-LaTeX-fragment-p)
21592 ;; FIXME: positions wrong.
21593 (push (list :latex-fragment (point) (point)) clist)))
21595 (setq clist (nreverse (delq nil clist)))
21596 clist))
21598 ;; FIXME: Compare with at-regexp-p Do we need both?
21599 (defun org-in-regexp (re &optional nlines visually)
21600 "Check if point is inside a match of regexp.
21601 Normally only the current line is checked, but you can include NLINES extra
21602 lines both before and after point into the search.
21603 If VISUALLY is set, require that the cursor is not after the match but
21604 really on, so that the block visually is on the match."
21605 (catch 'exit
21606 (let ((pos (point))
21607 (eol (point-at-eol (+ 1 (or nlines 0))))
21608 (inc (if visually 1 0)))
21609 (save-excursion
21610 (beginning-of-line (- 1 (or nlines 0)))
21611 (while (re-search-forward re eol t)
21612 (if (and (<= (match-beginning 0) pos)
21613 (>= (+ inc (match-end 0)) pos))
21614 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21616 (defun org-at-regexp-p (regexp)
21617 "Is point inside a match of REGEXP in the current line?"
21618 (catch 'exit
21619 (save-excursion
21620 (let ((pos (point)) (end (point-at-eol)))
21621 (beginning-of-line 1)
21622 (while (re-search-forward regexp end t)
21623 (if (and (<= (match-beginning 0) pos)
21624 (>= (match-end 0) pos))
21625 (throw 'exit t)))
21626 nil))))
21628 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21629 "Non-nil when point is between matches of START-RE and END-RE.
21631 Also return a non-nil value when point is on one of the matches.
21633 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21634 buffer positions. Default values are the positions of headlines
21635 surrounding the point.
21637 The functions returns a cons cell whose car (resp. cdr) is the
21638 position before START-RE (resp. after END-RE)."
21639 (save-match-data
21640 (let ((pos (point))
21641 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21642 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21643 beg end)
21644 (save-excursion
21645 ;; Point is on a block when on START-RE or if START-RE can be
21646 ;; found before it...
21647 (and (or (org-at-regexp-p start-re)
21648 (re-search-backward start-re limit-up t))
21649 (setq beg (match-beginning 0))
21650 ;; ... and END-RE after it...
21651 (goto-char (match-end 0))
21652 (re-search-forward end-re limit-down t)
21653 (> (setq end (match-end 0)) pos)
21654 ;; ... without another START-RE in-between.
21655 (goto-char (match-beginning 0))
21656 (not (re-search-backward start-re (1+ beg) t))
21657 ;; Return value.
21658 (cons beg end))))))
21660 (defun org-in-block-p (names)
21661 "Non-nil when point belongs to a block whose name belongs to NAMES.
21663 NAMES is a list of strings containing names of blocks.
21665 Return first block name matched, or nil. Beware that in case of
21666 nested blocks, the returned name may not belong to the closest
21667 block from point."
21668 (save-match-data
21669 (catch 'exit
21670 (let ((case-fold-search t)
21671 (lim-up (save-excursion (outline-previous-heading)))
21672 (lim-down (save-excursion (outline-next-heading))))
21673 (mapc (lambda (name)
21674 (let ((n (regexp-quote name)))
21675 (when (org-between-regexps-p
21676 (concat "^[ \t]*#\\+begin_" n)
21677 (concat "^[ \t]*#\\+end_" n)
21678 lim-up lim-down)
21679 (throw 'exit n))))
21680 names))
21681 nil)))
21683 (defun org-in-drawer-p ()
21684 "Is point within a drawer?"
21685 (save-match-data
21686 (let ((case-fold-search t)
21687 (lim-up (save-excursion (outline-previous-heading)))
21688 (lim-down (save-excursion (outline-next-heading))))
21689 (org-between-regexps-p
21690 (concat "^[ \t]*:" (regexp-opt org-drawers) ":")
21691 "^[ \t]*:end:.*$"
21692 lim-up lim-down))))
21694 (defun org-occur-in-agenda-files (regexp &optional nlines)
21695 "Call `multi-occur' with buffers for all agenda files."
21696 (interactive "sOrg-files matching: \np")
21697 (let* ((files (org-agenda-files))
21698 (tnames (mapcar 'file-truename files))
21699 (extra org-agenda-text-search-extra-files)
21701 (when (eq (car extra) 'agenda-archives)
21702 (setq extra (cdr extra))
21703 (setq files (org-add-archive-files files)))
21704 (while (setq f (pop extra))
21705 (unless (member (file-truename f) tnames)
21706 (add-to-list 'files f 'append)
21707 (add-to-list 'tnames (file-truename f) 'append)))
21708 (multi-occur
21709 (mapcar (lambda (x)
21710 (with-current-buffer
21711 (or (get-file-buffer x) (find-file-noselect x))
21712 (widen)
21713 (current-buffer)))
21714 files)
21715 regexp)))
21717 (if (boundp 'occur-mode-find-occurrence-hook)
21718 ;; Emacs 23
21719 (add-hook 'occur-mode-find-occurrence-hook
21720 (lambda ()
21721 (when (derived-mode-p 'org-mode)
21722 (org-reveal))))
21723 ;; Emacs 22
21724 (defadvice occur-mode-goto-occurrence
21725 (after org-occur-reveal activate)
21726 (and (derived-mode-p 'org-mode) (org-reveal)))
21727 (defadvice occur-mode-goto-occurrence-other-window
21728 (after org-occur-reveal activate)
21729 (and (derived-mode-p 'org-mode) (org-reveal)))
21730 (defadvice occur-mode-display-occurrence
21731 (after org-occur-reveal activate)
21732 (when (derived-mode-p 'org-mode)
21733 (let ((pos (occur-mode-find-occurrence)))
21734 (with-current-buffer (marker-buffer pos)
21735 (save-excursion
21736 (goto-char pos)
21737 (org-reveal)))))))
21739 (defun org-occur-link-in-agenda-files ()
21740 "Create a link and search for it in the agendas.
21741 The link is not stored in `org-stored-links', it is just created
21742 for the search purpose."
21743 (interactive)
21744 (let ((link (condition-case nil
21745 (org-store-link nil)
21746 (error "Unable to create a link to here"))))
21747 (org-occur-in-agenda-files (regexp-quote link))))
21749 (defun org-reverse-string (string)
21750 "Return the reverse of STRING."
21751 (apply 'string (reverse (string-to-list string))))
21753 (defsubst org-uniquify (list)
21754 "Non-destructively remove duplicate elements from LIST."
21755 (let ((res (copy-sequence list))) (delete-dups res)))
21757 (defun org-uniquify-alist (alist)
21758 "Merge elements of ALIST with the same key.
21760 For example, in this alist:
21762 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
21763 => '((a 1 3) (b 2))
21765 merge (a 1) and (a 3) into (a 1 3).
21767 The function returns the new ALIST."
21768 (let (rtn)
21769 (mapc
21770 (lambda (e)
21771 (let (n)
21772 (if (not (assoc (car e) rtn))
21773 (push e rtn)
21774 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
21775 (setq rtn (assq-delete-all (car e) rtn))
21776 (push n rtn))))
21777 alist)
21778 rtn))
21780 (defun org-delete-all (elts list)
21781 "Remove all elements in ELTS from LIST."
21782 (while elts
21783 (setq list (delete (pop elts) list)))
21784 list)
21786 (defun org-count (cl-item cl-seq)
21787 "Count the number of occurrences of ITEM in SEQ.
21788 Taken from `count' in cl-seq.el with all keyword arguments removed."
21789 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21790 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21791 (while (< cl-start cl-end)
21792 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21793 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21794 (setq cl-start (1+ cl-start)))
21795 cl-count))
21797 (defun org-remove-if (predicate seq)
21798 "Remove everything from SEQ that fulfills PREDICATE."
21799 (let (res e)
21800 (while seq
21801 (setq e (pop seq))
21802 (if (not (funcall predicate e)) (push e res)))
21803 (nreverse res)))
21805 (defun org-remove-if-not (predicate seq)
21806 "Remove everything from SEQ that does not fulfill PREDICATE."
21807 (let (res e)
21808 (while seq
21809 (setq e (pop seq))
21810 (if (funcall predicate e) (push e res)))
21811 (nreverse res)))
21813 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21814 "Reduce two-argument FUNCTION across SEQ.
21815 Taken from `reduce' in cl-seq.el with all keyword arguments but
21816 \":initial-value\" removed."
21817 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21818 (cadr (memq :initial-value cl-keys)))
21819 (cl-seq (pop cl-seq))
21820 (t (funcall cl-func)))))
21821 (while cl-seq
21822 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21823 cl-accum))
21825 (defun org-every (pred seq)
21826 "Return true if PREDICATE is true of every element of SEQ.
21827 Adapted from `every' in cl.el."
21828 (catch 'org-every
21829 (mapc (lambda (e) (unless (funcall pred e) (throw 'org-every nil))) seq)
21832 (defun org-some (pred seq)
21833 "Return true if PREDICATE is true of any element of SEQ.
21834 Adapted from `some' in cl.el."
21835 (catch 'org-some
21836 (mapc (lambda (e) (when (funcall pred e) (throw 'org-some t))) seq)
21837 nil))
21839 (defun org-back-over-empty-lines ()
21840 "Move backwards over whitespace, to the beginning of the first empty line.
21841 Returns the number of empty lines passed."
21842 (let ((pos (point)))
21843 (if (cdr (assoc 'heading org-blank-before-new-entry))
21844 (skip-chars-backward " \t\n\r")
21845 (unless (eobp)
21846 (forward-line -1)))
21847 (beginning-of-line 2)
21848 (goto-char (min (point) pos))
21849 (count-lines (point) pos)))
21851 (defun org-skip-whitespace ()
21852 (skip-chars-forward " \t\n\r"))
21854 (defun org-point-in-group (point group &optional context)
21855 "Check if POINT is in match-group GROUP.
21856 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21857 match. If the match group does not exist or point is not inside it,
21858 return nil."
21859 (and (match-beginning group)
21860 (>= point (match-beginning group))
21861 (<= point (match-end group))
21862 (if context
21863 (list context (match-beginning group) (match-end group))
21864 t)))
21866 (defun org-switch-to-buffer-other-window (&rest args)
21867 "Switch to buffer in a second window on the current frame.
21868 In particular, do not allow pop-up frames.
21869 Returns the newly created buffer."
21870 (org-no-popups
21871 (apply 'switch-to-buffer-other-window args)))
21873 (defun org-combine-plists (&rest plists)
21874 "Create a single property list from all plists in PLISTS.
21875 The process starts by copying the first list, and then setting properties
21876 from the other lists. Settings in the last list are the most significant
21877 ones and overrule settings in the other lists."
21878 (let ((rtn (copy-sequence (pop plists)))
21879 p v ls)
21880 (while plists
21881 (setq ls (pop plists))
21882 (while ls
21883 (setq p (pop ls) v (pop ls))
21884 (setq rtn (plist-put rtn p v))))
21885 rtn))
21887 (defun org-replace-escapes (string table)
21888 "Replace %-escapes in STRING with values in TABLE.
21889 TABLE is an association list with keys like \"%a\" and string values.
21890 The sequences in STRING may contain normal field width and padding information,
21891 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21892 so values can contain further %-escapes if they are define later in TABLE."
21893 (let ((tbl (copy-alist table))
21894 (case-fold-search nil)
21895 (pchg 0)
21896 e re rpl)
21897 (while (setq e (pop tbl))
21898 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21899 (when (and (cdr e) (string-match re (cdr e)))
21900 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21901 (safe "SREF"))
21902 (add-text-properties 0 3 (list 'sref sref) safe)
21903 (setcdr e (replace-match safe t t (cdr e)))))
21904 (while (string-match re string)
21905 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21906 (cdr e)))
21907 (setq string (replace-match rpl t t string))))
21908 (while (setq pchg (next-property-change pchg string))
21909 (let ((sref (get-text-property pchg 'sref string)))
21910 (when (and sref (string-match "SREF" string pchg))
21911 (setq string (replace-match sref t t string)))))
21912 string))
21914 (defun org-sublist (list start end)
21915 "Return a section of LIST, from START to END.
21916 Counting starts at 1."
21917 (let (rtn (c start))
21918 (setq list (nthcdr (1- start) list))
21919 (while (and list (<= c end))
21920 (push (pop list) rtn)
21921 (setq c (1+ c)))
21922 (nreverse rtn)))
21924 (defun org-find-base-buffer-visiting (file)
21925 "Like `find-buffer-visiting' but always return the base buffer and
21926 not an indirect buffer."
21927 (let ((buf (or (get-file-buffer file)
21928 (find-buffer-visiting file))))
21929 (if buf
21930 (or (buffer-base-buffer buf) buf)
21931 nil)))
21933 (defun org-image-file-name-regexp (&optional extensions)
21934 "Return regexp matching the file names of images.
21935 If EXTENSIONS is given, only match these."
21936 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21937 (image-file-name-regexp)
21938 (let ((image-file-name-extensions
21939 (or extensions
21940 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21941 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21942 (concat "\\."
21943 (regexp-opt (nconc (mapcar 'upcase
21944 image-file-name-extensions)
21945 image-file-name-extensions)
21947 "\\'"))))
21949 (defun org-file-image-p (file &optional extensions)
21950 "Return non-nil if FILE is an image."
21951 (save-match-data
21952 (string-match (org-image-file-name-regexp extensions) file)))
21954 (defun org-get-cursor-date (&optional with-time)
21955 "Return the date at cursor in as a time.
21956 This works in the calendar and in the agenda, anywhere else it just
21957 returns the current time.
21958 If WITH-TIME is non-nil, returns the time of the event at point (in
21959 the agenda) or the current time of the day."
21960 (let (date day defd tp tm hod mod)
21961 (when with-time
21962 (setq tp (get-text-property (point) 'time))
21963 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21964 (setq hod (string-to-number (match-string 1 tp))
21965 mod (string-to-number (match-string 2 tp))))
21966 (or tp (setq hod (nth 2 (decode-time (current-time)))
21967 mod (nth 1 (decode-time (current-time))))))
21968 (cond
21969 ((eq major-mode 'calendar-mode)
21970 (setq date (calendar-cursor-to-date)
21971 defd (encode-time 0 (or mod 0) (or hod 0)
21972 (nth 1 date) (nth 0 date) (nth 2 date))))
21973 ((eq major-mode 'org-agenda-mode)
21974 (setq day (get-text-property (point) 'day))
21975 (if day
21976 (setq date (calendar-gregorian-from-absolute day)
21977 defd (encode-time 0 (or mod 0) (or hod 0)
21978 (nth 1 date) (nth 0 date) (nth 2 date))))))
21979 (or defd (current-time))))
21981 (defun org-mark-subtree (&optional up)
21982 "Mark the current subtree.
21983 This puts point at the start of the current subtree, and mark at
21984 the end. If a numeric prefix UP is given, move up into the
21985 hierarchy of headlines by UP levels before marking the subtree."
21986 (interactive "P")
21987 (org-with-limited-levels
21988 (cond ((org-at-heading-p) (beginning-of-line))
21989 ((org-before-first-heading-p) (user-error "Not in a subtree"))
21990 (t (outline-previous-visible-heading 1))))
21991 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21992 (if (org-called-interactively-p 'any)
21993 (call-interactively 'org-mark-element)
21994 (org-mark-element)))
21997 ;;; Indentation
21999 (defun org-indent-line ()
22000 "Indent line depending on context."
22001 (interactive)
22002 (let* ((pos (point))
22003 (itemp (org-at-item-p))
22004 (case-fold-search t)
22005 (org-drawer-regexp (or org-drawer-regexp "\000"))
22006 (inline-task-p (and (featurep 'org-inlinetask)
22007 (org-inlinetask-in-task-p)))
22008 (inline-re (and inline-task-p
22009 (org-inlinetask-outline-regexp)))
22010 column)
22011 (if (and orgstruct-is-++ (eq pos (point)))
22012 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
22013 (indent-according-to-mode))
22014 (beginning-of-line 1)
22015 (cond
22016 ;; Headings
22017 ((looking-at org-outline-regexp) (setq column 0))
22018 ;; Footnote definition
22019 ((looking-at org-footnote-definition-re) (setq column 0))
22020 ;; Literal examples
22021 ((looking-at "[ \t]*:\\( \\|$\\)")
22022 (setq column (org-get-indentation))) ; do nothing
22023 ;; Lists
22024 ((ignore-errors (goto-char (org-in-item-p)))
22025 (setq column (if itemp
22026 (org-get-indentation)
22027 (org-list-item-body-column (point))))
22028 (goto-char pos))
22029 ;; Drawers
22030 ((and (looking-at "[ \t]*:END:")
22031 (save-excursion (re-search-backward org-drawer-regexp nil t)))
22032 (save-excursion
22033 (goto-char (1- (match-beginning 1)))
22034 (setq column (current-column))))
22035 ;; Special blocks
22036 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
22037 (save-excursion
22038 (re-search-backward
22039 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
22040 (setq column (org-get-indentation (match-string 0))))
22041 ((and (not (looking-at "[ \t]*#\\+begin_"))
22042 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
22043 (save-excursion
22044 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
22045 (setq column
22046 (cond ((equal (downcase (match-string 1)) "src")
22047 ;; src blocks: let `org-edit-src-exit' handle them
22048 (org-get-indentation))
22049 ((equal (downcase (match-string 1)) "example")
22050 (max (org-get-indentation)
22051 (org-get-indentation (match-string 0))))
22053 (org-get-indentation (match-string 0))))))
22054 ;; This line has nothing special, look at the previous relevant
22055 ;; line to compute indentation
22057 (beginning-of-line 0)
22058 (while (and (not (bobp))
22059 (not (looking-at org-table-line-regexp))
22060 (not (looking-at org-drawer-regexp))
22061 ;; When point started in an inline task, do not move
22062 ;; above task starting line.
22063 (not (and inline-task-p (looking-at inline-re)))
22064 ;; Skip drawers, blocks, empty lines, verbatim,
22065 ;; comments, tables, footnotes definitions, lists,
22066 ;; inline tasks.
22067 (or (and (looking-at "[ \t]*:END:")
22068 (re-search-backward org-drawer-regexp nil t))
22069 (and (looking-at "[ \t]*#\\+end_")
22070 (re-search-backward "[ \t]*#\\+begin_"nil t))
22071 (looking-at "[ \t]*[\n:#|]")
22072 (looking-at org-footnote-definition-re)
22073 (and (not inline-task-p)
22074 (featurep 'org-inlinetask)
22075 (org-inlinetask-in-task-p)
22076 (or (org-inlinetask-goto-beginning) t))))
22077 (beginning-of-line 0))
22078 (cond
22079 ;; There was a list item above.
22080 ((ignore-errors (goto-char (org-in-item-p)))
22081 (goto-char (org-list-get-top-point (org-list-struct)))
22082 (setq column (org-get-indentation)))
22083 ;; There was an heading above.
22084 ((looking-at "\\*+[ \t]+")
22085 (if (not org-adapt-indentation)
22086 (setq column 0)
22087 (goto-char (match-end 0))
22088 (setq column (current-column))))
22089 ;; A drawer had started and is unfinished
22090 ((looking-at org-drawer-regexp)
22091 (goto-char (1- (match-beginning 1)))
22092 (setq column (current-column)))
22093 ;; Else, nothing noticeable found: get indentation and go on.
22094 (t (setq column (org-get-indentation))))))
22095 ;; Now apply indentation and move cursor accordingly
22096 (goto-char pos)
22097 (if (<= (current-column) (current-indentation))
22098 (org-indent-line-to column)
22099 (save-excursion (org-indent-line-to column)))
22100 ;; Special polishing for properties, see `org-property-format'
22101 (setq column (current-column))
22102 (beginning-of-line 1)
22103 (if (looking-at org-property-re)
22104 (replace-match (concat (match-string 4)
22105 (format org-property-format
22106 (match-string 1) (match-string 3)))
22107 t t))
22108 (org-move-to-column column))))
22110 (defun org-indent-drawer ()
22111 "Indent the drawer at point."
22112 (interactive)
22113 (let ((p (point))
22114 (e (and (save-excursion (re-search-forward ":END:" nil t))
22115 (match-end 0)))
22116 (folded
22117 (save-excursion
22118 (end-of-line)
22119 (when (overlays-at (point))
22120 (member 'invisible (overlay-properties
22121 (car (overlays-at (point)))))))))
22122 (when folded (org-cycle))
22123 (indent-for-tab-command)
22124 (while (and (move-beginning-of-line 2) (< (point) e))
22125 (indent-for-tab-command))
22126 (goto-char p)
22127 (when folded (org-cycle)))
22128 (message "Drawer at point indented"))
22130 (defun org-indent-block ()
22131 "Indent the block at point."
22132 (interactive)
22133 (let ((p (point))
22134 (case-fold-search t)
22135 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
22136 (match-end 0)))
22137 (folded
22138 (save-excursion
22139 (end-of-line)
22140 (when (overlays-at (point))
22141 (member 'invisible (overlay-properties
22142 (car (overlays-at (point)))))))))
22143 (when folded (org-cycle))
22144 (indent-for-tab-command)
22145 (while (and (move-beginning-of-line 2) (< (point) e))
22146 (indent-for-tab-command))
22147 (goto-char p)
22148 (when folded (org-cycle)))
22149 (message "Block at point indented"))
22151 (defun org-indent-region (start end)
22152 "Indent region."
22153 (interactive "r")
22154 (save-excursion
22155 (let ((line-end (org-current-line end)))
22156 (goto-char start)
22157 (while (< (org-current-line) line-end)
22158 (cond ((org-in-src-block-p t) (org-src-native-tab-command-maybe))
22159 (t (call-interactively 'org-indent-line)))
22160 (move-beginning-of-line 2)))))
22163 ;;; Filling
22165 ;; We use our own fill-paragraph and auto-fill functions.
22167 ;; `org-fill-paragraph' relies on adaptive filling and context
22168 ;; checking. Appropriate `fill-prefix' is computed with
22169 ;; `org-adaptive-fill-function'.
22171 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22172 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22173 ;; `org-adaptive-fill-function' value. Internally,
22174 ;; `org-comment-line-break-function' breaks the line.
22176 ;; `org-setup-filling' installs filling and auto-filling related
22177 ;; variables during `org-mode' initialization.
22179 (defvar org-element-paragraph-separate) ; org-element.el
22180 (defun org-setup-filling ()
22181 (require 'org-element)
22182 ;; Prevent auto-fill from inserting unwanted new items.
22183 (when (boundp 'fill-nobreak-predicate)
22184 (org-set-local
22185 'fill-nobreak-predicate
22186 (org-uniquify
22187 (append fill-nobreak-predicate
22188 '(org-fill-line-break-nobreak-p
22189 org-fill-paragraph-with-timestamp-nobreak-p)))))
22190 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22191 (org-set-local 'paragraph-start paragraph-ending)
22192 (org-set-local 'paragraph-separate paragraph-ending))
22193 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22194 (org-set-local 'auto-fill-inhibit-regexp nil)
22195 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22196 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22197 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22199 (defun org-fill-line-break-nobreak-p ()
22200 "Non-nil when a new line at point would create an Org line break."
22201 (save-excursion
22202 (skip-chars-backward "[ \t]")
22203 (skip-chars-backward "\\\\")
22204 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22206 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22207 "Non-nil when a new line at point would split a timestamp."
22208 (and (org-at-timestamp-p t)
22209 (not (looking-at org-ts-regexp-both))))
22211 (declare-function message-in-body-p "message" ())
22212 (defvar orgtbl-line-start-regexp) ; From org-table.el
22213 (defun org-adaptive-fill-function ()
22214 "Compute a fill prefix for the current line.
22215 Return fill prefix, as a string, or nil if current line isn't
22216 meant to be filled. For convenience, if `adaptive-fill-regexp'
22217 matches in paragraphs or comments, use it."
22218 (catch 'exit
22219 (when (derived-mode-p 'message-mode)
22220 (save-excursion
22221 (beginning-of-line)
22222 (cond ((or (not (message-in-body-p))
22223 (looking-at orgtbl-line-start-regexp))
22224 (throw 'exit nil))
22225 ((looking-at message-cite-prefix-regexp)
22226 (throw 'exit (match-string-no-properties 0)))
22227 ((looking-at org-outline-regexp)
22228 (throw 'exit (make-string (length (match-string 0)) ? ))))))
22229 (org-with-wide-buffer
22230 (let* ((p (line-beginning-position))
22231 (element (save-excursion
22232 (beginning-of-line)
22233 (or (ignore-errors (org-element-at-point))
22234 (user-error "An element cannot be parsed line %d"
22235 (line-number-at-pos (point))))))
22236 (type (org-element-type element))
22237 (post-affiliated (org-element-property :post-affiliated element)))
22238 (unless (and post-affiliated (< p post-affiliated))
22239 (case type
22240 (comment
22241 (save-excursion
22242 (beginning-of-line)
22243 (looking-at "[ \t]*")
22244 (concat (match-string 0) "# ")))
22245 (footnote-definition "")
22246 ((item plain-list)
22247 (make-string (org-list-item-body-column
22248 (or post-affiliated
22249 (org-element-property :begin element)))
22250 ? ))
22251 (paragraph
22252 ;; Fill prefix is usually the same as the current line,
22253 ;; unless the paragraph is at the beginning of an item.
22254 (let ((parent (org-element-property :parent element)))
22255 (save-excursion
22256 (beginning-of-line)
22257 (cond ((eq (org-element-type parent) 'item)
22258 (make-string (org-list-item-body-column
22259 (org-element-property :begin parent))
22260 ? ))
22261 ((and adaptive-fill-regexp
22262 ;; Locally disable
22263 ;; `adaptive-fill-function' to let
22264 ;; `fill-context-prefix' handle
22265 ;; `adaptive-fill-regexp' variable.
22266 (let (adaptive-fill-function)
22267 (fill-context-prefix
22268 post-affiliated
22269 (org-element-property :end element)))))
22270 ((looking-at "[ \t]+") (match-string 0))
22271 (t "")))))
22272 (comment-block
22273 ;; Only fill contents if P is within block boundaries.
22274 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22275 (forward-line)
22276 (point)))
22277 (cend (save-excursion
22278 (goto-char (org-element-property :end element))
22279 (skip-chars-backward " \r\t\n")
22280 (line-beginning-position))))
22281 (when (and (>= p cbeg) (< p cend))
22282 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22283 (match-string 0)
22284 ""))))))))))
22286 (declare-function message-goto-body "message" ())
22287 (defvar message-cite-prefix-regexp) ; From message.el
22288 (defun org-fill-paragraph (&optional justify)
22289 "Fill element at point, when applicable.
22291 This function only applies to comment blocks, comments, example
22292 blocks and paragraphs. Also, as a special case, re-align table
22293 when point is at one.
22295 If JUSTIFY is non-nil (interactively, with prefix argument),
22296 justify as well. If `sentence-end-double-space' is non-nil, then
22297 period followed by one space does not end a sentence, so don't
22298 break a line there. The variable `fill-column' controls the
22299 width for filling.
22301 For convenience, when point is at a plain list, an item or
22302 a footnote definition, try to fill the first paragraph within."
22303 (interactive)
22304 (if (and (derived-mode-p 'message-mode)
22305 (or (not (message-in-body-p))
22306 (save-excursion (move-beginning-of-line 1)
22307 (looking-at message-cite-prefix-regexp))))
22308 ;; First ensure filling is correct in message-mode.
22309 (let ((fill-paragraph-function
22310 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22311 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22312 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22313 (paragraph-separate
22314 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22315 (fill-paragraph nil))
22316 (with-syntax-table org-mode-transpose-word-syntax-table
22317 ;; Move to end of line in order to get the first paragraph
22318 ;; within a plain list or a footnote definition.
22319 (let ((element (save-excursion
22320 (end-of-line)
22321 (or (ignore-errors (org-element-at-point))
22322 (user-error "An element cannot be parsed line %d"
22323 (line-number-at-pos (point)))))))
22324 ;; First check if point is in a blank line at the beginning of
22325 ;; the buffer. In that case, ignore filling.
22326 (case (org-element-type element)
22327 ;; Use major mode filling function is src blocks.
22328 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22329 ;; Align Org tables, leave table.el tables as-is.
22330 (table-row (org-table-align) t)
22331 (table
22332 (when (eq (org-element-property :type element) 'org)
22333 (save-excursion
22334 (goto-char (org-element-property :post-affiliated element))
22335 (org-table-align)))
22337 (paragraph
22338 ;; Paragraphs may contain `line-break' type objects.
22339 (let ((beg (max (point-min)
22340 (org-element-property :contents-begin element)))
22341 (end (min (point-max)
22342 (org-element-property :contents-end element))))
22343 ;; Do nothing if point is at an affiliated keyword.
22344 (if (< (line-end-position) beg) t
22345 (when (derived-mode-p 'message-mode)
22346 ;; In `message-mode', do not fill following citation
22347 ;; in current paragraph nor text before message body.
22348 (let ((body-start (save-excursion (message-goto-body))))
22349 (when body-start (setq beg (max body-start beg))))
22350 (when (save-excursion
22351 (re-search-forward
22352 (concat "^" message-cite-prefix-regexp) end t))
22353 (setq end (match-beginning 0))))
22354 ;; Fill paragraph, taking line breaks into account.
22355 ;; For that, slice the paragraph using line breaks as
22356 ;; separators, and fill the parts in reverse order to
22357 ;; avoid messing with markers.
22358 (save-excursion
22359 (goto-char end)
22360 (mapc
22361 (lambda (pos)
22362 (fill-region-as-paragraph pos (point) justify)
22363 (goto-char pos))
22364 ;; Find the list of ending positions for line breaks
22365 ;; in the current paragraph. Add paragraph
22366 ;; beginning to include first slice.
22367 (nreverse
22368 (cons beg
22369 (org-element-map
22370 (org-element--parse-objects
22371 beg end nil (org-element-restriction 'paragraph))
22372 'line-break
22373 (lambda (lb) (org-element-property :end lb)))))))
22374 t)))
22375 ;; Contents of `comment-block' type elements should be
22376 ;; filled as plain text, but only if point is within block
22377 ;; markers.
22378 (comment-block
22379 (let* ((case-fold-search t)
22380 (beg (save-excursion
22381 (goto-char (org-element-property :begin element))
22382 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22383 (forward-line)
22384 (point)))
22385 (end (save-excursion
22386 (goto-char (org-element-property :end element))
22387 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22388 (line-beginning-position))))
22389 (if (or (< (point) beg) (> (point) end)) t
22390 (fill-region-as-paragraph
22391 (save-excursion (end-of-line)
22392 (re-search-backward "^[ \t]*$" beg 'move)
22393 (line-beginning-position))
22394 (save-excursion (beginning-of-line)
22395 (re-search-forward "^[ \t]*$" end 'move)
22396 (line-beginning-position))
22397 justify))))
22398 ;; Fill comments.
22399 (comment
22400 (let ((begin (org-element-property :post-affiliated element))
22401 (end (org-element-property :end element)))
22402 (when (and (>= (point) begin) (<= (point) end))
22403 (let ((begin (save-excursion
22404 (end-of-line)
22405 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22406 (progn (forward-line) (point))
22407 begin)))
22408 (end (save-excursion
22409 (end-of-line)
22410 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22411 (1- (line-beginning-position))
22412 (skip-chars-backward " \r\t\n")
22413 (line-end-position)))))
22414 ;; Do not fill comments when at a blank line.
22415 (when (> end begin)
22416 (let ((fill-prefix
22417 (save-excursion
22418 (beginning-of-line)
22419 (looking-at "[ \t]*#")
22420 (let ((comment-prefix (match-string 0)))
22421 (goto-char (match-end 0))
22422 (if (looking-at adaptive-fill-regexp)
22423 (concat comment-prefix (match-string 0))
22424 (concat comment-prefix " "))))))
22425 (save-excursion
22426 (fill-region-as-paragraph begin end justify))))))
22428 ;; Ignore every other element.
22429 (otherwise t))))))
22431 (defun org-auto-fill-function ()
22432 "Auto-fill function."
22433 ;; Check if auto-filling is meaningful.
22434 (let ((fc (current-fill-column)))
22435 (when (and fc (> (current-column) fc))
22436 (let* ((fill-prefix (org-adaptive-fill-function))
22437 ;; Enforce empty fill prefix, if required. Otherwise, it
22438 ;; will be computed again.
22439 (adaptive-fill-mode (not (equal fill-prefix ""))))
22440 (when fill-prefix (do-auto-fill))))))
22442 (defun org-comment-line-break-function (&optional soft)
22443 "Break line at point and indent, continuing comment if within one.
22444 The inserted newline is marked hard if variable
22445 `use-hard-newlines' is true, unless optional argument SOFT is
22446 non-nil."
22447 (if soft (insert-and-inherit ?\n) (newline 1))
22448 (save-excursion (forward-char -1) (delete-horizontal-space))
22449 (delete-horizontal-space)
22450 (indent-to-left-margin)
22451 (insert-before-markers-and-inherit fill-prefix))
22454 ;;; Comments
22456 ;; Org comments syntax is quite complex. It requires the entire line
22457 ;; to be just a comment. Also, even with the right syntax at the
22458 ;; beginning of line, some some elements (i.e. verse-block or
22459 ;; example-block) don't accept comments. Usual Emacs comment commands
22460 ;; cannot cope with those requirements. Therefore, Org replaces them.
22462 ;; Org still relies on `comment-dwim', but cannot trust
22463 ;; `comment-only-p'. So, `comment-region-function' and
22464 ;; `uncomment-region-function' both point
22465 ;; to`org-comment-or-uncomment-region'. Eventually,
22466 ;; `org-insert-comment' takes care of insertion of comments at the
22467 ;; beginning of line.
22469 ;; `org-setup-comments-handling' install comments related variables
22470 ;; during `org-mode' initialization.
22472 (defun org-setup-comments-handling ()
22473 (interactive)
22474 (org-set-local 'comment-use-syntax nil)
22475 (org-set-local 'comment-start "# ")
22476 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22477 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22478 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22479 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22481 (defun org-insert-comment ()
22482 "Insert an empty comment above current line.
22483 If the line is empty, insert comment at its beginning."
22484 (beginning-of-line)
22485 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
22486 (org-indent-line)
22487 (insert "# "))
22489 (defvar comment-empty-lines) ; From newcomment.el.
22490 (defun org-comment-or-uncomment-region (beg end &rest ignore)
22491 "Comment or uncomment each non-blank line in the region.
22492 Uncomment each non-blank line between BEG and END if it only
22493 contains commented lines. Otherwise, comment them."
22494 (save-restriction
22495 ;; Restrict region
22496 (narrow-to-region (save-excursion (goto-char beg)
22497 (skip-chars-forward " \r\t\n" end)
22498 (line-beginning-position))
22499 (save-excursion (goto-char end)
22500 (skip-chars-backward " \r\t\n" beg)
22501 (line-end-position)))
22502 (let ((uncommentp
22503 ;; UNCOMMENTP is non-nil when every non blank line between
22504 ;; BEG and END is a comment.
22505 (save-excursion
22506 (goto-char (point-min))
22507 (while (and (not (eobp))
22508 (let ((element (org-element-at-point)))
22509 (and (eq (org-element-type element) 'comment)
22510 (goto-char (min (point-max)
22511 (org-element-property
22512 :end element)))))))
22513 (eobp))))
22514 (if uncommentp
22515 ;; Only blank lines and comments in region: uncomment it.
22516 (save-excursion
22517 (goto-char (point-min))
22518 (while (not (eobp))
22519 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22520 (replace-match "" nil nil nil 1))
22521 (forward-line)))
22522 ;; Comment each line in region.
22523 (let ((min-indent (point-max)))
22524 ;; First find the minimum indentation across all lines.
22525 (save-excursion
22526 (goto-char (point-min))
22527 (while (and (not (eobp)) (not (zerop min-indent)))
22528 (unless (looking-at "[ \t]*$")
22529 (setq min-indent (min min-indent (current-indentation))))
22530 (forward-line)))
22531 ;; Then loop over all lines.
22532 (save-excursion
22533 (goto-char (point-min))
22534 (while (not (eobp))
22535 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22536 ;; Don't get fooled by invisible text (e.g. link path)
22537 ;; when moving to column MIN-INDENT.
22538 (let ((buffer-invisibility-spec nil))
22539 (org-move-to-column min-indent t))
22540 (insert comment-start))
22541 (forward-line))))))))
22544 ;;; Planning
22546 ;; This section contains tools to operate on timestamp objects, as
22547 ;; returned by, e.g. `org-element-context'.
22549 (defun org-timestamp-has-time-p (timestamp)
22550 "Non-nil when TIMESTAMP has a time specified."
22551 (org-element-property :hour-start timestamp))
22553 (defun org-timestamp-format (timestamp format &optional end utc)
22554 "Format a TIMESTAMP element into a string.
22556 FORMAT is a format specifier to be passed to
22557 `format-time-string'.
22559 When optional argument END is non-nil, use end of date-range or
22560 time-range, if possible.
22562 When optional argument UTC is non-nil, time will be expressed as
22563 Universal Time."
22564 (format-time-string
22565 format
22566 (apply 'encode-time
22567 (cons 0
22568 (mapcar
22569 (lambda (prop) (or (org-element-property prop timestamp) 0))
22570 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22571 '(:minute-start :hour-start :day-start :month-start
22572 :year-start)))))
22573 utc))
22575 (defun org-timestamp-split-range (timestamp &optional end)
22576 "Extract a timestamp object from a date or time range.
22578 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22579 the end of the range. Otherwise, extract its start.
22581 Return a new timestamp object sharing the same parent as
22582 TIMESTAMP."
22583 (let ((type (org-element-property :type timestamp)))
22584 (if (memq type '(active inactive diary)) timestamp
22585 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22586 ;; Set new type.
22587 (org-element-put-property
22588 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22589 ;; Copy start properties over end properties if END is
22590 ;; non-nil. Otherwise, copy end properties over `start' ones.
22591 (let ((p-alist '((:minute-start . :minute-end)
22592 (:hour-start . :hour-end)
22593 (:day-start . :day-end)
22594 (:month-start . :month-end)
22595 (:year-start . :year-end))))
22596 (dolist (p-cell p-alist)
22597 (org-element-put-property
22598 split-ts
22599 (funcall (if end 'car 'cdr) p-cell)
22600 (org-element-property
22601 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22602 ;; Eventually refresh `:raw-value'.
22603 (org-element-put-property split-ts :raw-value nil)
22604 (org-element-put-property
22605 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22607 (defun org-timestamp-translate (timestamp &optional boundary)
22608 "Apply `org-translate-time' on a TIMESTAMP object.
22609 When optional argument BOUNDARY is non-nil, it is either the
22610 symbol `start' or `end'. In this case, only translate the
22611 starting or ending part of TIMESTAMP if it is a date or time
22612 range. Otherwise, translate both parts."
22613 (if (and (not boundary)
22614 (memq (org-element-property :type timestamp)
22615 '(active-range inactive-range)))
22616 (concat
22617 (org-translate-time
22618 (org-element-property :raw-value
22619 (org-timestamp-split-range timestamp)))
22620 "--"
22621 (org-translate-time
22622 (org-element-property :raw-value
22623 (org-timestamp-split-range timestamp t))))
22624 (org-translate-time
22625 (org-element-property
22626 :raw-value
22627 (if (not boundary) timestamp
22628 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22632 ;;; Other stuff.
22634 (defun org-toggle-fixed-width-section (arg)
22635 "Toggle the fixed-width export.
22636 If there is no active region, the QUOTE keyword at the current headline is
22637 inserted or removed. When present, it causes the text between this headline
22638 and the next to be exported as fixed-width text, and unmodified.
22639 If there is an active region, this command adds or removes a colon as the
22640 first character of this line. If the first character of a line is a colon,
22641 this line is also exported in fixed-width font."
22642 (interactive "P")
22643 (let* ((cc 0)
22644 (regionp (org-region-active-p))
22645 (beg (if regionp (region-beginning) (point)))
22646 (end (if regionp (region-end)))
22647 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22648 (case-fold-search nil)
22649 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22650 off)
22651 (if regionp
22652 (save-excursion
22653 (goto-char beg)
22654 (setq cc (current-column))
22655 (beginning-of-line 1)
22656 (setq off (looking-at re))
22657 (while (> nlines 0)
22658 (setq nlines (1- nlines))
22659 (beginning-of-line 1)
22660 (cond
22661 (arg
22662 (org-move-to-column cc t)
22663 (insert ": \n")
22664 (forward-line -1))
22665 ((and off (looking-at re))
22666 (replace-match "" t t nil 1))
22667 ((not off) (org-move-to-column cc t) (insert ": ")))
22668 (forward-line 1)))
22669 (save-excursion
22670 (org-back-to-heading)
22671 (cond
22672 ((looking-at (format org-heading-keyword-regexp-format
22673 org-quote-string))
22674 (goto-char (match-end 1))
22675 (looking-at (concat " +" org-quote-string))
22676 (replace-match "" t t)
22677 (when (eolp) (insert " ")))
22678 ((looking-at org-outline-regexp)
22679 (goto-char (match-end 0))
22680 (insert org-quote-string " ")))))))
22682 (defun org-reftex-citation ()
22683 "Use reftex-citation to insert a citation into the buffer.
22684 This looks for a line like
22686 #+BIBLIOGRAPHY: foo plain option:-d
22688 and derives from it that foo.bib is the bibliography file relevant
22689 for this document. It then installs the necessary environment for RefTeX
22690 to work in this buffer and calls `reftex-citation' to insert a citation
22691 into the buffer.
22693 Export of such citations to both LaTeX and HTML is handled by the contributed
22694 package ox-bibtex by Taru Karttunen."
22695 (interactive)
22696 (let ((reftex-docstruct-symbol 'rds)
22697 (reftex-cite-format "\\cite{%l}")
22698 rds bib)
22699 (save-excursion
22700 (save-restriction
22701 (widen)
22702 (let ((case-fold-search t)
22703 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22704 (if (not (save-excursion
22705 (or (re-search-forward re nil t)
22706 (re-search-backward re nil t))))
22707 (error "No bibliography defined in file")
22708 (setq bib (concat (match-string 1) ".bib")
22709 rds (list (list 'bib bib)))))))
22710 (call-interactively 'reftex-citation)))
22712 ;;;; Functions extending outline functionality
22714 (defun org-beginning-of-line (&optional arg)
22715 "Go to the beginning of the current line. If that is invisible, continue
22716 to a visible line beginning. This makes the function of C-a more intuitive.
22717 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22718 first attempt, and only move to after the tags when the cursor is already
22719 beyond the end of the headline."
22720 (interactive "P")
22721 (let ((pos (point))
22722 (special (if (consp org-special-ctrl-a/e)
22723 (car org-special-ctrl-a/e)
22724 org-special-ctrl-a/e))
22725 deactivate-mark refpos)
22726 (if (org-bound-and-true-p visual-line-mode)
22727 (beginning-of-visual-line 1)
22728 (beginning-of-line 1))
22729 (if (and arg (fboundp 'move-beginning-of-line))
22730 (call-interactively 'move-beginning-of-line)
22731 (if (bobp)
22733 (backward-char 1)
22734 (if (org-truely-invisible-p)
22735 (while (and (not (bobp)) (org-truely-invisible-p))
22736 (backward-char 1)
22737 (beginning-of-line 1))
22738 (forward-char 1))))
22739 (when special
22740 (cond
22741 ((and (looking-at org-complex-heading-regexp)
22742 (= (char-after (match-end 1)) ?\ ))
22743 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22744 (point-at-eol)))
22745 (goto-char
22746 (if (eq special t)
22747 (cond ((> pos refpos) refpos)
22748 ((= pos (point)) refpos)
22749 (t (point)))
22750 (cond ((> pos (point)) (point))
22751 ((not (eq last-command this-command)) (point))
22752 (t refpos)))))
22753 ((org-at-item-p)
22754 ;; Being at an item and not looking at an the item means point
22755 ;; was previously moved to beginning of a visual line, which
22756 ;; doesn't contain the item. Therefore, do nothing special,
22757 ;; just stay here.
22758 (when (looking-at org-list-full-item-re)
22759 ;; Set special position at first white space character after
22760 ;; bullet, and check-box, if any.
22761 (let ((after-bullet
22762 (let ((box (match-end 3)))
22763 (if (not box) (match-end 1)
22764 (let ((after (char-after box)))
22765 (if (and after (= after ? )) (1+ box) box))))))
22766 ;; Special case: Move point to special position when
22767 ;; currently after it or at beginning of line.
22768 (if (eq special t)
22769 (when (or (> pos after-bullet) (= (point) pos))
22770 (goto-char after-bullet))
22771 ;; Reversed case: Move point to special position when
22772 ;; point was already at beginning of line and command is
22773 ;; repeated.
22774 (when (and (= (point) pos) (eq last-command this-command))
22775 (goto-char after-bullet))))))))
22776 (org-no-warnings
22777 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22778 (setq disable-point-adjustment
22779 (or (not (invisible-p (point)))
22780 (not (invisible-p (max (point-min) (1- (point))))))))
22782 (defun org-end-of-line (&optional arg)
22783 "Go to the end of the line.
22784 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22785 tags on the first attempt, and only move to after the tags when
22786 the cursor is already beyond the end of the headline."
22787 (interactive "P")
22788 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22789 org-special-ctrl-a/e))
22790 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22791 'end-of-visual-line)
22792 ((fboundp 'move-end-of-line) 'move-end-of-line)
22793 (t 'end-of-line)))
22794 deactivate-mark)
22795 (if (or (not special) arg) (call-interactively move-fun)
22796 (let* ((element (save-excursion (beginning-of-line)
22797 (org-element-at-point)))
22798 (type (org-element-type element)))
22799 (cond
22800 ((memq type '(headline inlinetask))
22801 (let ((pos (point)))
22802 (beginning-of-line 1)
22803 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22804 (if (eq special t)
22805 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22806 (goto-char (match-beginning 1))
22807 (goto-char (match-end 0)))
22808 (if (or (< pos (match-end 0))
22809 (not (eq this-command last-command)))
22810 (goto-char (match-end 0))
22811 (goto-char (match-beginning 1))))
22812 (call-interactively move-fun))))
22813 ((org-element-property :hiddenp element)
22814 ;; If element is hidden, `move-end-of-line' would put point
22815 ;; after it. Use `end-of-line' to stay on current line.
22816 (call-interactively 'end-of-line))
22817 (t (call-interactively move-fun)))))
22818 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22819 (setq disable-point-adjustment
22820 (or (not (invisible-p (point)))
22821 (not (invisible-p (max (point-min) (1- (point))))))))
22823 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22824 (define-key org-mode-map "\C-e" 'org-end-of-line)
22826 (defun org-backward-sentence (&optional arg)
22827 "Go to beginning of sentence, or beginning of table field.
22828 This will call `backward-sentence' or `org-table-beginning-of-field',
22829 depending on context."
22830 (interactive "P")
22831 (cond
22832 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22833 (t (call-interactively 'backward-sentence))))
22835 (defun org-forward-sentence (&optional arg)
22836 "Go to end of sentence, or end of table field.
22837 This will call `forward-sentence' or `org-table-end-of-field',
22838 depending on context."
22839 (interactive "P")
22840 (cond
22841 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22842 (t (call-interactively 'forward-sentence))))
22844 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22845 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22847 (defun org-kill-line (&optional arg)
22848 "Kill line, to tags or end of line."
22849 (interactive "P")
22850 (cond
22851 ((or (not org-special-ctrl-k)
22852 (bolp)
22853 (not (org-at-heading-p)))
22854 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22855 org-ctrl-k-protect-subtree)
22856 (if (or (eq org-ctrl-k-protect-subtree 'error)
22857 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22858 (user-error "C-k aborted as it would kill a hidden subtree")))
22859 (call-interactively
22860 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22861 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22862 (kill-region (point) (match-beginning 1))
22863 (org-set-tags nil t))
22864 (t (kill-region (point) (point-at-eol)))))
22866 (define-key org-mode-map "\C-k" 'org-kill-line)
22868 (defun org-yank (&optional arg)
22869 "Yank. If the kill is a subtree, treat it specially.
22870 This command will look at the current kill and check if is a single
22871 subtree, or a series of subtrees[1]. If it passes the test, and if the
22872 cursor is at the beginning of a line or after the stars of a currently
22873 empty headline, then the yank is handled specially. How exactly depends
22874 on the value of the following variables, both set by default.
22876 org-yank-folded-subtrees
22877 When set, the subtree(s) will be folded after insertion, but only
22878 if doing so would now swallow text after the yanked text.
22880 org-yank-adjusted-subtrees
22881 When set, the subtree will be promoted or demoted in order to
22882 fit into the local outline tree structure, which means that the level
22883 will be adjusted so that it becomes the smaller one of the two
22884 *visible* surrounding headings.
22886 Any prefix to this command will cause `yank' to be called directly with
22887 no special treatment. In particular, a simple \\[universal-argument] prefix \
22888 will just
22889 plainly yank the text as it is.
22891 \[1] The test checks if the first non-white line is a heading
22892 and if there are no other headings with fewer stars."
22893 (interactive "P")
22894 (org-yank-generic 'yank arg))
22896 (defun org-yank-generic (command arg)
22897 "Perform some yank-like command.
22899 This function implements the behavior described in the `org-yank'
22900 documentation. However, it has been generalized to work for any
22901 interactive command with similar behavior."
22903 ;; pretend to be command COMMAND
22904 (setq this-command command)
22906 (if arg
22907 (call-interactively command)
22909 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22910 (and (org-kill-is-subtree-p)
22911 (or (bolp)
22912 (and (looking-at "[ \t]*$")
22913 (string-match
22914 "\\`\\*+\\'"
22915 (buffer-substring (point-at-bol) (point)))))))
22916 swallowp)
22917 (cond
22918 ((and subtreep org-yank-folded-subtrees)
22919 (let ((beg (point))
22920 end)
22921 (if (and subtreep org-yank-adjusted-subtrees)
22922 (org-paste-subtree nil nil 'for-yank)
22923 (call-interactively command))
22925 (setq end (point))
22926 (goto-char beg)
22927 (when (and (bolp) subtreep
22928 (not (setq swallowp
22929 (org-yank-folding-would-swallow-text beg end))))
22930 (org-with-limited-levels
22931 (or (looking-at org-outline-regexp)
22932 (re-search-forward org-outline-regexp-bol end t))
22933 (while (and (< (point) end) (looking-at org-outline-regexp))
22934 (hide-subtree)
22935 (org-cycle-show-empty-lines 'folded)
22936 (condition-case nil
22937 (outline-forward-same-level 1)
22938 (error (goto-char end))))))
22939 (when swallowp
22940 (message
22941 "Inserted text not folded because that would swallow text"))
22943 (goto-char end)
22944 (skip-chars-forward " \t\n\r")
22945 (beginning-of-line 1)
22946 (push-mark beg 'nomsg)))
22947 ((and subtreep org-yank-adjusted-subtrees)
22948 (let ((beg (point-at-bol)))
22949 (org-paste-subtree nil nil 'for-yank)
22950 (push-mark beg 'nomsg)))
22952 (call-interactively command))))))
22954 (defun org-yank-folding-would-swallow-text (beg end)
22955 "Would hide-subtree at BEG swallow any text after END?"
22956 (let (level)
22957 (org-with-limited-levels
22958 (save-excursion
22959 (goto-char beg)
22960 (when (or (looking-at org-outline-regexp)
22961 (re-search-forward org-outline-regexp-bol end t))
22962 (setq level (org-outline-level)))
22963 (goto-char end)
22964 (skip-chars-forward " \t\r\n\v\f")
22965 (if (or (eobp)
22966 (and (bolp) (looking-at org-outline-regexp)
22967 (<= (org-outline-level) level)))
22968 nil ; Nothing would be swallowed
22969 t))))) ; something would swallow
22971 (define-key org-mode-map "\C-y" 'org-yank)
22973 (defun org-truely-invisible-p ()
22974 "Check if point is at a character currently not visible.
22975 This version does not only check the character property, but also
22976 `visible-mode'."
22977 ;; Early versions of noutline don't have `outline-invisible-p'.
22978 (if (org-bound-and-true-p visible-mode)
22980 (outline-invisible-p)))
22982 (defun org-invisible-p2 ()
22983 "Check if point is at a character currently not visible."
22984 (save-excursion
22985 (if (and (eolp) (not (bobp))) (backward-char 1))
22986 ;; Early versions of noutline don't have `outline-invisible-p'.
22987 (outline-invisible-p)))
22989 (defun org-back-to-heading (&optional invisible-ok)
22990 "Call `outline-back-to-heading', but provide a better error message."
22991 (condition-case nil
22992 (outline-back-to-heading invisible-ok)
22993 (error (error "Before first headline at position %d in buffer %s"
22994 (point) (current-buffer)))))
22996 (defun org-before-first-heading-p ()
22997 "Before first heading?"
22998 (save-excursion
22999 (end-of-line)
23000 (null (re-search-backward org-outline-regexp-bol nil t))))
23002 (defun org-at-heading-p (&optional ignored)
23003 (outline-on-heading-p t))
23004 ;; Compatibility alias with Org versions < 7.8.03
23005 (defalias 'org-on-heading-p 'org-at-heading-p)
23007 (defun org-at-comment-p nil
23008 "Is cursor in a line starting with a # character?"
23009 (save-excursion
23010 (beginning-of-line)
23011 (looking-at "^#")))
23013 (defun org-at-drawer-p nil
23014 "Is cursor at a drawer keyword?"
23015 (save-excursion
23016 (move-beginning-of-line 1)
23017 (looking-at org-drawer-regexp)))
23019 (defun org-at-block-p nil
23020 "Is cursor at a block keyword?"
23021 (save-excursion
23022 (move-beginning-of-line 1)
23023 (looking-at org-block-regexp)))
23025 (defun org-point-at-end-of-empty-headline ()
23026 "If point is at the end of an empty headline, return t, else nil.
23027 If the heading only contains a TODO keyword, it is still still considered
23028 empty."
23029 (and (looking-at "[ \t]*$")
23030 (when org-todo-line-regexp
23031 (save-excursion
23032 (beginning-of-line 1)
23033 (let ((case-fold-search nil))
23034 (looking-at org-todo-line-regexp)
23035 (string= (match-string 3) ""))))))
23037 (defun org-at-heading-or-item-p ()
23038 (or (org-at-heading-p) (org-at-item-p)))
23040 (defun org-at-target-p ()
23041 (or (org-in-regexp org-radio-target-regexp)
23042 (org-in-regexp org-target-regexp)))
23043 ;; Compatibility alias with Org versions < 7.8.03
23044 (defalias 'org-on-target-p 'org-at-target-p)
23046 (defun org-up-heading-all (arg)
23047 "Move to the heading line of which the present line is a subheading.
23048 This function considers both visible and invisible heading lines.
23049 With argument, move up ARG levels."
23050 (if (fboundp 'outline-up-heading-all)
23051 (outline-up-heading-all arg) ; emacs 21 version of outline.el
23052 (outline-up-heading arg t))) ; emacs 22 version of outline.el
23054 (defun org-up-heading-safe ()
23055 "Move to the heading line of which the present line is a subheading.
23056 This version will not throw an error. It will return the level of the
23057 headline found, or nil if no higher level is found.
23059 Also, this function will be a lot faster than `outline-up-heading',
23060 because it relies on stars being the outline starters. This can really
23061 make a significant difference in outlines with very many siblings."
23062 (let (start-level re)
23063 (org-back-to-heading t)
23064 (setq start-level (funcall outline-level))
23065 (if (equal start-level 1)
23067 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
23068 (if (re-search-backward re nil t)
23069 (funcall outline-level)))))
23071 (defun org-first-sibling-p ()
23072 "Is this heading the first child of its parents?"
23073 (interactive)
23074 (let ((re org-outline-regexp-bol)
23075 level l)
23076 (unless (org-at-heading-p t)
23077 (user-error "Not at a heading"))
23078 (setq level (funcall outline-level))
23079 (save-excursion
23080 (if (not (re-search-backward re nil t))
23082 (setq l (funcall outline-level))
23083 (< l level)))))
23085 (defun org-goto-sibling (&optional previous)
23086 "Goto the next sibling, even if it is invisible.
23087 When PREVIOUS is set, go to the previous sibling instead. Returns t
23088 when a sibling was found. When none is found, return nil and don't
23089 move point."
23090 (let ((fun (if previous 're-search-backward 're-search-forward))
23091 (pos (point))
23092 (re org-outline-regexp-bol)
23093 level l)
23094 (when (condition-case nil (org-back-to-heading t) (error nil))
23095 (setq level (funcall outline-level))
23096 (catch 'exit
23097 (or previous (forward-char 1))
23098 (while (funcall fun re nil t)
23099 (setq l (funcall outline-level))
23100 (when (< l level) (goto-char pos) (throw 'exit nil))
23101 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23102 (goto-char pos)
23103 nil))))
23105 (defun org-show-siblings ()
23106 "Show all siblings of the current headline."
23107 (save-excursion
23108 (while (org-goto-sibling) (org-flag-heading nil)))
23109 (save-excursion
23110 (while (org-goto-sibling 'previous)
23111 (org-flag-heading nil))))
23113 (defun org-goto-first-child ()
23114 "Goto the first child, even if it is invisible.
23115 Return t when a child was found. Otherwise don't move point and
23116 return nil."
23117 (let (level (pos (point)) (re org-outline-regexp-bol))
23118 (when (condition-case nil (org-back-to-heading t) (error nil))
23119 (setq level (outline-level))
23120 (forward-char 1)
23121 (if (and (re-search-forward re nil t) (> (outline-level) level))
23122 (progn (goto-char (match-beginning 0)) t)
23123 (goto-char pos) nil))))
23125 (defun org-show-hidden-entry ()
23126 "Show an entry where even the heading is hidden."
23127 (save-excursion
23128 (org-show-entry)))
23130 (defun org-flag-heading (flag &optional entry)
23131 "Flag the current heading. FLAG non-nil means make invisible.
23132 When ENTRY is non-nil, show the entire entry."
23133 (save-excursion
23134 (org-back-to-heading t)
23135 ;; Check if we should show the entire entry
23136 (if entry
23137 (progn
23138 (org-show-entry)
23139 (save-excursion
23140 (and (outline-next-heading)
23141 (org-flag-heading nil))))
23142 (outline-flag-region (max (point-min) (1- (point)))
23143 (save-excursion (outline-end-of-heading) (point))
23144 flag))))
23146 (defun org-get-next-sibling ()
23147 "Move to next heading of the same level, and return point.
23148 If there is no such heading, return nil.
23149 This is like outline-next-sibling, but invisible headings are ok."
23150 (let ((level (funcall outline-level)))
23151 (outline-next-heading)
23152 (while (and (not (eobp)) (> (funcall outline-level) level))
23153 (outline-next-heading))
23154 (if (or (eobp) (< (funcall outline-level) level))
23156 (point))))
23158 (defun org-get-last-sibling ()
23159 "Move to previous heading of the same level, and return point.
23160 If there is no such heading, return nil."
23161 (let ((opoint (point))
23162 (level (funcall outline-level)))
23163 (outline-previous-heading)
23164 (when (and (/= (point) opoint) (outline-on-heading-p t))
23165 (while (and (> (funcall outline-level) level)
23166 (not (bobp)))
23167 (outline-previous-heading))
23168 (if (< (funcall outline-level) level)
23170 (point)))))
23172 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23173 "Goto to the end of a subtree."
23174 ;; This contains an exact copy of the original function, but it uses
23175 ;; `org-back-to-heading', to make it work also in invisible
23176 ;; trees. And is uses an invisible-ok argument.
23177 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23178 ;; Furthermore, when used inside Org, finding the end of a large subtree
23179 ;; with many children and grandchildren etc, this can be much faster
23180 ;; than the outline version.
23181 (org-back-to-heading invisible-ok)
23182 (let ((first t)
23183 (level (funcall outline-level)))
23184 (if (and (derived-mode-p 'org-mode) (< level 1000))
23185 ;; A true heading (not a plain list item), in Org-mode
23186 ;; This means we can easily find the end by looking
23187 ;; only for the right number of stars. Using a regexp to do
23188 ;; this is so much faster than using a Lisp loop.
23189 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23190 (forward-char 1)
23191 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23192 ;; something else, do it the slow way
23193 (while (and (not (eobp))
23194 (or first (> (funcall outline-level) level)))
23195 (setq first nil)
23196 (outline-next-heading)))
23197 (unless to-heading
23198 (if (memq (preceding-char) '(?\n ?\^M))
23199 (progn
23200 ;; Go to end of line before heading
23201 (forward-char -1)
23202 (if (memq (preceding-char) '(?\n ?\^M))
23203 ;; leave blank line before heading
23204 (forward-char -1))))))
23205 (point))
23207 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
23208 "Use Org version in org-mode, for dramatic speed-up."
23209 (if (derived-mode-p 'org-mode)
23210 (progn
23211 (org-end-of-subtree nil t)
23212 (unless (eobp) (backward-char 1)))
23213 ad-do-it))
23215 (defun org-end-of-meta-data-and-drawers ()
23216 "Jump to the first text after meta data and drawers in the current entry.
23217 This will move over empty lines, lines with planning time stamps,
23218 clocking lines, and drawers."
23219 (org-back-to-heading t)
23220 (let ((end (save-excursion (outline-next-heading) (point)))
23221 (re (concat "\\(" org-drawer-regexp "\\)"
23222 "\\|" "[ \t]*" org-keyword-time-regexp)))
23223 (forward-line 1)
23224 (while (re-search-forward re end t)
23225 (if (not (match-end 1))
23226 ;; empty or planning line
23227 (forward-line 1)
23228 ;; a drawer, find the end
23229 (re-search-forward "^[ \t]*:END:" end 'move)
23230 (forward-line 1)))
23231 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23232 (point)))
23234 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23235 "Move forward to the ARG'th subheading at same level as this one.
23236 Stop at the first and last subheadings of a superior heading.
23237 Normally this only looks at visible headings, but when INVISIBLE-OK is
23238 non-nil it will also look at invisible ones."
23239 (interactive "p")
23240 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23241 (if (and arg (< arg 0))
23242 (goto-char (point-min))
23243 (outline-next-heading))
23244 (org-at-heading-p)
23245 (let ((level (- (match-end 0) (match-beginning 0) 1))
23246 (f (if (and arg (< arg 0))
23247 're-search-backward
23248 're-search-forward))
23249 (count (if arg (abs arg) 1))
23250 (result (point)))
23251 (while (and (prog1 (> count 0)
23252 (forward-char (if (and arg (< arg 0)) -1 1)))
23253 (funcall f org-outline-regexp-bol nil 'move))
23254 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23255 (cond ((< l level) (setq count 0))
23256 ((and (= l level)
23257 (or invisible-ok
23258 (progn
23259 (goto-char (line-beginning-position))
23260 (not (outline-invisible-p)))))
23261 (setq count (1- count))
23262 (when (eq l level)
23263 (setq result (point)))))))
23264 (goto-char result))
23265 (beginning-of-line 1)))
23267 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23268 "Move backward to the ARG'th subheading at same level as this one.
23269 Stop at the first and last subheadings of a superior heading."
23270 (interactive "p")
23271 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23273 (defun org-next-block (arg &optional backward block-regexp)
23274 "Jump to the next block.
23275 With a prefix argument ARG, jump forward ARG many source blocks.
23276 When BACKWARD is non-nil, jump to the previous block.
23277 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23278 (interactive "p")
23279 (let ((re (or block-regexp org-block-regexp))
23280 (re-search-fn (or (and backward 're-search-backward)
23281 're-search-forward)))
23282 (if (looking-at re) (forward-char 1))
23283 (condition-case nil
23284 (funcall re-search-fn re nil nil arg)
23285 (error (error "No %s code blocks" (if backward "previous" "further" ))))
23286 (goto-char (match-beginning 0)) (org-show-context)))
23288 (defun org-previous-block (arg &optional block-regexp)
23289 "Jump to the previous block.
23290 With a prefix argument ARG, jump backward ARG many source blocks.
23291 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23292 (interactive "p")
23293 (org-next-block arg t block-regexp))
23295 (defun org-forward-paragraph ()
23296 "Move forward to beginning of next paragraph or equivalent.
23298 The function moves point to the beginning of the next visible
23299 structural element, which can be a paragraph, a table, a list
23300 item, etc. It also provides some special moves for convenience:
23302 - On an affiliated keyword, jump to the beginning of the
23303 relative element.
23304 - On an item or a footnote definition, move to the second
23305 element inside, if any.
23306 - On a table or a property drawer, jump after it.
23307 - On a verse or source block, stop after blank lines."
23308 (interactive)
23309 (when (eobp) (user-error "Cannot move further down"))
23310 (let* ((deactivate-mark nil)
23311 (element (org-element-at-point))
23312 (type (org-element-type element))
23313 (post-affiliated (org-element-property :post-affiliated element))
23314 (contents-begin (org-element-property :contents-begin element))
23315 (contents-end (org-element-property :contents-end element))
23316 (end (let ((end (org-element-property :end element)) (parent element))
23317 (while (and (setq parent (org-element-property :parent parent))
23318 (= (org-element-property :contents-end parent) end))
23319 (setq end (org-element-property :end parent)))
23320 end)))
23321 (cond ((not element)
23322 (skip-chars-forward " \r\t\n")
23323 (or (eobp) (beginning-of-line)))
23324 ;; On affiliated keywords, move to element's beginning.
23325 ((and post-affiliated (< (point) post-affiliated))
23326 (goto-char post-affiliated))
23327 ;; At a table row, move to the end of the table. Similarly,
23328 ;; at a node property, move to the end of the property
23329 ;; drawer.
23330 ((memq type '(node-property table-row))
23331 (goto-char (org-element-property
23332 :end (org-element-property :parent element))))
23333 ((memq type '(property-drawer table)) (goto-char end))
23334 ;; Consider blank lines as separators in verse and source
23335 ;; blocks to ease editing.
23336 ((memq type '(src-block verse-block))
23337 (when (eq type 'src-block)
23338 (setq contents-end
23339 (save-excursion (goto-char end)
23340 (skip-chars-backward " \r\t\n")
23341 (line-beginning-position))))
23342 (beginning-of-line)
23343 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23344 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23345 (goto-char end)
23346 (skip-chars-forward " \r\t\n")
23347 (if (= (point) contents-end) (goto-char end)
23348 (beginning-of-line))))
23349 ;; With no contents, just skip element.
23350 ((not contents-begin) (goto-char end))
23351 ;; If contents are invisible, skip the element altogether.
23352 ((outline-invisible-p (line-end-position))
23353 (case type
23354 (headline
23355 (org-with-limited-levels (outline-next-visible-heading 1)))
23356 ;; At a plain list, make sure we move to the next item
23357 ;; instead of skipping the whole list.
23358 (plain-list (forward-char)
23359 (org-forward-paragraph))
23360 (otherwise (goto-char end))))
23361 ((>= (point) contents-end) (goto-char end))
23362 ((>= (point) contents-begin)
23363 ;; This can only happen on paragraphs and plain lists.
23364 (case type
23365 (paragraph (goto-char end))
23366 ;; At a plain list, try to move to second element in
23367 ;; first item, if possible.
23368 (plain-list (end-of-line)
23369 (org-forward-paragraph))))
23370 ;; When contents start on the middle of a line (e.g. in
23371 ;; items and footnote definitions), try to reach first
23372 ;; element starting after current line.
23373 ((> (line-end-position) contents-begin)
23374 (end-of-line)
23375 (org-forward-paragraph))
23376 (t (goto-char contents-begin)))))
23378 (defun org-backward-paragraph ()
23379 "Move backward to start of previous paragraph or equivalent.
23381 The function moves point to the beginning of the current
23382 structural element, which can be a paragraph, a table, a list
23383 item, etc., or to the beginning of the previous visible one if
23384 point is already there. It also provides some special moves for
23385 convenience:
23387 - On an affiliated keyword, jump to the first one.
23388 - On a table or a property drawer, move to its beginning.
23389 - On a verse or source block, stop before blank lines."
23390 (interactive)
23391 (when (bobp) (user-error "Cannot move further up"))
23392 (let* ((deactivate-mark nil)
23393 (element (org-element-at-point))
23394 (type (org-element-type element))
23395 (contents-begin (org-element-property :contents-begin element))
23396 (contents-end (org-element-property :contents-end element))
23397 (post-affiliated (org-element-property :post-affiliated element))
23398 (begin (org-element-property :begin element)))
23399 (cond
23400 ((not element) (goto-char (point-min)))
23401 ((= (point) begin)
23402 (backward-char)
23403 (org-backward-paragraph))
23404 ((and post-affiliated (<= (point) post-affiliated)) (goto-char begin))
23405 ((memq type '(node-property table-row))
23406 (goto-char (org-element-property
23407 :post-affiliated (org-element-property :parent element))))
23408 ((memq type '(property-drawer table)) (goto-char begin))
23409 ((memq type '(src-block verse-block))
23410 (when (eq type 'src-block)
23411 (setq contents-begin
23412 (save-excursion (goto-char begin) (forward-line) (point))))
23413 (if (= (point) contents-begin) (goto-char post-affiliated)
23414 ;; Inside a verse block, see blank lines as paragraph
23415 ;; separators.
23416 (let ((origin (point)))
23417 (skip-chars-backward " \r\t\n" contents-begin)
23418 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
23419 (skip-chars-forward " \r\t\n" origin)
23420 (if (= (point) origin) (goto-char contents-begin)
23421 (beginning-of-line))))))
23422 ((not contents-begin) (goto-char (or post-affiliated begin)))
23423 ((eq type 'paragraph)
23424 (goto-char contents-begin)
23425 ;; When at first paragraph in an item or a footnote definition,
23426 ;; move directly to beginning of line.
23427 (let ((parent-contents
23428 (org-element-property
23429 :contents-begin (org-element-property :parent element))))
23430 (when (and parent-contents (= parent-contents contents-begin))
23431 (beginning-of-line))))
23432 ;; At the end of a greater element, move to the beginning of the
23433 ;; last element within.
23434 ((>= (point) contents-end)
23435 (goto-char (1- contents-end))
23436 (org-backward-paragraph))
23437 (t (goto-char (or post-affiliated begin))))
23438 ;; Ensure we never leave point invisible.
23439 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
23441 (defun org-forward-element ()
23442 "Move forward by one element.
23443 Move to the next element at the same level, when possible."
23444 (interactive)
23445 (cond ((eobp) (user-error "Cannot move further down"))
23446 ((org-with-limited-levels (org-at-heading-p))
23447 (let ((origin (point)))
23448 (goto-char (org-end-of-subtree nil t))
23449 (unless (org-with-limited-levels (org-at-heading-p))
23450 (goto-char origin)
23451 (user-error "Cannot move further down"))))
23453 (let* ((elem (org-element-at-point))
23454 (end (org-element-property :end elem))
23455 (parent (org-element-property :parent elem)))
23456 (cond ((and parent (= (org-element-property :contents-end parent) end))
23457 (goto-char (org-element-property :end parent)))
23458 ((integer-or-marker-p end) (goto-char end))
23459 (t (message "No element at point")))))))
23461 (defun org-backward-element ()
23462 "Move backward by one element.
23463 Move to the previous element at the same level, when possible."
23464 (interactive)
23465 (cond ((bobp) (user-error "Cannot move further up"))
23466 ((org-with-limited-levels (org-at-heading-p))
23467 ;; At a headline, move to the previous one, if any, or stay
23468 ;; here.
23469 (let ((origin (point)))
23470 (org-with-limited-levels (org-backward-heading-same-level 1))
23471 ;; When current headline has no sibling above, move to its
23472 ;; parent.
23473 (when (= (point) origin)
23474 (or (org-with-limited-levels (org-up-heading-safe))
23475 (progn (goto-char origin)
23476 (user-error "Cannot move further up"))))))
23478 (let* ((trail (org-element-at-point 'keep-trail))
23479 (elem (car trail))
23480 (prev-elem (nth 1 trail))
23481 (beg (org-element-property :begin elem)))
23482 (cond
23483 ;; Move to beginning of current element if point isn't
23484 ;; there already.
23485 ((null beg) (message "No element at point"))
23486 ((/= (point) beg) (goto-char beg))
23487 (prev-elem (goto-char (org-element-property :begin prev-elem)))
23488 ((org-before-first-heading-p) (goto-char (point-min)))
23489 (t (org-back-to-heading)))))))
23491 (defun org-up-element ()
23492 "Move to upper element."
23493 (interactive)
23494 (if (org-with-limited-levels (org-at-heading-p))
23495 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23496 (let* ((elem (org-element-at-point))
23497 (parent (org-element-property :parent elem)))
23498 (if parent (goto-char (org-element-property :begin parent))
23499 (if (org-with-limited-levels (org-before-first-heading-p))
23500 (user-error "No surrounding element")
23501 (org-with-limited-levels (org-back-to-heading)))))))
23503 (defvar org-element-greater-elements)
23504 (defun org-down-element ()
23505 "Move to inner element."
23506 (interactive)
23507 (let ((element (org-element-at-point)))
23508 (cond
23509 ((memq (org-element-type element) '(plain-list table))
23510 (goto-char (org-element-property :contents-begin element))
23511 (forward-char))
23512 ((memq (org-element-type element) org-element-greater-elements)
23513 ;; If contents are hidden, first disclose them.
23514 (when (org-element-property :hiddenp element) (org-cycle))
23515 (goto-char (or (org-element-property :contents-begin element)
23516 (user-error "No content for this element"))))
23517 (t (user-error "No inner element")))))
23519 (defun org-drag-element-backward ()
23520 "Move backward element at point."
23521 (interactive)
23522 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
23523 (let* ((trail (org-element-at-point 'keep-trail))
23524 (elem (car trail))
23525 (prev-elem (nth 1 trail)))
23526 ;; Error out if no previous element or previous element is
23527 ;; a parent of the current one.
23528 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23529 (user-error "Cannot drag element backward")
23530 (let ((pos (point)))
23531 (org-element-swap-A-B prev-elem elem)
23532 (goto-char (+ (org-element-property :begin prev-elem)
23533 (- pos (org-element-property :begin elem)))))))))
23535 (defun org-drag-element-forward ()
23536 "Move forward element at point."
23537 (interactive)
23538 (let* ((pos (point))
23539 (elem (org-element-at-point)))
23540 (when (= (point-max) (org-element-property :end elem))
23541 (user-error "Cannot drag element forward"))
23542 (goto-char (org-element-property :end elem))
23543 (let ((next-elem (org-element-at-point)))
23544 (when (or (org-element-nested-p elem next-elem)
23545 (and (eq (org-element-type next-elem) 'headline)
23546 (not (eq (org-element-type elem) 'headline))))
23547 (goto-char pos)
23548 (user-error "Cannot drag element forward"))
23549 ;; Compute new position of point: it's shifted by NEXT-ELEM
23550 ;; body's length (without final blanks) and by the length of
23551 ;; blanks between ELEM and NEXT-ELEM.
23552 (let ((size-next (- (save-excursion
23553 (goto-char (org-element-property :end next-elem))
23554 (skip-chars-backward " \r\t\n")
23555 (forward-line)
23556 ;; Small correction if buffer doesn't end
23557 ;; with a newline character.
23558 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23559 (org-element-property :begin next-elem)))
23560 (size-blank (- (org-element-property :end elem)
23561 (save-excursion
23562 (goto-char (org-element-property :end elem))
23563 (skip-chars-backward " \r\t\n")
23564 (forward-line)
23565 (point)))))
23566 (org-element-swap-A-B elem next-elem)
23567 (goto-char (+ pos size-next size-blank))))))
23569 (defun org-drag-line-forward (arg)
23570 "Drag the line at point ARG lines forward."
23571 (interactive "p")
23572 (dotimes (n (abs arg))
23573 (let ((c (current-column)))
23574 (if (< 0 arg)
23575 (progn
23576 (beginning-of-line 2)
23577 (transpose-lines 1)
23578 (beginning-of-line 0))
23579 (transpose-lines 1)
23580 (beginning-of-line -1))
23581 (org-move-to-column c))))
23583 (defun org-drag-line-backward (arg)
23584 "Drag the line at point ARG lines backward."
23585 (interactive "p")
23586 (org-drag-line-forward (- arg)))
23588 (defun org-mark-element ()
23589 "Put point at beginning of this element, mark at end.
23591 Interactively, if this command is repeated or (in Transient Mark
23592 mode) if the mark is active, it marks the next element after the
23593 ones already marked."
23594 (interactive)
23595 (let (deactivate-mark)
23596 (if (and (org-called-interactively-p 'any)
23597 (or (and (eq last-command this-command) (mark t))
23598 (and transient-mark-mode mark-active)))
23599 (set-mark
23600 (save-excursion
23601 (goto-char (mark))
23602 (goto-char (org-element-property :end (org-element-at-point)))))
23603 (let ((element (org-element-at-point)))
23604 (end-of-line)
23605 (push-mark (org-element-property :end element) t t)
23606 (goto-char (org-element-property :begin element))))))
23608 (defun org-narrow-to-element ()
23609 "Narrow buffer to current element."
23610 (interactive)
23611 (let ((elem (org-element-at-point)))
23612 (cond
23613 ((eq (car elem) 'headline)
23614 (narrow-to-region
23615 (org-element-property :begin elem)
23616 (org-element-property :end elem)))
23617 ((memq (car elem) org-element-greater-elements)
23618 (narrow-to-region
23619 (org-element-property :contents-begin elem)
23620 (org-element-property :contents-end elem)))
23622 (narrow-to-region
23623 (org-element-property :begin elem)
23624 (org-element-property :end elem))))))
23626 (defun org-transpose-element ()
23627 "Transpose current and previous elements, keeping blank lines between.
23628 Point is moved after both elements."
23629 (interactive)
23630 (org-skip-whitespace)
23631 (let ((end (org-element-property :end (org-element-at-point))))
23632 (org-drag-element-backward)
23633 (goto-char end)))
23635 (defun org-unindent-buffer ()
23636 "Un-indent the visible part of the buffer.
23637 Relative indentation (between items, inside blocks, etc.) isn't
23638 modified."
23639 (interactive)
23640 (unless (eq major-mode 'org-mode)
23641 (user-error "Cannot un-indent a buffer not in Org mode"))
23642 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
23643 unindent-tree ; For byte-compiler.
23644 (unindent-tree
23645 (function
23646 (lambda (contents)
23647 (mapc
23648 (lambda (element)
23649 (if (memq (org-element-type element) '(headline section))
23650 (funcall unindent-tree (org-element-contents element))
23651 (save-excursion
23652 (save-restriction
23653 (narrow-to-region
23654 (org-element-property :begin element)
23655 (org-element-property :end element))
23656 (org-do-remove-indentation)))))
23657 (reverse contents))))))
23658 (funcall unindent-tree (org-element-contents parse-tree))))
23660 (defun org-show-subtree ()
23661 "Show everything after this heading at deeper levels."
23662 (interactive)
23663 (outline-flag-region
23664 (point)
23665 (save-excursion
23666 (org-end-of-subtree t t))
23667 nil))
23669 (defun org-show-entry ()
23670 "Show the body directly following this heading.
23671 Show the heading too, if it is currently invisible."
23672 (interactive)
23673 (save-excursion
23674 (condition-case nil
23675 (progn
23676 (org-back-to-heading t)
23677 (outline-flag-region
23678 (max (point-min) (1- (point)))
23679 (save-excursion
23680 (if (re-search-forward
23681 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23682 (match-beginning 1)
23683 (point-max)))
23684 nil)
23685 (org-cycle-hide-drawers 'children))
23686 (error nil))))
23688 (defun org-make-options-regexp (kwds &optional extra)
23689 "Make a regular expression for keyword lines."
23690 (concat
23691 "^#\\+\\("
23692 (mapconcat 'regexp-quote kwds "\\|")
23693 (if extra (concat "\\|" extra))
23694 "\\):[ \t]*\\(.*\\)"))
23696 ;; Make isearch reveal the necessary context
23697 (defun org-isearch-end ()
23698 "Reveal context after isearch exits."
23699 (when isearch-success ; only if search was successful
23700 (if (featurep 'xemacs)
23701 ;; Under XEmacs, the hook is run in the correct place,
23702 ;; we directly show the context.
23703 (org-show-context 'isearch)
23704 ;; In Emacs the hook runs *before* restoring the overlays.
23705 ;; So we have to use a one-time post-command-hook to do this.
23706 ;; (Emacs 22 has a special variable, see function `org-mode')
23707 (unless (and (boundp 'isearch-mode-end-hook-quit)
23708 isearch-mode-end-hook-quit)
23709 ;; Only when the isearch was not quitted.
23710 (org-add-hook 'post-command-hook 'org-isearch-post-command
23711 'append 'local)))
23712 (org-fix-ellipsis-at-bol)))
23714 (defun org-isearch-post-command ()
23715 "Remove self from hook, and show context."
23716 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23717 (org-show-context 'isearch))
23720 ;;;; Integration with and fixes for other packages
23722 ;;; Imenu support
23724 (defvar org-imenu-markers nil
23725 "All markers currently used by Imenu.")
23726 (make-variable-buffer-local 'org-imenu-markers)
23728 (defun org-imenu-new-marker (&optional pos)
23729 "Return a new marker for use by Imenu, and remember the marker."
23730 (let ((m (make-marker)))
23731 (move-marker m (or pos (point)))
23732 (push m org-imenu-markers)
23735 (defun org-imenu-get-tree ()
23736 "Produce the index for Imenu."
23737 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23738 (setq org-imenu-markers nil)
23739 (let* ((n org-imenu-depth)
23740 (re (concat "^" (org-get-limited-outline-regexp)))
23741 (subs (make-vector (1+ n) nil))
23742 (last-level 0)
23743 m level head0 head)
23744 (save-excursion
23745 (save-restriction
23746 (widen)
23747 (goto-char (point-max))
23748 (while (re-search-backward re nil t)
23749 (setq level (org-reduced-level (funcall outline-level)))
23750 (when (and (<= level n)
23751 (looking-at org-complex-heading-regexp)
23752 (setq head0 (org-match-string-no-properties 4)))
23753 (setq head (org-link-display-format head0)
23754 m (org-imenu-new-marker))
23755 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23756 (if (>= level last-level)
23757 (push (cons head m) (aref subs level))
23758 (push (cons head (aref subs (1+ level))) (aref subs level))
23759 (loop for i from (1+ level) to n do (aset subs i nil)))
23760 (setq last-level level)))))
23761 (aref subs 1)))
23763 (eval-after-load "imenu"
23764 '(progn
23765 (add-hook 'imenu-after-jump-hook
23766 (lambda ()
23767 (if (derived-mode-p 'org-mode)
23768 (org-show-context 'org-goto))))))
23770 (defun org-link-display-format (link)
23771 "Replace a link with its the description.
23772 If there is no description, use the link target."
23773 (save-match-data
23774 (if (string-match org-bracket-link-analytic-regexp link)
23775 (replace-match (if (match-end 5)
23776 (match-string 5 link)
23777 (concat (match-string 1 link)
23778 (match-string 3 link)))
23779 nil t link)
23780 link)))
23782 (defun org-toggle-link-display ()
23783 "Toggle the literal or descriptive display of links."
23784 (interactive)
23785 (if org-descriptive-links
23786 (progn (org-remove-from-invisibility-spec '(org-link))
23787 (org-restart-font-lock)
23788 (setq org-descriptive-links nil))
23789 (progn (add-to-invisibility-spec '(org-link))
23790 (org-restart-font-lock)
23791 (setq org-descriptive-links t))))
23793 ;; Speedbar support
23795 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23796 "Overlay marking the agenda restriction line in speedbar.")
23797 (overlay-put org-speedbar-restriction-lock-overlay
23798 'face 'org-agenda-restriction-lock)
23799 (overlay-put org-speedbar-restriction-lock-overlay
23800 'help-echo "Agendas are currently limited to this item.")
23801 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23803 (defun org-speedbar-set-agenda-restriction ()
23804 "Restrict future agenda commands to the location at point in speedbar.
23805 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23806 (interactive)
23807 (require 'org-agenda)
23808 (let (p m tp np dir txt)
23809 (cond
23810 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23811 'org-imenu t))
23812 (setq m (get-text-property p 'org-imenu-marker))
23813 (with-current-buffer (marker-buffer m)
23814 (goto-char m)
23815 (org-agenda-set-restriction-lock 'subtree)))
23816 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23817 'speedbar-function 'speedbar-find-file))
23818 (setq tp (previous-single-property-change
23819 (1+ p) 'speedbar-function)
23820 np (next-single-property-change
23821 tp 'speedbar-function)
23822 dir (speedbar-line-directory)
23823 txt (buffer-substring-no-properties (or tp (point-min))
23824 (or np (point-max))))
23825 (with-current-buffer (find-file-noselect
23826 (let ((default-directory dir))
23827 (expand-file-name txt)))
23828 (unless (derived-mode-p 'org-mode)
23829 (user-error "Cannot restrict to non-Org-mode file"))
23830 (org-agenda-set-restriction-lock 'file)))
23831 (t (user-error "Don't know how to restrict Org-mode's agenda")))
23832 (move-overlay org-speedbar-restriction-lock-overlay
23833 (point-at-bol) (point-at-eol))
23834 (setq current-prefix-arg nil)
23835 (org-agenda-maybe-redo)))
23837 (defvar speedbar-file-key-map)
23838 (declare-function speedbar-add-supported-extension "speedbar" (extension))
23839 (eval-after-load "speedbar"
23840 '(progn
23841 (speedbar-add-supported-extension ".org")
23842 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23843 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23844 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23845 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23846 (add-hook 'speedbar-visiting-tag-hook
23847 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23849 ;;; Fixes and Hacks for problems with other packages
23851 ;; Make flyspell not check words in links, to not mess up our keymap
23852 (defvar org-element-affiliated-keywords) ; From org-element.el
23853 (defvar org-element-block-name-alist) ; From org-element.el
23854 (defun org-mode-flyspell-verify ()
23855 "Don't let flyspell put overlays at active buttons, or on
23856 {todo,all-time,additional-option-like}-keywords."
23857 (require 'org-element) ; For `org-element-affiliated-keywords'
23858 (let ((pos (max (1- (point)) (point-min)))
23859 (word (thing-at-point 'word)))
23860 (and (not (get-text-property pos 'keymap))
23861 (not (get-text-property pos 'org-no-flyspell))
23862 (not (member word org-todo-keywords-1))
23863 (not (member word org-all-time-keywords))
23864 (not (member word org-options-keywords))
23865 (not (member word (mapcar 'car org-startup-options)))
23866 (not (member-ignore-case word org-element-affiliated-keywords))
23867 (not (member-ignore-case word (org-get-export-keywords)))
23868 (not (member-ignore-case
23869 word (mapcar 'car org-element-block-name-alist)))
23870 (not (member-ignore-case word '("BEGIN" "END" "ATTR")))
23871 (not (org-in-src-block-p)))))
23873 (defun org-remove-flyspell-overlays-in (beg end)
23874 "Remove flyspell overlays in region."
23875 (and (org-bound-and-true-p flyspell-mode)
23876 (fboundp 'flyspell-delete-region-overlays)
23877 (flyspell-delete-region-overlays beg end))
23878 (add-text-properties beg end '(org-no-flyspell t)))
23880 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23881 (eval-after-load "bookmark"
23882 '(if (boundp 'bookmark-after-jump-hook)
23883 ;; We can use the hook
23884 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23885 ;; Hook not available, use advice
23886 (defadvice bookmark-jump (after org-make-visible activate)
23887 "Make the position visible."
23888 (org-bookmark-jump-unhide))))
23890 ;; Make sure saveplace shows the location if it was hidden
23891 (eval-after-load "saveplace"
23892 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23893 "Make the position visible."
23894 (org-bookmark-jump-unhide)))
23896 ;; Make sure ecb shows the location if it was hidden
23897 (eval-after-load "ecb"
23898 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23899 "Make hierarchy visible when jumping into location from ECB tree buffer."
23900 (if (derived-mode-p 'org-mode)
23901 (org-show-context))))
23903 (defun org-bookmark-jump-unhide ()
23904 "Unhide the current position, to show the bookmark location."
23905 (and (derived-mode-p 'org-mode)
23906 (or (outline-invisible-p)
23907 (save-excursion (goto-char (max (point-min) (1- (point))))
23908 (outline-invisible-p)))
23909 (org-show-context 'bookmark-jump)))
23911 ;; Make session.el ignore our circular variable
23912 (defvar session-globals-exclude)
23913 (eval-after-load "session"
23914 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23916 ;;;; Finish up
23918 (provide 'org)
23920 (run-hooks 'org-load-hook)
23922 ;;; org.el ends here