org.el (org-refresh-properties): Bugfix
[org-mode/org-kjn.git] / lisp / org.el
blob70bf19e833a1755344688246a9087366ee65e474
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2014 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;;; Commentary:
28 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
29 ;; project planning with a fast and effective plain-text system.
31 ;; Org-mode develops organizational tasks around NOTES files that contain
32 ;; information about projects as plain text. Org-mode is implemented on
33 ;; top of outline-mode, which makes it possible to keep the content of
34 ;; large files well structured. Visibility cycling and structure editing
35 ;; help to work with the tree. Tables are easily created with a built-in
36 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
37 ;; and scheduling. It dynamically compiles entries into an agenda that
38 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
39 ;; Plain text URL-like links connect to websites, emails, Usenet
40 ;; messages, BBDB entries, and any files related to the projects. For
41 ;; printing and sharing of notes, an Org-mode file can be exported as a
42 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
43 ;; iCalendar file. It can also serve as a publishing tool for a set of
44 ;; linked webpages.
46 ;; Installation and Activation
47 ;; ---------------------------
48 ;; See the corresponding sections in the manual at
50 ;; http://orgmode.org/org.html#Installation
52 ;; Documentation
53 ;; -------------
54 ;; The documentation of Org-mode can be found in the TeXInfo file. The
55 ;; distribution also contains a PDF version of it. At the homepage of
56 ;; Org-mode, you can read the same text online as HTML. There is also an
57 ;; excellent reference card made by Philip Rooke. This card can be found
58 ;; in the etc/ directory of Emacs 22.
60 ;; A list of recent changes can be found at
61 ;; http://orgmode.org/Changes.html
63 ;;; Code:
65 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
66 (defvar org-table-formula-constants-local nil
67 "Local version of `org-table-formula-constants'.")
68 (make-variable-buffer-local 'org-table-formula-constants-local)
70 ;;;; Require other packages
72 (eval-when-compile
73 (require 'cl)
74 (require 'gnus-sum))
76 (require 'calendar)
77 (require 'find-func)
78 (require 'format-spec)
80 (load "org-loaddefs.el" t t t)
82 (require 'org-macs)
83 (require 'org-compat)
85 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
86 ;; some places -- e.g. see the macro `org-with-limited-levels'.
88 ;; In Org buffers, the value of `outline-regexp' is that of
89 ;; `org-outline-regexp'. The only function still directly relying on
90 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
91 ;; job when `orgstruct-mode' is active.
92 (defvar org-outline-regexp "\\*+ "
93 "Regexp to match Org headlines.")
95 (defvar org-outline-regexp-bol "^\\*+ "
96 "Regexp to match Org headlines.
97 This is similar to `org-outline-regexp' but additionally makes
98 sure that we are at the beginning of the line.")
100 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
101 "Matches a headline, putting stars and text into groups.
102 Stars are put in group 1 and the trimmed body in group 2.")
104 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
105 (unless (boundp 'calendar-view-holidays-initially-flag)
106 (org-defvaralias 'calendar-view-holidays-initially-flag
107 'view-calendar-holidays-initially))
108 (unless (boundp 'calendar-view-diary-initially-flag)
109 (org-defvaralias 'calendar-view-diary-initially-flag
110 'view-diary-entries-initially))
111 (unless (boundp 'diary-fancy-buffer)
112 (org-defvaralias 'diary-fancy-buffer 'fancy-diary-buffer))
114 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
115 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
116 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
117 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
118 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
119 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
120 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
121 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
123 (declare-function orgtbl-mode "org-table" (&optional arg))
124 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
125 (declare-function org-beamer-mode "ox-beamer" ())
126 (declare-function org-table-edit-field "org-table" (arg))
127 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
128 (declare-function org-table-set-constants "org-table" ())
129 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
130 (declare-function org-id-get-create "org-id" (&optional force))
131 (declare-function org-id-find-id-file "org-id" (id))
132 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
133 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
134 (declare-function org-agenda-redo "org-agenda" (&optional all))
135 (declare-function org-table-align "org-table" ())
136 (declare-function org-table-paste-rectangle "org-table" ())
137 (declare-function org-table-maybe-eval-formula "org-table" ())
138 (declare-function org-table-maybe-recalculate-line "org-table" ())
140 (declare-function org-element--parse-objects "org-element"
141 (beg end acc restriction))
142 (declare-function org-element-at-point "org-element" (&optional keep-trail))
143 (declare-function org-element-contents "org-element" (element))
144 (declare-function org-element-context "org-element" (&optional element))
145 (declare-function org-element-interpret-data "org-element"
146 (data &optional parent))
147 (declare-function org-element-map "org-element"
148 (data types fun &optional info first-match no-recursion))
149 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
150 (declare-function org-element-parse-buffer "org-element"
151 (&optional granularity visible-only))
152 (declare-function org-element-property "org-element" (property element))
153 (declare-function org-element-put-property "org-element"
154 (element property value))
155 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
156 (declare-function org-element--parse-objects "org-element"
157 (beg end acc restriction))
158 (declare-function org-element-parse-buffer "org-element"
159 (&optional granularity visible-only))
160 (declare-function org-element-restriction "org-element" (element))
161 (declare-function org-element-type "org-element" (element))
163 ;; load languages based on value of `org-babel-load-languages'
164 (defvar org-babel-load-languages)
166 ;;;###autoload
167 (defun org-babel-do-load-languages (sym value)
168 "Load the languages defined in `org-babel-load-languages'."
169 (set-default sym value)
170 (mapc (lambda (pair)
171 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
172 (if active
173 (progn
174 (require (intern (concat "ob-" lang))))
175 (progn
176 (funcall 'fmakunbound
177 (intern (concat "org-babel-execute:" lang)))
178 (funcall 'fmakunbound
179 (intern (concat "org-babel-expand-body:" lang)))))))
180 org-babel-load-languages))
182 ;;;###autoload
183 (defun org-babel-load-file (file &optional compile)
184 "Load Emacs Lisp source code blocks in the Org-mode FILE.
185 This function exports the source code using `org-babel-tangle'
186 and then loads the resulting file using `load-file'. With prefix
187 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
188 file to byte-code before it is loaded."
189 (interactive "fFile to load: \nP")
190 (require 'ob-core)
191 (let* ((age (lambda (file)
192 (float-time
193 (time-subtract (current-time)
194 (nth 5 (or (file-attributes (file-truename file))
195 (file-attributes file)))))))
196 (base-name (file-name-sans-extension file))
197 (exported-file (concat base-name ".el")))
198 ;; tangle if the org-mode file is newer than the elisp file
199 (unless (and (file-exists-p exported-file)
200 (> (funcall age file) (funcall age exported-file)))
201 (setq exported-file
202 (car (org-babel-tangle-file file exported-file "emacs-lisp"))))
203 (message "%s %s"
204 (if compile
205 (progn (byte-compile-file exported-file 'load)
206 "Compiled and loaded")
207 (progn (load-file exported-file) "Loaded"))
208 exported-file)))
210 (defcustom org-babel-load-languages '((emacs-lisp . t))
211 "Languages which can be evaluated in Org-mode buffers.
212 This list can be used to load support for any of the languages
213 below, note that each language will depend on a different set of
214 system executables and/or Emacs modes. When a language is
215 \"loaded\", then code blocks in that language can be evaluated
216 with `org-babel-execute-src-block' bound by default to C-c
217 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
218 be set to remove code block evaluation from the C-c C-c
219 keybinding. By default only Emacs Lisp (which has no
220 requirements) is loaded."
221 :group 'org-babel
222 :set 'org-babel-do-load-languages
223 :version "24.1"
224 :type '(alist :tag "Babel Languages"
225 :key-type
226 (choice
227 (const :tag "Awk" awk)
228 (const :tag "C" C)
229 (const :tag "R" R)
230 (const :tag "Asymptote" asymptote)
231 (const :tag "Calc" calc)
232 (const :tag "Clojure" clojure)
233 (const :tag "CSS" css)
234 (const :tag "Ditaa" ditaa)
235 (const :tag "Dot" dot)
236 (const :tag "Emacs Lisp" emacs-lisp)
237 (const :tag "Fortran" fortran)
238 (const :tag "Gnuplot" gnuplot)
239 (const :tag "Haskell" haskell)
240 (const :tag "IO" io)
241 (const :tag "Java" java)
242 (const :tag "Javascript" js)
243 (const :tag "LaTeX" latex)
244 (const :tag "Ledger" ledger)
245 (const :tag "Lilypond" lilypond)
246 (const :tag "Lisp" lisp)
247 (const :tag "Makefile" makefile)
248 (const :tag "Maxima" maxima)
249 (const :tag "Matlab" matlab)
250 (const :tag "Mscgen" mscgen)
251 (const :tag "Ocaml" ocaml)
252 (const :tag "Octave" octave)
253 (const :tag "Org" org)
254 (const :tag "Perl" perl)
255 (const :tag "Pico Lisp" picolisp)
256 (const :tag "PlantUML" plantuml)
257 (const :tag "Python" python)
258 (const :tag "Ruby" ruby)
259 (const :tag "Sass" sass)
260 (const :tag "Scala" scala)
261 (const :tag "Scheme" scheme)
262 (const :tag "Screen" screen)
263 (const :tag "Shell Script" sh)
264 (const :tag "Shen" shen)
265 (const :tag "Sql" sql)
266 (const :tag "Sqlite" sqlite))
267 :value-type (boolean :tag "Activate" :value t)))
269 ;;;; Customization variables
270 (defcustom org-clone-delete-id nil
271 "Remove ID property of clones of a subtree.
272 When non-nil, clones of a subtree don't inherit the ID property.
273 Otherwise they inherit the ID property with a new unique
274 identifier."
275 :type 'boolean
276 :version "24.1"
277 :group 'org-id)
279 ;;; Version
280 (org-check-version)
282 ;;;###autoload
283 (defun org-version (&optional here full message)
284 "Show the org-mode version in the echo area.
285 With prefix argument HERE, insert it at point.
286 When FULL is non-nil, use a verbose version string.
287 When MESSAGE is non-nil, display a message with the version."
288 (interactive "P")
289 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
290 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
291 (load-suffixes (list ".el"))
292 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
293 (org-trash (or
294 (and (fboundp 'org-release) (fboundp 'org-git-version))
295 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
296 (load-suffixes save-load-suffixes)
297 (org-version (org-release))
298 (git-version (org-git-version))
299 (version (format "Org-mode version %s (%s @ %s)"
300 org-version
301 git-version
302 (if org-install-dir
303 (if (string= org-dir org-install-dir)
304 org-install-dir
305 (concat "mixed installation! " org-install-dir " and " org-dir))
306 "org-loaddefs.el can not be found!")))
307 (version1 (if full version org-version)))
308 (if (org-called-interactively-p 'interactive)
309 (if here
310 (insert version)
311 (message version))
312 (if message (message version1))
313 version1)))
315 (defconst org-version (org-version))
317 ;;; Compatibility constants
319 ;;; The custom variables
321 (defgroup org nil
322 "Outline-based notes management and organizer."
323 :tag "Org"
324 :group 'outlines
325 :group 'calendar)
327 (defcustom org-mode-hook nil
328 "Mode hook for Org-mode, run after the mode was turned on."
329 :group 'org
330 :type 'hook)
332 (defcustom org-load-hook nil
333 "Hook that is run after org.el has been loaded."
334 :group 'org
335 :type 'hook)
337 (defcustom org-log-buffer-setup-hook nil
338 "Hook that is run after an Org log buffer is created."
339 :group 'org
340 :version "24.1"
341 :type 'hook)
343 (defvar org-modules) ; defined below
344 (defvar org-modules-loaded nil
345 "Have the modules been loaded already?")
347 (defun org-load-modules-maybe (&optional force)
348 "Load all extensions listed in `org-modules'."
349 (when (or force (not org-modules-loaded))
350 (mapc (lambda (ext)
351 (condition-case nil (require ext)
352 (error (message "Problems while trying to load feature `%s'" ext))))
353 org-modules)
354 (setq org-modules-loaded t)))
356 (defun org-set-modules (var value)
357 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
358 (set var value)
359 (when (featurep 'org)
360 (org-load-modules-maybe 'force)))
362 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
363 "Modules that should always be loaded together with org.el.
365 If a description starts with <C>, the file is not part of Emacs
366 and loading it will require that you have downloaded and properly
367 installed the Org mode distribution.
369 You can also use this system to load external packages (i.e. neither Org
370 core modules, nor modules from the CONTRIB directory). Just add symbols
371 to the end of the list. If the package is called org-xyz.el, then you need
372 to add the symbol `xyz', and the package must have a call to:
374 \(provide 'org-xyz)
376 For export specific modules, see also `org-export-backends'."
377 :group 'org
378 :set 'org-set-modules
379 :version "24.4"
380 :package-version '(Org . "8.0")
381 :type
382 '(set :greedy t
383 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
384 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
385 (const :tag " crypt: Encryption of subtrees" org-crypt)
386 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
387 (const :tag " docview: Links to doc-view buffers" org-docview)
388 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
389 (const :tag " habit: Track your consistency with habits" org-habit)
390 (const :tag " id: Global IDs for identifying entries" org-id)
391 (const :tag " info: Links to Info nodes" org-info)
392 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
393 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
394 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
395 (const :tag " mouse: Additional mouse support" org-mouse)
396 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
397 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
398 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
400 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
401 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
402 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
403 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
404 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
405 (const :tag "C collector: Collect properties into tables" org-collector)
406 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
407 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
408 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
409 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
410 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
411 (const :tag "C eval: Include command output as text" org-eval)
412 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
413 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
414 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
415 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
416 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
417 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
418 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
419 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
420 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
421 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
422 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
423 (const :tag "C mew: Links to Mew folders/messages" org-mew)
424 (const :tag "C mtags: Support for muse-like tags" org-mtags)
425 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
426 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
427 (const :tag "C registry: A registry for Org-mode links" org-registry)
428 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
429 (const :tag "C secretary: Team management with org-mode" org-secretary)
430 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
431 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
432 (const :tag "C track: Keep up with Org-mode development" org-track)
433 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
434 (const :tag "C vm: Links to VM folders/messages" org-vm)
435 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
436 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
437 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
439 (defvar org-export--registered-backends) ; From ox.el.
440 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
441 (declare-function org-export-backend-name "ox" (backend))
442 (defcustom org-export-backends '(ascii html icalendar latex)
443 "List of export back-ends that should be always available.
445 If a description starts with <C>, the file is not part of Emacs
446 and loading it will require that you have downloaded and properly
447 installed the Org mode distribution.
449 Unlike to `org-modules', libraries in this list will not be
450 loaded along with Org, but only once the export framework is
451 needed.
453 This variable needs to be set before org.el is loaded. If you
454 need to make a change while Emacs is running, use the customize
455 interface or run the following code, where VAL stands for the new
456 value of the variable, after updating it:
458 \(progn
459 \(setq org-export--registered-backends
460 \(org-remove-if-not
461 \(lambda (backend)
462 \(let ((name (org-export-backend-name backend)))
463 \(or (memq name val)
464 \(catch 'parentp
465 \(dolist (b val)
466 \(and (org-export-derived-backend-p b name)
467 \(throw 'parentp t)))))))
468 org-export--registered-backends))
469 \(let ((new-list (mapcar 'org-export-backend-name
470 org-export--registered-backends)))
471 \(dolist (backend val)
472 \(cond
473 \((not (load (format \"ox-%s\" backend) t t))
474 \(message \"Problems while trying to load export back-end `%s'\"
475 backend))
476 \((not (memq backend new-list)) (push backend new-list))))
477 \(set-default 'org-export-backends new-list)))
479 Adding a back-end to this list will also pull the back-end it
480 depends on, if any."
481 :group 'org
482 :group 'org-export
483 :version "24.4"
484 :package-version '(Org . "8.0")
485 :initialize 'custom-initialize-set
486 :set (lambda (var val)
487 (if (not (featurep 'ox)) (set-default var val)
488 ;; Any back-end not required anymore (not present in VAL and not
489 ;; a parent of any back-end in the new value) is removed from the
490 ;; list of registered back-ends.
491 (setq org-export--registered-backends
492 (org-remove-if-not
493 (lambda (backend)
494 (let ((name (org-export-backend-name backend)))
495 (or (memq name val)
496 (catch 'parentp
497 (dolist (b val)
498 (and (org-export-derived-backend-p b name)
499 (throw 'parentp t)))))))
500 org-export--registered-backends))
501 ;; Now build NEW-LIST of both new back-ends and required
502 ;; parents.
503 (let ((new-list (mapcar 'org-export-backend-name
504 org-export--registered-backends)))
505 (dolist (backend val)
506 (cond
507 ((not (load (format "ox-%s" backend) t t))
508 (message "Problems while trying to load export back-end `%s'"
509 backend))
510 ((not (memq backend new-list)) (push backend new-list))))
511 ;; Set VAR to that list with fixed dependencies.
512 (set-default var new-list))))
513 :type '(set :greedy t
514 (const :tag " ascii Export buffer to ASCII format" ascii)
515 (const :tag " beamer Export buffer to Beamer presentation" beamer)
516 (const :tag " html Export buffer to HTML format" html)
517 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
518 (const :tag " latex Export buffer to LaTeX format" latex)
519 (const :tag " man Export buffer to MAN format" man)
520 (const :tag " md Export buffer to Markdown format" md)
521 (const :tag " odt Export buffer to ODT format" odt)
522 (const :tag " org Export buffer to Org format" org)
523 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
524 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
525 (const :tag "C deck Export buffer to deck.js presentations" deck)
526 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
527 (const :tag "C groff Export buffer to Groff format" groff)
528 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
529 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
530 (const :tag "C s5 Export buffer to s5 presentations" s5)
531 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
533 (eval-after-load 'ox
534 '(mapc
535 (lambda (backend)
536 (condition-case nil (require (intern (format "ox-%s" backend)))
537 (error (message "Problems while trying to load export back-end `%s'"
538 backend))))
539 org-export-backends))
541 (defcustom org-support-shift-select nil
542 "Non-nil means make shift-cursor commands select text when possible.
544 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
545 start selecting a region, or enlarge regions started in this way.
546 In Org-mode, in special contexts, these same keys are used for
547 other purposes, important enough to compete with shift selection.
548 Org tries to balance these needs by supporting `shift-select-mode'
549 outside these special contexts, under control of this variable.
551 The default of this variable is nil, to avoid confusing behavior. Shifted
552 cursor keys will then execute Org commands in the following contexts:
553 - on a headline, changing TODO state (left/right) and priority (up/down)
554 - on a time stamp, changing the time
555 - in a plain list item, changing the bullet type
556 - in a property definition line, switching between allowed values
557 - in the BEGIN line of a clock table (changing the time block).
558 Outside these contexts, the commands will throw an error.
560 When this variable is t and the cursor is not in a special
561 context, Org-mode will support shift-selection for making and
562 enlarging regions. To make this more effective, the bullet
563 cycling will no longer happen anywhere in an item line, but only
564 if the cursor is exactly on the bullet.
566 If you set this variable to the symbol `always', then the keys
567 will not be special in headlines, property lines, and item lines,
568 to make shift selection work there as well. If this is what you
569 want, you can use the following alternative commands: `C-c C-t'
570 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
571 can be used to switch TODO sets, `C-c -' to cycle item bullet
572 types, and properties can be edited by hand or in column view.
574 However, when the cursor is on a timestamp, shift-cursor commands
575 will still edit the time stamp - this is just too good to give up.
577 XEmacs user should have this variable set to nil, because
578 `shift-select-mode' is in Emacs 23 or later only."
579 :group 'org
580 :type '(choice
581 (const :tag "Never" nil)
582 (const :tag "When outside special context" t)
583 (const :tag "Everywhere except timestamps" always)))
585 (defcustom org-loop-over-headlines-in-active-region nil
586 "Shall some commands act upon headlines in the active region?
588 When set to `t', some commands will be performed in all headlines
589 within the active region.
591 When set to `start-level', some commands will be performed in all
592 headlines within the active region, provided that these headlines
593 are of the same level than the first one.
595 When set to a string, those commands will be performed on the
596 matching headlines within the active region. Such string must be
597 a tags/property/todo match as it is used in the agenda tags view.
599 The list of commands is: `org-schedule', `org-deadline',
600 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
601 `org-archive-to-archive-sibling'. The archiving commands skip
602 already archived entries."
603 :type '(choice (const :tag "Don't loop" nil)
604 (const :tag "All headlines in active region" t)
605 (const :tag "In active region, headlines at the same level than the first one" start-level)
606 (string :tag "Tags/Property/Todo matcher"))
607 :version "24.1"
608 :group 'org-todo
609 :group 'org-archive)
611 (defgroup org-startup nil
612 "Options concerning startup of Org-mode."
613 :tag "Org Startup"
614 :group 'org)
616 (defcustom org-startup-folded t
617 "Non-nil means entering Org-mode will switch to OVERVIEW.
618 This can also be configured on a per-file basis by adding one of
619 the following lines anywhere in the buffer:
621 #+STARTUP: fold (or `overview', this is equivalent)
622 #+STARTUP: nofold (or `showall', this is equivalent)
623 #+STARTUP: content
624 #+STARTUP: showeverything
626 By default, this option is ignored when Org opens agenda files
627 for the first time. If you want the agenda to honor the startup
628 option, set `org-agenda-inhibit-startup' to nil."
629 :group 'org-startup
630 :type '(choice
631 (const :tag "nofold: show all" nil)
632 (const :tag "fold: overview" t)
633 (const :tag "content: all headlines" content)
634 (const :tag "show everything, even drawers" showeverything)))
636 (defcustom org-startup-truncated t
637 "Non-nil means entering Org-mode will set `truncate-lines'.
638 This is useful since some lines containing links can be very long and
639 uninteresting. Also tables look terrible when wrapped."
640 :group 'org-startup
641 :type 'boolean)
643 (defcustom org-startup-indented nil
644 "Non-nil means turn on `org-indent-mode' on startup.
645 This can also be configured on a per-file basis by adding one of
646 the following lines anywhere in the buffer:
648 #+STARTUP: indent
649 #+STARTUP: noindent"
650 :group 'org-structure
651 :type '(choice
652 (const :tag "Not" nil)
653 (const :tag "Globally (slow on startup in large files)" t)))
655 (defcustom org-use-sub-superscripts t
656 "Non-nil means interpret \"_\" and \"^\" for display.
658 If you want to control how Org exports those characters, see
659 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
660 used to be an alias for `org-export-with-sub-superscripts' in
661 Org <8.0, it is not anymore.
663 When this option is turned on, you can use TeX-like syntax for
664 sub- and superscripts within the buffer. Several characters after
665 \"_\" or \"^\" will be considered as a single item - so grouping
666 with {} is normally not needed. For example, the following things
667 will be parsed as single sub- or superscripts:
669 10^24 or 10^tau several digits will be considered 1 item.
670 10^-12 or 10^-tau a leading sign with digits or a word
671 x^2-y^3 will be read as x^2 - y^3, because items are
672 terminated by almost any nonword/nondigit char.
673 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
675 Still, ambiguity is possible. So when in doubt, use {} to enclose
676 the sub/superscript. If you set this variable to the symbol `{}',
677 the braces are *required* in order to trigger interpretations as
678 sub/superscript. This can be helpful in documents that need \"_\"
679 frequently in plain text."
680 :group 'org-startup
681 :version "24.4"
682 :package-version '(Org . "8.0")
683 :type '(choice
684 (const :tag "Always interpret" t)
685 (const :tag "Only with braces" {})
686 (const :tag "Never interpret" nil)))
688 (defcustom org-startup-with-beamer-mode nil
689 "Non-nil means turn on `org-beamer-mode' on startup.
690 This can also be configured on a per-file basis by adding one of
691 the following lines anywhere in the buffer:
693 #+STARTUP: beamer"
694 :group 'org-startup
695 :version "24.1"
696 :type 'boolean)
698 (defcustom org-startup-align-all-tables nil
699 "Non-nil means align all tables when visiting a file.
700 This is useful when the column width in tables is forced with <N> cookies
701 in table fields. Such tables will look correct only after the first re-align.
702 This can also be configured on a per-file basis by adding one of
703 the following lines anywhere in the buffer:
704 #+STARTUP: align
705 #+STARTUP: noalign"
706 :group 'org-startup
707 :type 'boolean)
709 (defcustom org-startup-with-inline-images nil
710 "Non-nil means show inline images when loading a new Org file.
711 This can also be configured on a per-file basis by adding one of
712 the following lines anywhere in the buffer:
713 #+STARTUP: inlineimages
714 #+STARTUP: noinlineimages"
715 :group 'org-startup
716 :version "24.1"
717 :type 'boolean)
719 (defcustom org-startup-with-latex-preview nil
720 "Non-nil means preview LaTeX fragments when loading a new Org file.
722 This can also be configured on a per-file basis by adding one of
723 the following lines anywhere in the buffer:
724 #+STARTUP: latexpreview
725 #+STARTUP: nolatexpreview"
726 :group 'org-startup
727 :version "24.4"
728 :package-version '(Org . "8.0")
729 :type 'boolean)
731 (defcustom org-insert-mode-line-in-empty-file nil
732 "Non-nil means insert the first line setting Org-mode in empty files.
733 When the function `org-mode' is called interactively in an empty file, this
734 normally means that the file name does not automatically trigger Org-mode.
735 To ensure that the file will always be in Org-mode in the future, a
736 line enforcing Org-mode will be inserted into the buffer, if this option
737 has been set."
738 :group 'org-startup
739 :type 'boolean)
741 (defcustom org-replace-disputed-keys nil
742 "Non-nil means use alternative key bindings for some keys.
743 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
744 These keys are also used by other packages like shift-selection-mode'
745 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
746 If you want to use Org-mode together with one of these other modes,
747 or more generally if you would like to move some Org-mode commands to
748 other keys, set this variable and configure the keys with the variable
749 `org-disputed-keys'.
751 This option is only relevant at load-time of Org-mode, and must be set
752 *before* org.el is loaded. Changing it requires a restart of Emacs to
753 become effective."
754 :group 'org-startup
755 :type 'boolean)
757 (defcustom org-use-extra-keys nil
758 "Non-nil means use extra key sequence definitions for certain commands.
759 This happens automatically if you run XEmacs or if `window-system'
760 is nil. This variable lets you do the same manually. You must
761 set it before loading org.
763 Example: on Carbon Emacs 22 running graphically, with an external
764 keyboard on a Powerbook, the default way of setting M-left might
765 not work for either Alt or ESC. Setting this variable will make
766 it work for ESC."
767 :group 'org-startup
768 :type 'boolean)
770 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
772 (defcustom org-disputed-keys
773 '(([(shift up)] . [(meta p)])
774 ([(shift down)] . [(meta n)])
775 ([(shift left)] . [(meta -)])
776 ([(shift right)] . [(meta +)])
777 ([(control shift right)] . [(meta shift +)])
778 ([(control shift left)] . [(meta shift -)]))
779 "Keys for which Org-mode and other modes compete.
780 This is an alist, cars are the default keys, second element specifies
781 the alternative to use when `org-replace-disputed-keys' is t.
783 Keys can be specified in any syntax supported by `define-key'.
784 The value of this option takes effect only at Org-mode's startup,
785 therefore you'll have to restart Emacs to apply it after changing."
786 :group 'org-startup
787 :type 'alist)
789 (defun org-key (key)
790 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
791 Or return the original if not disputed.
792 Also apply the translations defined in `org-xemacs-key-equivalents'."
793 (when org-replace-disputed-keys
794 (let* ((nkey (key-description key))
795 (x (org-find-if (lambda (x)
796 (equal (key-description (car x)) nkey))
797 org-disputed-keys)))
798 (setq key (if x (cdr x) key))))
799 (when (featurep 'xemacs)
800 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
801 key)
803 (defun org-find-if (predicate seq)
804 (catch 'exit
805 (while seq
806 (if (funcall predicate (car seq))
807 (throw 'exit (car seq))
808 (pop seq)))))
810 (defun org-defkey (keymap key def)
811 "Define a key, possibly translated, as returned by `org-key'."
812 (define-key keymap (org-key key) def))
814 (defcustom org-ellipsis nil
815 "The ellipsis to use in the Org-mode outline.
816 When nil, just use the standard three dots.
817 When a string, use that string instead.
818 When a face, use the standard 3 dots, but with the specified face.
819 The change affects only Org-mode (which will then use its own display table).
820 Changing this requires executing `M-x org-mode RET' in a buffer to become
821 effective."
822 :group 'org-startup
823 :type '(choice (const :tag "Default" nil)
824 (face :tag "Face" :value org-warning)
825 (string :tag "String" :value "...#")))
827 (defvar org-display-table nil
828 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
830 (defgroup org-keywords nil
831 "Keywords in Org-mode."
832 :tag "Org Keywords"
833 :group 'org)
835 (defcustom org-deadline-string "DEADLINE:"
836 "String to mark deadline entries.
837 A deadline is this string, followed by a time stamp. Should be a word,
838 terminated by a colon. You can insert a schedule keyword and
839 a timestamp with \\[org-deadline].
840 Changes become only effective after restarting Emacs."
841 :group 'org-keywords
842 :type 'string)
844 (defcustom org-scheduled-string "SCHEDULED:"
845 "String to mark scheduled TODO entries.
846 A schedule is this string, followed by a time stamp. Should be a word,
847 terminated by a colon. You can insert a schedule keyword and
848 a timestamp with \\[org-schedule].
849 Changes become only effective after restarting Emacs."
850 :group 'org-keywords
851 :type 'string)
853 (defcustom org-closed-string "CLOSED:"
854 "String used as the prefix for timestamps logging closing a TODO entry."
855 :group 'org-keywords
856 :type 'string)
858 (defcustom org-clock-string "CLOCK:"
859 "String used as prefix for timestamps clocking work hours on an item."
860 :group 'org-keywords
861 :type 'string)
863 (defcustom org-closed-keep-when-no-todo nil
864 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
865 :group 'org-todo
866 :group 'org-keywords
867 :version "24.4"
868 :package-version '(Org . "8.0")
869 :type 'boolean)
871 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
872 org-scheduled-string "\\|"
873 org-deadline-string "\\|"
874 org-closed-string "\\|"
875 org-clock-string "\\)")
876 "Matches a line with planning or clock info.")
878 (defcustom org-comment-string "COMMENT"
879 "Entries starting with this keyword will never be exported.
880 An entry can be toggled between COMMENT and normal with
881 \\[org-toggle-comment].
882 Changes become only effective after restarting Emacs."
883 :group 'org-keywords
884 :type 'string)
886 (defcustom org-quote-string "QUOTE"
887 "Entries starting with this keyword will be exported in fixed-width font.
888 Quoting applies only to the text in the entry following the headline, and does
889 not extend beyond the next headline, even if that is lower level.
890 An entry can be toggled between QUOTE and normal with
891 \\[org-toggle-fixed-width-section]."
892 :group 'org-keywords
893 :type 'string)
895 (defconst org-repeat-re
896 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
897 "Regular expression for specifying repeated events.
898 After a match, group 1 contains the repeat expression.")
900 (defgroup org-structure nil
901 "Options concerning the general structure of Org-mode files."
902 :tag "Org Structure"
903 :group 'org)
905 (defgroup org-reveal-location nil
906 "Options about how to make context of a location visible."
907 :tag "Org Reveal Location"
908 :group 'org-structure)
910 (defconst org-context-choice
911 '(choice
912 (const :tag "Always" t)
913 (const :tag "Never" nil)
914 (repeat :greedy t :tag "Individual contexts"
915 (cons
916 (choice :tag "Context"
917 (const agenda)
918 (const org-goto)
919 (const occur-tree)
920 (const tags-tree)
921 (const link-search)
922 (const mark-goto)
923 (const bookmark-jump)
924 (const isearch)
925 (const default))
926 (boolean))))
927 "Contexts for the reveal options.")
929 (defcustom org-show-hierarchy-above '((default . t))
930 "Non-nil means show full hierarchy when revealing a location.
931 Org-mode often shows locations in an org-mode file which might have
932 been invisible before. When this is set, the hierarchy of headings
933 above the exposed location is shown.
934 Turning this off for example for sparse trees makes them very compact.
935 Instead of t, this can also be an alist specifying this option for different
936 contexts. Valid contexts are
937 agenda when exposing an entry from the agenda
938 org-goto when using the command `org-goto' on key C-c C-j
939 occur-tree when using the command `org-occur' on key C-c /
940 tags-tree when constructing a sparse tree based on tags matches
941 link-search when exposing search matches associated with a link
942 mark-goto when exposing the jump goal of a mark
943 bookmark-jump when exposing a bookmark location
944 isearch when exiting from an incremental search
945 default default for all contexts not set explicitly"
946 :group 'org-reveal-location
947 :type org-context-choice)
949 (defcustom org-show-following-heading '((default . nil))
950 "Non-nil means show following heading when revealing a location.
951 Org-mode often shows locations in an org-mode file which might have
952 been invisible before. When this is set, the heading following the
953 match is shown.
954 Turning this off for example for sparse trees makes them very compact,
955 but makes it harder to edit the location of the match. In such a case,
956 use the command \\[org-reveal] to show more context.
957 Instead of t, this can also be an alist specifying this option for different
958 contexts. See `org-show-hierarchy-above' for valid contexts."
959 :group 'org-reveal-location
960 :type org-context-choice)
962 (defcustom org-show-siblings '((default . nil) (isearch t) (bookmark-jump t))
963 "Non-nil means show all sibling heading when revealing a location.
964 Org-mode often shows locations in an org-mode file which might have
965 been invisible before. When this is set, the sibling of the current entry
966 heading are all made visible. If `org-show-hierarchy-above' is t,
967 the same happens on each level of the hierarchy above the current entry.
969 By default this is on for the isearch context, off for all other contexts.
970 Turning this off for example for sparse trees makes them very compact,
971 but makes it harder to edit the location of the match. In such a case,
972 use the command \\[org-reveal] to show more context.
973 Instead of t, this can also be an alist specifying this option for different
974 contexts. See `org-show-hierarchy-above' for valid contexts."
975 :group 'org-reveal-location
976 :type org-context-choice
977 :version "24.4"
978 :package-version '(Org . "8.0"))
980 (defcustom org-show-entry-below '((default . nil))
981 "Non-nil means show the entry below a headline when revealing a location.
982 Org-mode often shows locations in an org-mode file which might have
983 been invisible before. When this is set, the text below the headline that is
984 exposed is also shown.
986 By default this is off for all contexts.
987 Instead of t, this can also be an alist specifying this option for different
988 contexts. See `org-show-hierarchy-above' for valid contexts."
989 :group 'org-reveal-location
990 :type org-context-choice)
992 (defcustom org-indirect-buffer-display 'other-window
993 "How should indirect tree buffers be displayed?
994 This applies to indirect buffers created with the commands
995 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
996 Valid values are:
997 current-window Display in the current window
998 other-window Just display in another window.
999 dedicated-frame Create one new frame, and re-use it each time.
1000 new-frame Make a new frame each time. Note that in this case
1001 previously-made indirect buffers are kept, and you need to
1002 kill these buffers yourself."
1003 :group 'org-structure
1004 :group 'org-agenda-windows
1005 :type '(choice
1006 (const :tag "In current window" current-window)
1007 (const :tag "In current frame, other window" other-window)
1008 (const :tag "Each time a new frame" new-frame)
1009 (const :tag "One dedicated frame" dedicated-frame)))
1011 (defcustom org-use-speed-commands nil
1012 "Non-nil means activate single letter commands at beginning of a headline.
1013 This may also be a function to test for appropriate locations where speed
1014 commands should be active."
1015 :group 'org-structure
1016 :type '(choice
1017 (const :tag "Never" nil)
1018 (const :tag "At beginning of headline stars" t)
1019 (function)))
1021 (defcustom org-speed-commands-user nil
1022 "Alist of additional speed commands.
1023 This list will be checked before `org-speed-commands-default'
1024 when the variable `org-use-speed-commands' is non-nil
1025 and when the cursor is at the beginning of a headline.
1026 The car if each entry is a string with a single letter, which must
1027 be assigned to `self-insert-command' in the global map.
1028 The cdr is either a command to be called interactively, a function
1029 to be called, or a form to be evaluated.
1030 An entry that is just a list with a single string will be interpreted
1031 as a descriptive headline that will be added when listing the speed
1032 commands in the Help buffer using the `?' speed command."
1033 :group 'org-structure
1034 :type '(repeat :value ("k" . ignore)
1035 (choice :value ("k" . ignore)
1036 (list :tag "Descriptive Headline" (string :tag "Headline"))
1037 (cons :tag "Letter and Command"
1038 (string :tag "Command letter")
1039 (choice
1040 (function)
1041 (sexp))))))
1043 (defcustom org-bookmark-names-plist
1044 '(:last-capture "org-capture-last-stored"
1045 :last-refile "org-refile-last-stored"
1046 :last-capture-marker "org-capture-last-stored-marker")
1047 "Names for bookmarks automatically set by some Org commands.
1048 This can provide strings as names for a number of bookmarks Org sets
1049 automatically. The following keys are currently implemented:
1050 :last-capture
1051 :last-capture-marker
1052 :last-refile
1053 When a key does not show up in the property list, the corresponding bookmark
1054 is not set."
1055 :group 'org-structure
1056 :type 'plist)
1058 (defgroup org-cycle nil
1059 "Options concerning visibility cycling in Org-mode."
1060 :tag "Org Cycle"
1061 :group 'org-structure)
1063 (defcustom org-cycle-skip-children-state-if-no-children t
1064 "Non-nil means skip CHILDREN state in entries that don't have any."
1065 :group 'org-cycle
1066 :type 'boolean)
1068 (defcustom org-cycle-max-level nil
1069 "Maximum level which should still be subject to visibility cycling.
1070 Levels higher than this will, for cycling, be treated as text, not a headline.
1071 When `org-odd-levels-only' is set, a value of N in this variable actually
1072 means 2N-1 stars as the limiting headline.
1073 When nil, cycle all levels.
1074 Note that the limiting level of cycling is also influenced by
1075 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1076 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1077 than its value."
1078 :group 'org-cycle
1079 :type '(choice
1080 (const :tag "No limit" nil)
1081 (integer :tag "Maximum level")))
1083 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
1084 "Names of drawers. Drawers are not opened by cycling on the headline above.
1085 Drawers only open with a TAB on the drawer line itself. A drawer looks like
1086 this:
1087 :DRAWERNAME:
1088 .....
1089 :END:
1090 The drawer \"PROPERTIES\" is special for capturing properties through
1091 the property API.
1093 Drawers can be defined on the per-file basis with a line like:
1095 #+DRAWERS: HIDDEN STATE PROPERTIES"
1096 :group 'org-structure
1097 :group 'org-cycle
1098 :type '(repeat (string :tag "Drawer Name")))
1100 (defcustom org-hide-block-startup nil
1101 "Non-nil means entering Org-mode will fold all blocks.
1102 This can also be set in on a per-file basis with
1104 #+STARTUP: hideblocks
1105 #+STARTUP: showblocks"
1106 :group 'org-startup
1107 :group 'org-cycle
1108 :type 'boolean)
1110 (defcustom org-cycle-global-at-bob nil
1111 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1112 This makes it possible to do global cycling without having to use S-TAB or
1113 \\[universal-argument] TAB. For this special case to work, the first line
1114 of the buffer must not be a headline -- it may be empty or some other text.
1115 When used in this way, `org-cycle-hook' is disabled temporarily to make
1116 sure the cursor stays at the beginning of the buffer. When this option is
1117 nil, don't do anything special at the beginning of the buffer."
1118 :group 'org-cycle
1119 :type 'boolean)
1121 (defcustom org-cycle-level-after-item/entry-creation t
1122 "Non-nil means cycle entry level or item indentation in new empty entries.
1124 When the cursor is at the end of an empty headline, i.e., with only stars
1125 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1126 and then all possible ancestor states, before returning to the original state.
1127 This makes data entry extremely fast: M-RET to create a new headline,
1128 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1130 When the cursor is at the end of an empty plain list item, one TAB will
1131 make it a subitem, two or more tabs will back up to make this an item
1132 higher up in the item hierarchy."
1133 :group 'org-cycle
1134 :type 'boolean)
1136 (defcustom org-cycle-emulate-tab t
1137 "Where should `org-cycle' emulate TAB.
1138 nil Never
1139 white Only in completely white lines
1140 whitestart Only at the beginning of lines, before the first non-white char
1141 t Everywhere except in headlines
1142 exc-hl-bol Everywhere except at the start of a headline
1143 If TAB is used in a place where it does not emulate TAB, the current subtree
1144 visibility is cycled."
1145 :group 'org-cycle
1146 :type '(choice (const :tag "Never" nil)
1147 (const :tag "Only in completely white lines" white)
1148 (const :tag "Before first char in a line" whitestart)
1149 (const :tag "Everywhere except in headlines" t)
1150 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1152 (defcustom org-cycle-separator-lines 2
1153 "Number of empty lines needed to keep an empty line between collapsed trees.
1154 If you leave an empty line between the end of a subtree and the following
1155 headline, this empty line is hidden when the subtree is folded.
1156 Org-mode will leave (exactly) one empty line visible if the number of
1157 empty lines is equal or larger to the number given in this variable.
1158 So the default 2 means at least 2 empty lines after the end of a subtree
1159 are needed to produce free space between a collapsed subtree and the
1160 following headline.
1162 If the number is negative, and the number of empty lines is at least -N,
1163 all empty lines are shown.
1165 Special case: when 0, never leave empty lines in collapsed view."
1166 :group 'org-cycle
1167 :type 'integer)
1168 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1170 (defcustom org-pre-cycle-hook nil
1171 "Hook that is run before visibility cycling is happening.
1172 The function(s) in this hook must accept a single argument which indicates
1173 the new state that will be set right after running this hook. The
1174 argument is a symbol. Before a global state change, it can have the values
1175 `overview', `content', or `all'. Before a local state change, it can have
1176 the values `folded', `children', or `subtree'."
1177 :group 'org-cycle
1178 :type 'hook)
1180 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1181 org-cycle-hide-drawers
1182 org-cycle-hide-inline-tasks
1183 org-cycle-show-empty-lines
1184 org-optimize-window-after-visibility-change)
1185 "Hook that is run after `org-cycle' has changed the buffer visibility.
1186 The function(s) in this hook must accept a single argument which indicates
1187 the new state that was set by the most recent `org-cycle' command. The
1188 argument is a symbol. After a global state change, it can have the values
1189 `overview', `contents', or `all'. After a local state change, it can have
1190 the values `folded', `children', or `subtree'."
1191 :group 'org-cycle
1192 :type 'hook)
1194 (defgroup org-edit-structure nil
1195 "Options concerning structure editing in Org-mode."
1196 :tag "Org Edit Structure"
1197 :group 'org-structure)
1199 (defcustom org-odd-levels-only nil
1200 "Non-nil means skip even levels and only use odd levels for the outline.
1201 This has the effect that two stars are being added/taken away in
1202 promotion/demotion commands. It also influences how levels are
1203 handled by the exporters.
1204 Changing it requires restart of `font-lock-mode' to become effective
1205 for fontification also in regions already fontified.
1206 You may also set this on a per-file basis by adding one of the following
1207 lines to the buffer:
1209 #+STARTUP: odd
1210 #+STARTUP: oddeven"
1211 :group 'org-edit-structure
1212 :group 'org-appearance
1213 :type 'boolean)
1215 (defcustom org-adapt-indentation t
1216 "Non-nil means adapt indentation to outline node level.
1218 When this variable is set, Org assumes that you write outlines by
1219 indenting text in each node to align with the headline (after the stars).
1220 The following issues are influenced by this variable:
1222 - When this is set and the *entire* text in an entry is indented, the
1223 indentation is increased by one space in a demotion command, and
1224 decreased by one in a promotion command. If any line in the entry
1225 body starts with text at column 0, indentation is not changed at all.
1227 - Property drawers and planning information is inserted indented when
1228 this variable s set. When nil, they will not be indented.
1230 - TAB indents a line relative to context. The lines below a headline
1231 will be indented when this variable is set.
1233 Note that this is all about true indentation, by adding and removing
1234 space characters. See also `org-indent.el' which does level-dependent
1235 indentation in a virtual way, i.e. at display time in Emacs."
1236 :group 'org-edit-structure
1237 :type 'boolean)
1239 (defcustom org-special-ctrl-a/e nil
1240 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1242 When t, `C-a' will bring back the cursor to the beginning of the
1243 headline text, i.e. after the stars and after a possible TODO
1244 keyword. In an item, this will be the position after bullet and
1245 check-box, if any. When the cursor is already at that position,
1246 another `C-a' will bring it to the beginning of the line.
1248 `C-e' will jump to the end of the headline, ignoring the presence
1249 of tags in the headline. A second `C-e' will then jump to the
1250 true end of the line, after any tags. This also means that, when
1251 this variable is non-nil, `C-e' also will never jump beyond the
1252 end of the heading of a folded section, i.e. not after the
1253 ellipses.
1255 When set to the symbol `reversed', the first `C-a' or `C-e' works
1256 normally, going to the true line boundary first. Only a directly
1257 following, identical keypress will bring the cursor to the
1258 special positions.
1260 This may also be a cons cell where the behavior for `C-a' and
1261 `C-e' is set separately."
1262 :group 'org-edit-structure
1263 :type '(choice
1264 (const :tag "off" nil)
1265 (const :tag "on: after stars/bullet and before tags first" t)
1266 (const :tag "reversed: true line boundary first" reversed)
1267 (cons :tag "Set C-a and C-e separately"
1268 (choice :tag "Special C-a"
1269 (const :tag "off" nil)
1270 (const :tag "on: after stars/bullet first" t)
1271 (const :tag "reversed: before stars/bullet first" reversed))
1272 (choice :tag "Special C-e"
1273 (const :tag "off" nil)
1274 (const :tag "on: before tags first" t)
1275 (const :tag "reversed: after tags first" reversed)))))
1276 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1278 (defcustom org-special-ctrl-k nil
1279 "Non-nil means `C-k' will behave specially in headlines.
1280 When nil, `C-k' will call the default `kill-line' command.
1281 When t, the following will happen while the cursor is in the headline:
1283 - When the cursor is at the beginning of a headline, kill the entire
1284 line and possible the folded subtree below the line.
1285 - When in the middle of the headline text, kill the headline up to the tags.
1286 - When after the headline text, kill the tags."
1287 :group 'org-edit-structure
1288 :type 'boolean)
1290 (defcustom org-ctrl-k-protect-subtree nil
1291 "Non-nil means, do not delete a hidden subtree with C-k.
1292 When set to the symbol `error', simply throw an error when C-k is
1293 used to kill (part-of) a headline that has hidden text behind it.
1294 Any other non-nil value will result in a query to the user, if it is
1295 OK to kill that hidden subtree. When nil, kill without remorse."
1296 :group 'org-edit-structure
1297 :version "24.1"
1298 :type '(choice
1299 (const :tag "Do not protect hidden subtrees" nil)
1300 (const :tag "Protect hidden subtrees with a security query" t)
1301 (const :tag "Never kill a hidden subtree with C-k" error)))
1303 (defcustom org-special-ctrl-o t
1304 "Non-nil means, make `C-o' insert a row in tables."
1305 :group 'org-edit-structure
1306 :type 'boolean)
1308 (defcustom org-catch-invisible-edits nil
1309 "Check if in invisible region before inserting or deleting a character.
1310 Valid values are:
1312 nil Do not check, so just do invisible edits.
1313 error Throw an error and do nothing.
1314 show Make point visible, and do the requested edit.
1315 show-and-error Make point visible, then throw an error and abort the edit.
1316 smart Make point visible, and do insertion/deletion if it is
1317 adjacent to visible text and the change feels predictable.
1318 Never delete a previously invisible character or add in the
1319 middle or right after an invisible region. Basically, this
1320 allows insertion and backward-delete right before ellipses.
1321 FIXME: maybe in this case we should not even show?"
1322 :group 'org-edit-structure
1323 :version "24.1"
1324 :type '(choice
1325 (const :tag "Do not check" nil)
1326 (const :tag "Throw error when trying to edit" error)
1327 (const :tag "Unhide, but do not do the edit" show-and-error)
1328 (const :tag "Show invisible part and do the edit" show)
1329 (const :tag "Be smart and do the right thing" smart)))
1331 (defcustom org-yank-folded-subtrees t
1332 "Non-nil means when yanking subtrees, fold them.
1333 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1334 it starts with a heading and all other headings in it are either children
1335 or siblings, then fold all the subtrees. However, do this only if no
1336 text after the yank would be swallowed into a folded tree by this action."
1337 :group 'org-edit-structure
1338 :type 'boolean)
1340 (defcustom org-yank-adjusted-subtrees nil
1341 "Non-nil means when yanking subtrees, adjust the level.
1342 With this setting, `org-paste-subtree' is used to insert the subtree, see
1343 this function for details."
1344 :group 'org-edit-structure
1345 :type 'boolean)
1347 (defcustom org-M-RET-may-split-line '((default . t))
1348 "Non-nil means M-RET will split the line at the cursor position.
1349 When nil, it will go to the end of the line before making a
1350 new line.
1351 You may also set this option in a different way for different
1352 contexts. Valid contexts are:
1354 headline when creating a new headline
1355 item when creating a new item
1356 table in a table field
1357 default the value to be used for all contexts not explicitly
1358 customized"
1359 :group 'org-structure
1360 :group 'org-table
1361 :type '(choice
1362 (const :tag "Always" t)
1363 (const :tag "Never" nil)
1364 (repeat :greedy t :tag "Individual contexts"
1365 (cons
1366 (choice :tag "Context"
1367 (const headline)
1368 (const item)
1369 (const table)
1370 (const default))
1371 (boolean)))))
1374 (defcustom org-insert-heading-respect-content nil
1375 "Non-nil means insert new headings after the current subtree.
1376 When nil, the new heading is created directly after the current line.
1377 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1378 this variable on for the duration of the command."
1379 :group 'org-structure
1380 :type 'boolean)
1382 (defcustom org-blank-before-new-entry '((heading . auto)
1383 (plain-list-item . auto))
1384 "Should `org-insert-heading' leave a blank line before new heading/item?
1385 The value is an alist, with `heading' and `plain-list-item' as CAR,
1386 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1387 which case Org will look at the surrounding headings/items and try to
1388 make an intelligent decision whether to insert a blank line or not.
1390 For plain lists, if `org-list-empty-line-terminates-plain-lists' is set,
1391 the setting here is ignored and no empty line is inserted to avoid breaking
1392 the list structure."
1393 :group 'org-edit-structure
1394 :type '(list
1395 (cons (const heading)
1396 (choice (const :tag "Never" nil)
1397 (const :tag "Always" t)
1398 (const :tag "Auto" auto)))
1399 (cons (const plain-list-item)
1400 (choice (const :tag "Never" nil)
1401 (const :tag "Always" t)
1402 (const :tag "Auto" auto)))))
1404 (defcustom org-insert-heading-hook nil
1405 "Hook being run after inserting a new heading."
1406 :group 'org-edit-structure
1407 :type 'hook)
1409 (defcustom org-enable-fixed-width-editor t
1410 "Non-nil means lines starting with \":\" are treated as fixed-width.
1411 This currently only means they are never auto-wrapped.
1412 When nil, such lines will be treated like ordinary lines.
1413 See also the QUOTE keyword."
1414 :group 'org-edit-structure
1415 :type 'boolean)
1417 (defcustom org-goto-auto-isearch t
1418 "Non-nil means typing characters in `org-goto' starts incremental search.
1419 When nil, you can use these keybindings to navigate the buffer:
1421 q Quit the org-goto interface
1422 n Go to the next visible heading
1423 p Go to the previous visible heading
1424 f Go one heading forward on same level
1425 b Go one heading backward on same level
1426 u Go one heading up"
1427 :group 'org-edit-structure
1428 :type 'boolean)
1430 (defgroup org-sparse-trees nil
1431 "Options concerning sparse trees in Org-mode."
1432 :tag "Org Sparse Trees"
1433 :group 'org-structure)
1435 (defcustom org-highlight-sparse-tree-matches t
1436 "Non-nil means highlight all matches that define a sparse tree.
1437 The highlights will automatically disappear the next time the buffer is
1438 changed by an edit command."
1439 :group 'org-sparse-trees
1440 :type 'boolean)
1442 (defcustom org-remove-highlights-with-change t
1443 "Non-nil means any change to the buffer will remove temporary highlights.
1444 Such highlights are created by `org-occur' and `org-clock-display'.
1445 When nil, `C-c C-c needs to be used to get rid of the highlights.
1446 The highlights created by `org-preview-latex-fragment' always need
1447 `C-c C-c' to be removed."
1448 :group 'org-sparse-trees
1449 :group 'org-time
1450 :type 'boolean)
1453 (defcustom org-occur-hook '(org-first-headline-recenter)
1454 "Hook that is run after `org-occur' has constructed a sparse tree.
1455 This can be used to recenter the window to show as much of the structure
1456 as possible."
1457 :group 'org-sparse-trees
1458 :type 'hook)
1460 (defgroup org-imenu-and-speedbar nil
1461 "Options concerning imenu and speedbar in Org-mode."
1462 :tag "Org Imenu and Speedbar"
1463 :group 'org-structure)
1465 (defcustom org-imenu-depth 2
1466 "The maximum level for Imenu access to Org-mode headlines.
1467 This also applied for speedbar access."
1468 :group 'org-imenu-and-speedbar
1469 :type 'integer)
1471 (defgroup org-table nil
1472 "Options concerning tables in Org-mode."
1473 :tag "Org Table"
1474 :group 'org)
1476 (defcustom org-enable-table-editor 'optimized
1477 "Non-nil means lines starting with \"|\" are handled by the table editor.
1478 When nil, such lines will be treated like ordinary lines.
1480 When equal to the symbol `optimized', the table editor will be optimized to
1481 do the following:
1482 - Automatic overwrite mode in front of whitespace in table fields.
1483 This makes the structure of the table stay in tact as long as the edited
1484 field does not exceed the column width.
1485 - Minimize the number of realigns. Normally, the table is aligned each time
1486 TAB or RET are pressed to move to another field. With optimization this
1487 happens only if changes to a field might have changed the column width.
1488 Optimization requires replacing the functions `self-insert-command',
1489 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1490 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1491 very good at guessing when a re-align will be necessary, but you can always
1492 force one with \\[org-ctrl-c-ctrl-c].
1494 If you would like to use the optimized version in Org-mode, but the
1495 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1497 This variable can be used to turn on and off the table editor during a session,
1498 but in order to toggle optimization, a restart is required.
1500 See also the variable `org-table-auto-blank-field'."
1501 :group 'org-table
1502 :type '(choice
1503 (const :tag "off" nil)
1504 (const :tag "on" t)
1505 (const :tag "on, optimized" optimized)))
1507 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1508 (version<= emacs-version "24.1"))
1509 "Non-nil means cluster self-insert commands for undo when possible.
1510 If this is set, then, like in the Emacs command loop, 20 consecutive
1511 characters will be undone together.
1512 This is configurable, because there is some impact on typing performance."
1513 :group 'org-table
1514 :type 'boolean)
1516 (defcustom org-table-tab-recognizes-table.el t
1517 "Non-nil means TAB will automatically notice a table.el table.
1518 When it sees such a table, it moves point into it and - if necessary -
1519 calls `table-recognize-table'."
1520 :group 'org-table-editing
1521 :type 'boolean)
1523 (defgroup org-link nil
1524 "Options concerning links in Org-mode."
1525 :tag "Org Link"
1526 :group 'org)
1528 (defvar org-link-abbrev-alist-local nil
1529 "Buffer-local version of `org-link-abbrev-alist', which see.
1530 The value of this is taken from the #+LINK lines.")
1531 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1533 (defcustom org-link-abbrev-alist nil
1534 "Alist of link abbreviations.
1535 The car of each element is a string, to be replaced at the start of a link.
1536 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1537 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1539 [[linkkey:tag][description]]
1541 The 'linkkey' must be a word word, starting with a letter, followed
1542 by letters, numbers, '-' or '_'.
1544 If REPLACE is a string, the tag will simply be appended to create the link.
1545 If the string contains \"%s\", the tag will be inserted there. If the string
1546 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1547 at that point (see the function `url-hexify-string'). If the string contains
1548 the specifier \"%(my-function)\", then the custom function `my-function' will
1549 be invoked: this function takes the tag as its only argument and must return
1550 a string.
1552 REPLACE may also be a function that will be called with the tag as the
1553 only argument to create the link, which should be returned as a string.
1555 See the manual for examples."
1556 :group 'org-link
1557 :type '(repeat
1558 (cons
1559 (string :tag "Protocol")
1560 (choice
1561 (string :tag "Format")
1562 (function)))))
1564 (defcustom org-descriptive-links t
1565 "Non-nil means Org will display descriptive links.
1566 E.g. [[http://orgmode.org][Org website]] will be displayed as
1567 \"Org Website\", hiding the link itself and just displaying its
1568 description. When set to `nil', Org will display the full links
1569 literally.
1571 You can interactively set the value of this variable by calling
1572 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1573 :group 'org-link
1574 :type 'boolean)
1576 (defcustom org-link-file-path-type 'adaptive
1577 "How the path name in file links should be stored.
1578 Valid values are:
1580 relative Relative to the current directory, i.e. the directory of the file
1581 into which the link is being inserted.
1582 absolute Absolute path, if possible with ~ for home directory.
1583 noabbrev Absolute path, no abbreviation of home directory.
1584 adaptive Use relative path for files in the current directory and sub-
1585 directories of it. For other files, use an absolute path."
1586 :group 'org-link
1587 :type '(choice
1588 (const relative)
1589 (const absolute)
1590 (const noabbrev)
1591 (const adaptive)))
1593 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1594 "Types of links that should be activated in Org-mode files.
1595 This is a list of symbols, each leading to the activation of a certain link
1596 type. In principle, it does not hurt to turn on most link types - there may
1597 be a small gain when turning off unused link types. The types are:
1599 bracket The recommended [[link][description]] or [[link]] links with hiding.
1600 angle Links in angular brackets that may contain whitespace like
1601 <bbdb:Carsten Dominik>.
1602 plain Plain links in normal text, no whitespace, like http://google.com.
1603 radio Text that is matched by a radio target, see manual for details.
1604 tag Tag settings in a headline (link to tag search).
1605 date Time stamps (link to calendar).
1606 footnote Footnote labels.
1608 Changing this variable requires a restart of Emacs to become effective."
1609 :group 'org-link
1610 :type '(set :greedy t
1611 (const :tag "Double bracket links" bracket)
1612 (const :tag "Angular bracket links" angle)
1613 (const :tag "Plain text links" plain)
1614 (const :tag "Radio target matches" radio)
1615 (const :tag "Tags" tag)
1616 (const :tag "Timestamps" date)
1617 (const :tag "Footnotes" footnote)))
1619 (defcustom org-make-link-description-function nil
1620 "Function to use for generating link descriptions from links.
1621 When nil, the link location will be used. This function must take
1622 two parameters: the first one is the link, the second one is the
1623 description generated by `org-insert-link'. The function should
1624 return the description to use."
1625 :group 'org-link
1626 :type '(choice (const nil) (function)))
1628 (defgroup org-link-store nil
1629 "Options concerning storing links in Org-mode."
1630 :tag "Org Store Link"
1631 :group 'org-link)
1633 (defcustom org-url-hexify-p t
1634 "When non-nil, hexify URL when creating a link."
1635 :type 'boolean
1636 :version "24.3"
1637 :group 'org-link-store)
1639 (defcustom org-email-link-description-format "Email %c: %.30s"
1640 "Format of the description part of a link to an email or usenet message.
1641 The following %-escapes will be replaced by corresponding information:
1643 %F full \"From\" field
1644 %f name, taken from \"From\" field, address if no name
1645 %T full \"To\" field
1646 %t first name in \"To\" field, address if no name
1647 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1648 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1649 %s subject
1650 %d date
1651 %m message-id.
1653 You may use normal field width specification between the % and the letter.
1654 This is for example useful to limit the length of the subject.
1656 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1657 :group 'org-link-store
1658 :type 'string)
1660 (defcustom org-from-is-user-regexp
1661 (let (r1 r2)
1662 (when (and user-mail-address (not (string= user-mail-address "")))
1663 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1664 (when (and user-full-name (not (string= user-full-name "")))
1665 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1666 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1667 "Regexp matched against the \"From:\" header of an email or usenet message.
1668 It should match if the message is from the user him/herself."
1669 :group 'org-link-store
1670 :type 'regexp)
1672 (defcustom org-context-in-file-links t
1673 "Non-nil means file links from `org-store-link' contain context.
1674 A search string will be added to the file name with :: as separator and
1675 used to find the context when the link is activated by the command
1676 `org-open-at-point'. When this option is t, the entire active region
1677 will be placed in the search string of the file link. If set to a
1678 positive integer, only the first n lines of context will be stored.
1680 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1681 negates this setting for the duration of the command."
1682 :group 'org-link-store
1683 :type '(choice boolean integer))
1685 (defcustom org-keep-stored-link-after-insertion nil
1686 "Non-nil means keep link in list for entire session.
1688 The command `org-store-link' adds a link pointing to the current
1689 location to an internal list. These links accumulate during a session.
1690 The command `org-insert-link' can be used to insert links into any
1691 Org-mode file (offering completion for all stored links). When this
1692 option is nil, every link which has been inserted once using \\[org-insert-link]
1693 will be removed from the list, to make completing the unused links
1694 more efficient."
1695 :group 'org-link-store
1696 :type 'boolean)
1698 (defgroup org-link-follow nil
1699 "Options concerning following links in Org-mode."
1700 :tag "Org Follow Link"
1701 :group 'org-link)
1703 (defcustom org-link-translation-function nil
1704 "Function to translate links with different syntax to Org syntax.
1705 This can be used to translate links created for example by the Planner
1706 or emacs-wiki packages to Org syntax.
1707 The function must accept two parameters, a TYPE containing the link
1708 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1709 which is everything after the link protocol. It should return a cons
1710 with possibly modified values of type and path.
1711 Org contains a function for this, so if you set this variable to
1712 `org-translate-link-from-planner', you should be able follow many
1713 links created by planner."
1714 :group 'org-link-follow
1715 :type '(choice (const nil) (function)))
1717 (defcustom org-follow-link-hook nil
1718 "Hook that is run after a link has been followed."
1719 :group 'org-link-follow
1720 :type 'hook)
1722 (defcustom org-tab-follows-link nil
1723 "Non-nil means on links TAB will follow the link.
1724 Needs to be set before org.el is loaded.
1725 This really should not be used, it does not make sense, and the
1726 implementation is bad."
1727 :group 'org-link-follow
1728 :type 'boolean)
1730 (defcustom org-return-follows-link nil
1731 "Non-nil means on links RET will follow the link.
1732 In tables, the special behavior of RET has precedence."
1733 :group 'org-link-follow
1734 :type 'boolean)
1736 (defcustom org-mouse-1-follows-link
1737 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1738 "Non-nil means mouse-1 on a link will follow the link.
1739 A longer mouse click will still set point. Does not work on XEmacs.
1740 Needs to be set before org.el is loaded."
1741 :group 'org-link-follow
1742 :version "24.4"
1743 :package-version '(Org . "8.3")
1744 :type '(choice
1745 (const :tag "A double click follows the link" double)
1746 (const :tag "Unconditionally follow the link with mouse-1" t)
1747 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
1749 (defcustom org-mark-ring-length 4
1750 "Number of different positions to be recorded in the ring.
1751 Changing this requires a restart of Emacs to work correctly."
1752 :group 'org-link-follow
1753 :type 'integer)
1755 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1756 "Non-nil means internal links in Org files must exactly match a headline.
1757 When nil, the link search tries to match a phrase with all words
1758 in the search text."
1759 :group 'org-link-follow
1760 :version "24.1"
1761 :type '(choice
1762 (const :tag "Use fuzzy text search" nil)
1763 (const :tag "Match only exact headline" t)
1764 (const :tag "Match exact headline or query to create it"
1765 query-to-create)))
1767 (defcustom org-link-frame-setup
1768 '((vm . vm-visit-folder-other-frame)
1769 (vm-imap . vm-visit-imap-folder-other-frame)
1770 (gnus . org-gnus-no-new-news)
1771 (file . find-file-other-window)
1772 (wl . wl-other-frame))
1773 "Setup the frame configuration for following links.
1774 When following a link with Emacs, it may often be useful to display
1775 this link in another window or frame. This variable can be used to
1776 set this up for the different types of links.
1777 For VM, use any of
1778 `vm-visit-folder'
1779 `vm-visit-folder-other-window'
1780 `vm-visit-folder-other-frame'
1781 For Gnus, use any of
1782 `gnus'
1783 `gnus-other-frame'
1784 `org-gnus-no-new-news'
1785 For FILE, use any of
1786 `find-file'
1787 `find-file-other-window'
1788 `find-file-other-frame'
1789 For Wanderlust use any of
1790 `wl'
1791 `wl-other-frame'
1792 For the calendar, use the variable `calendar-setup'.
1793 For BBDB, it is currently only possible to display the matches in
1794 another window."
1795 :group 'org-link-follow
1796 :type '(list
1797 (cons (const vm)
1798 (choice
1799 (const vm-visit-folder)
1800 (const vm-visit-folder-other-window)
1801 (const vm-visit-folder-other-frame)))
1802 (cons (const vm-imap)
1803 (choice
1804 (const vm-visit-imap-folder)
1805 (const vm-visit-imap-folder-other-window)
1806 (const vm-visit-imap-folder-other-frame)))
1807 (cons (const gnus)
1808 (choice
1809 (const gnus)
1810 (const gnus-other-frame)
1811 (const org-gnus-no-new-news)))
1812 (cons (const file)
1813 (choice
1814 (const find-file)
1815 (const find-file-other-window)
1816 (const find-file-other-frame)))
1817 (cons (const wl)
1818 (choice
1819 (const wl)
1820 (const wl-other-frame)))))
1822 (defcustom org-display-internal-link-with-indirect-buffer nil
1823 "Non-nil means use indirect buffer to display infile links.
1824 Activating internal links (from one location in a file to another location
1825 in the same file) normally just jumps to the location. When the link is
1826 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1827 is displayed in
1828 another window. When this option is set, the other window actually displays
1829 an indirect buffer clone of the current buffer, to avoid any visibility
1830 changes to the current buffer."
1831 :group 'org-link-follow
1832 :type 'boolean)
1834 (defcustom org-open-non-existing-files nil
1835 "Non-nil means `org-open-file' will open non-existing files.
1836 When nil, an error will be generated.
1837 This variable applies only to external applications because they
1838 might choke on non-existing files. If the link is to a file that
1839 will be opened in Emacs, the variable is ignored."
1840 :group 'org-link-follow
1841 :type 'boolean)
1843 (defcustom org-open-directory-means-index-dot-org nil
1844 "Non-nil means a link to a directory really means to index.org.
1845 When nil, following a directory link will run dired or open a finder/explorer
1846 window on that directory."
1847 :group 'org-link-follow
1848 :type 'boolean)
1850 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1851 "Function and arguments to call for following mailto links.
1852 This is a list with the first element being a Lisp function, and the
1853 remaining elements being arguments to the function. In string arguments,
1854 %a will be replaced by the address, and %s will be replaced by the subject
1855 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1856 :group 'org-link-follow
1857 :type '(choice
1858 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1859 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1860 (const :tag "message-mail" (message-mail "%a" "%s"))
1861 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1863 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1864 "Non-nil means ask for confirmation before executing shell links.
1865 Shell links can be dangerous: just think about a link
1867 [[shell:rm -rf ~/*][Google Search]]
1869 This link would show up in your Org-mode document as \"Google Search\",
1870 but really it would remove your entire home directory.
1871 Therefore we advise against setting this variable to nil.
1872 Just change it to `y-or-n-p' if you want to confirm with a
1873 single keystroke rather than having to type \"yes\"."
1874 :group 'org-link-follow
1875 :type '(choice
1876 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1877 (const :tag "with y-or-n (faster)" y-or-n-p)
1878 (const :tag "no confirmation (dangerous)" nil)))
1879 (put 'org-confirm-shell-link-function
1880 'safe-local-variable
1881 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1883 (defcustom org-confirm-shell-link-not-regexp ""
1884 "A regexp to skip confirmation for shell links."
1885 :group 'org-link-follow
1886 :version "24.1"
1887 :type 'regexp)
1889 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1890 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1891 Elisp links can be dangerous: just think about a link
1893 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1895 This link would show up in your Org-mode document as \"Google Search\",
1896 but really it would remove your entire home directory.
1897 Therefore we advise against setting this variable to nil.
1898 Just change it to `y-or-n-p' if you want to confirm with a
1899 single keystroke rather than having to type \"yes\"."
1900 :group 'org-link-follow
1901 :type '(choice
1902 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1903 (const :tag "with y-or-n (faster)" y-or-n-p)
1904 (const :tag "no confirmation (dangerous)" nil)))
1905 (put 'org-confirm-shell-link-function
1906 'safe-local-variable
1907 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1909 (defcustom org-confirm-elisp-link-not-regexp ""
1910 "A regexp to skip confirmation for Elisp links."
1911 :group 'org-link-follow
1912 :version "24.1"
1913 :type 'regexp)
1915 (defconst org-file-apps-defaults-gnu
1916 '((remote . emacs)
1917 (system . mailcap)
1918 (t . mailcap))
1919 "Default file applications on a UNIX or GNU/Linux system.
1920 See `org-file-apps'.")
1922 (defconst org-file-apps-defaults-macosx
1923 '((remote . emacs)
1924 (t . "open %s")
1925 (system . "open %s")
1926 ("ps.gz" . "gv %s")
1927 ("eps.gz" . "gv %s")
1928 ("dvi" . "xdvi %s")
1929 ("fig" . "xfig %s"))
1930 "Default file applications on a MacOS X system.
1931 The system \"open\" is known as a default, but we use X11 applications
1932 for some files for which the OS does not have a good default.
1933 See `org-file-apps'.")
1935 (defconst org-file-apps-defaults-windowsnt
1936 (list
1937 '(remote . emacs)
1938 (cons t
1939 (list (if (featurep 'xemacs)
1940 'mswindows-shell-execute
1941 'w32-shell-execute)
1942 "open" 'file))
1943 (cons 'system
1944 (list (if (featurep 'xemacs)
1945 'mswindows-shell-execute
1946 'w32-shell-execute)
1947 "open" 'file)))
1948 "Default file applications on a Windows NT system.
1949 The system \"open\" is used for most files.
1950 See `org-file-apps'.")
1952 (defcustom org-file-apps
1953 '((auto-mode . emacs)
1954 ("\\.mm\\'" . default)
1955 ("\\.x?html?\\'" . default)
1956 ("\\.pdf\\'" . default))
1957 "External applications for opening `file:path' items in a document.
1958 Org-mode uses system defaults for different file types, but
1959 you can use this variable to set the application for a given file
1960 extension. The entries in this list are cons cells where the car identifies
1961 files and the cdr the corresponding command. Possible values for the
1962 file identifier are
1963 \"string\" A string as a file identifier can be interpreted in different
1964 ways, depending on its contents:
1966 - Alphanumeric characters only:
1967 Match links with this file extension.
1968 Example: (\"pdf\" . \"evince %s\")
1969 to open PDFs with evince.
1971 - Regular expression: Match links where the
1972 filename matches the regexp. If you want to
1973 use groups here, use shy groups.
1975 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1976 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1977 to open *.html and *.xhtml with firefox.
1979 - Regular expression which contains (non-shy) groups:
1980 Match links where the whole link, including \"::\", and
1981 anything after that, matches the regexp.
1982 In a custom command string, %1, %2, etc. are replaced with
1983 the parts of the link that were matched by the groups.
1984 For backwards compatibility, if a command string is given
1985 that does not use any of the group matches, this case is
1986 handled identically to the second one (i.e. match against
1987 file name only).
1988 In a custom lisp form, you can access the group matches with
1989 (match-string n link).
1991 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1992 to open [[file:document.pdf::5]] with evince at page 5.
1994 `directory' Matches a directory
1995 `remote' Matches a remote file, accessible through tramp or efs.
1996 Remote files most likely should be visited through Emacs
1997 because external applications cannot handle such paths.
1998 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1999 so all files Emacs knows how to handle. Using this with
2000 command `emacs' will open most files in Emacs. Beware that this
2001 will also open html files inside Emacs, unless you add
2002 (\"html\" . default) to the list as well.
2003 t Default for files not matched by any of the other options.
2004 `system' The system command to open files, like `open' on Windows
2005 and Mac OS X, and mailcap under GNU/Linux. This is the command
2006 that will be selected if you call `C-c C-o' with a double
2007 \\[universal-argument] \\[universal-argument] prefix.
2009 Possible values for the command are:
2010 `emacs' The file will be visited by the current Emacs process.
2011 `default' Use the default application for this file type, which is the
2012 association for t in the list, most likely in the system-specific
2013 part.
2014 This can be used to overrule an unwanted setting in the
2015 system-specific variable.
2016 `system' Use the system command for opening files, like \"open\".
2017 This command is specified by the entry whose car is `system'.
2018 Most likely, the system-specific version of this variable
2019 does define this command, but you can overrule/replace it
2020 here.
2021 string A command to be executed by a shell; %s will be replaced
2022 by the path to the file.
2023 sexp A Lisp form which will be evaluated. The file path will
2024 be available in the Lisp variable `file'.
2025 For more examples, see the system specific constants
2026 `org-file-apps-defaults-macosx'
2027 `org-file-apps-defaults-windowsnt'
2028 `org-file-apps-defaults-gnu'."
2029 :group 'org-link-follow
2030 :type '(repeat
2031 (cons (choice :value ""
2032 (string :tag "Extension")
2033 (const :tag "System command to open files" system)
2034 (const :tag "Default for unrecognized files" t)
2035 (const :tag "Remote file" remote)
2036 (const :tag "Links to a directory" directory)
2037 (const :tag "Any files that have Emacs modes"
2038 auto-mode))
2039 (choice :value ""
2040 (const :tag "Visit with Emacs" emacs)
2041 (const :tag "Use default" default)
2042 (const :tag "Use the system command" system)
2043 (string :tag "Command")
2044 (sexp :tag "Lisp form")))))
2046 (defcustom org-doi-server-url "http://dx.doi.org/"
2047 "The URL of the DOI server."
2048 :type 'string
2049 :version "24.3"
2050 :group 'org-link-follow)
2052 (defgroup org-refile nil
2053 "Options concerning refiling entries in Org-mode."
2054 :tag "Org Refile"
2055 :group 'org)
2057 (defcustom org-directory "~/org"
2058 "Directory with org files.
2059 This is just a default location to look for Org files. There is no need
2060 at all to put your files into this directory. It is only used in the
2061 following situations:
2063 1. When a capture template specifies a target file that is not an
2064 absolute path. The path will then be interpreted relative to
2065 `org-directory'
2066 2. When a capture note is filed away in an interactive way (when exiting the
2067 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2068 with `org-directory' as the default path."
2069 :group 'org-refile
2070 :group 'org-capture
2071 :type 'directory)
2073 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2074 "Default target for storing notes.
2075 Used as a fall back file for org-capture.el, for templates that
2076 do not specify a target file."
2077 :group 'org-refile
2078 :group 'org-capture
2079 :type '(choice
2080 (const :tag "Default from remember-data-file" nil)
2081 file))
2083 (defcustom org-goto-interface 'outline
2084 "The default interface to be used for `org-goto'.
2085 Allowed values are:
2086 outline The interface shows an outline of the relevant file
2087 and the correct heading is found by moving through
2088 the outline or by searching with incremental search.
2089 outline-path-completion Headlines in the current buffer are offered via
2090 completion. This is the interface also used by
2091 the refile command."
2092 :group 'org-refile
2093 :type '(choice
2094 (const :tag "Outline" outline)
2095 (const :tag "Outline-path-completion" outline-path-completion)))
2097 (defcustom org-goto-max-level 5
2098 "Maximum target level when running `org-goto' with refile interface."
2099 :group 'org-refile
2100 :type 'integer)
2102 (defcustom org-reverse-note-order nil
2103 "Non-nil means store new notes at the beginning of a file or entry.
2104 When nil, new notes will be filed to the end of a file or entry.
2105 This can also be a list with cons cells of regular expressions that
2106 are matched against file names, and values."
2107 :group 'org-capture
2108 :group 'org-refile
2109 :type '(choice
2110 (const :tag "Reverse always" t)
2111 (const :tag "Reverse never" nil)
2112 (repeat :tag "By file name regexp"
2113 (cons regexp boolean))))
2115 (defcustom org-log-refile nil
2116 "Information to record when a task is refiled.
2118 Possible values are:
2120 nil Don't add anything
2121 time Add a time stamp to the task
2122 note Prompt for a note and add it with template `org-log-note-headings'
2124 This option can also be set with on a per-file-basis with
2126 #+STARTUP: nologrefile
2127 #+STARTUP: logrefile
2128 #+STARTUP: lognoterefile
2130 You can have local logging settings for a subtree by setting the LOGGING
2131 property to one or more of these keywords.
2133 When bulk-refiling from the agenda, the value `note' is forbidden and
2134 will temporarily be changed to `time'."
2135 :group 'org-refile
2136 :group 'org-progress
2137 :version "24.1"
2138 :type '(choice
2139 (const :tag "No logging" nil)
2140 (const :tag "Record timestamp" time)
2141 (const :tag "Record timestamp with note." note)))
2143 (defcustom org-refile-targets nil
2144 "Targets for refiling entries with \\[org-refile].
2145 This is a list of cons cells. Each cell contains:
2146 - a specification of the files to be considered, either a list of files,
2147 or a symbol whose function or variable value will be used to retrieve
2148 a file name or a list of file names. If you use `org-agenda-files' for
2149 that, all agenda files will be scanned for targets. Nil means consider
2150 headings in the current buffer.
2151 - A specification of how to find candidate refile targets. This may be
2152 any of:
2153 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2154 This tag has to be present in all target headlines, inheritance will
2155 not be considered.
2156 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2157 todo keyword.
2158 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2159 headlines that are refiling targets.
2160 - a cons cell (:level . N). Any headline of level N is considered a target.
2161 Note that, when `org-odd-levels-only' is set, level corresponds to
2162 order in hierarchy, not to the number of stars.
2163 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2164 Note that, when `org-odd-levels-only' is set, level corresponds to
2165 order in hierarchy, not to the number of stars.
2167 Each element of this list generates a set of possible targets.
2168 The union of these sets is presented (with completion) to
2169 the user by `org-refile'.
2171 You can set the variable `org-refile-target-verify-function' to a function
2172 to verify each headline found by the simple criteria above.
2174 When this variable is nil, all top-level headlines in the current buffer
2175 are used, equivalent to the value `((nil . (:level . 1))'."
2176 :group 'org-refile
2177 :type '(repeat
2178 (cons
2179 (choice :value org-agenda-files
2180 (const :tag "All agenda files" org-agenda-files)
2181 (const :tag "Current buffer" nil)
2182 (function) (variable) (file))
2183 (choice :tag "Identify target headline by"
2184 (cons :tag "Specific tag" (const :value :tag) (string))
2185 (cons :tag "TODO keyword" (const :value :todo) (string))
2186 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2187 (cons :tag "Level number" (const :value :level) (integer))
2188 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2190 (defcustom org-refile-target-verify-function nil
2191 "Function to verify if the headline at point should be a refile target.
2192 The function will be called without arguments, with point at the
2193 beginning of the headline. It should return t and leave point
2194 where it is if the headline is a valid target for refiling.
2196 If the target should not be selected, the function must return nil.
2197 In addition to this, it may move point to a place from where the search
2198 should be continued. For example, the function may decide that the entire
2199 subtree of the current entry should be excluded and move point to the end
2200 of the subtree."
2201 :group 'org-refile
2202 :type '(choice
2203 (const nil)
2204 (function)))
2206 (defcustom org-refile-use-cache nil
2207 "Non-nil means cache refile targets to speed up the process.
2208 The cache for a particular file will be updated automatically when
2209 the buffer has been killed, or when any of the marker used for flagging
2210 refile targets no longer points at a live buffer.
2211 If you have added new entries to a buffer that might themselves be targets,
2212 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2213 find that easier, `C-u C-u C-u C-c C-w'."
2214 :group 'org-refile
2215 :version "24.1"
2216 :type 'boolean)
2218 (defcustom org-refile-use-outline-path nil
2219 "Non-nil means provide refile targets as paths.
2220 So a level 3 headline will be available as level1/level2/level3.
2222 When the value is `file', also include the file name (without directory)
2223 into the path. In this case, you can also stop the completion after
2224 the file name, to get entries inserted as top level in the file.
2226 When `full-file-path', include the full file path."
2227 :group 'org-refile
2228 :type '(choice
2229 (const :tag "Not" nil)
2230 (const :tag "Yes" t)
2231 (const :tag "Start with file name" file)
2232 (const :tag "Start with full file path" full-file-path)))
2234 (defcustom org-outline-path-complete-in-steps t
2235 "Non-nil means complete the outline path in hierarchical steps.
2236 When Org-mode uses the refile interface to select an outline path
2237 \(see variable `org-refile-use-outline-path'), the completion of
2238 the path can be done is a single go, or if can be done in steps down
2239 the headline hierarchy. Going in steps is probably the best if you
2240 do not use a special completion package like `ido' or `icicles'.
2241 However, when using these packages, going in one step can be very
2242 fast, while still showing the whole path to the entry."
2243 :group 'org-refile
2244 :type 'boolean)
2246 (defcustom org-refile-allow-creating-parent-nodes nil
2247 "Non-nil means allow to create new nodes as refile targets.
2248 New nodes are then created by adding \"/new node name\" to the completion
2249 of an existing node. When the value of this variable is `confirm',
2250 new node creation must be confirmed by the user (recommended).
2251 When nil, the completion must match an existing entry.
2253 Note that, if the new heading is not seen by the criteria
2254 listed in `org-refile-targets', multiple instances of the same
2255 heading would be created by trying again to file under the new
2256 heading."
2257 :group 'org-refile
2258 :type '(choice
2259 (const :tag "Never" nil)
2260 (const :tag "Always" t)
2261 (const :tag "Prompt for confirmation" confirm)))
2263 (defcustom org-refile-active-region-within-subtree nil
2264 "Non-nil means also refile active region within a subtree.
2266 By default `org-refile' doesn't allow refiling regions if they
2267 don't contain a set of subtrees, but it might be convenient to
2268 do so sometimes: in that case, the first line of the region is
2269 converted to a headline before refiling."
2270 :group 'org-refile
2271 :version "24.1"
2272 :type 'boolean)
2274 (defgroup org-todo nil
2275 "Options concerning TODO items in Org-mode."
2276 :tag "Org TODO"
2277 :group 'org)
2279 (defgroup org-progress nil
2280 "Options concerning Progress logging in Org-mode."
2281 :tag "Org Progress"
2282 :group 'org-time)
2284 (defvar org-todo-interpretation-widgets
2285 '((:tag "Sequence (cycling hits every state)" sequence)
2286 (:tag "Type (cycling directly to DONE)" type))
2287 "The available interpretation symbols for customizing `org-todo-keywords'.
2288 Interested libraries should add to this list.")
2290 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2291 "List of TODO entry keyword sequences and their interpretation.
2292 \\<org-mode-map>This is a list of sequences.
2294 Each sequence starts with a symbol, either `sequence' or `type',
2295 indicating if the keywords should be interpreted as a sequence of
2296 action steps, or as different types of TODO items. The first
2297 keywords are states requiring action - these states will select a headline
2298 for inclusion into the global TODO list Org-mode produces. If one of
2299 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2300 signify that no further action is necessary. If \"|\" is not found,
2301 the last keyword is treated as the only DONE state of the sequence.
2303 The command \\[org-todo] cycles an entry through these states, and one
2304 additional state where no keyword is present. For details about this
2305 cycling, see the manual.
2307 TODO keywords and interpretation can also be set on a per-file basis with
2308 the special #+SEQ_TODO and #+TYP_TODO lines.
2310 Each keyword can optionally specify a character for fast state selection
2311 \(in combination with the variable `org-use-fast-todo-selection')
2312 and specifiers for state change logging, using the same syntax that
2313 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2314 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2315 indicates to record a time stamp each time this state is selected.
2317 Each keyword may also specify if a timestamp or a note should be
2318 recorded when entering or leaving the state, by adding additional
2319 characters in the parenthesis after the keyword. This looks like this:
2320 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2321 record only the time of the state change. With X and Y being either
2322 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2323 Y when leaving the state if and only if the *target* state does not
2324 define X. You may omit any of the fast-selection key or X or /Y,
2325 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2327 For backward compatibility, this variable may also be just a list
2328 of keywords. In this case the interpretation (sequence or type) will be
2329 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2330 :group 'org-todo
2331 :group 'org-keywords
2332 :type '(choice
2333 (repeat :tag "Old syntax, just keywords"
2334 (string :tag "Keyword"))
2335 (repeat :tag "New syntax"
2336 (cons
2337 (choice
2338 :tag "Interpretation"
2339 ;;Quick and dirty way to see
2340 ;;`org-todo-interpretations'. This takes the
2341 ;;place of item arguments
2342 :convert-widget
2343 (lambda (widget)
2344 (widget-put widget
2345 :args (mapcar
2346 #'(lambda (x)
2347 (widget-convert
2348 (cons 'const x)))
2349 org-todo-interpretation-widgets))
2350 widget))
2351 (repeat
2352 (string :tag "Keyword"))))))
2354 (defvar org-todo-keywords-1 nil
2355 "All TODO and DONE keywords active in a buffer.")
2356 (make-variable-buffer-local 'org-todo-keywords-1)
2357 (defvar org-todo-keywords-for-agenda nil)
2358 (defvar org-done-keywords-for-agenda nil)
2359 (defvar org-drawers-for-agenda nil)
2360 (defvar org-todo-keyword-alist-for-agenda nil)
2361 (defvar org-tag-alist-for-agenda nil
2362 "Alist of all tags from all agenda files.")
2363 (defvar org-tag-groups-alist-for-agenda nil
2364 "Alist of all groups tags from all current agenda files.")
2365 (defvar org-tag-groups-alist nil)
2366 (make-variable-buffer-local 'org-tag-groups-alist)
2367 (defvar org-agenda-contributing-files nil)
2368 (defvar org-not-done-keywords nil)
2369 (make-variable-buffer-local 'org-not-done-keywords)
2370 (defvar org-done-keywords nil)
2371 (make-variable-buffer-local 'org-done-keywords)
2372 (defvar org-todo-heads nil)
2373 (make-variable-buffer-local 'org-todo-heads)
2374 (defvar org-todo-sets nil)
2375 (make-variable-buffer-local 'org-todo-sets)
2376 (defvar org-todo-log-states nil)
2377 (make-variable-buffer-local 'org-todo-log-states)
2378 (defvar org-todo-kwd-alist nil)
2379 (make-variable-buffer-local 'org-todo-kwd-alist)
2380 (defvar org-todo-key-alist nil)
2381 (make-variable-buffer-local 'org-todo-key-alist)
2382 (defvar org-todo-key-trigger nil)
2383 (make-variable-buffer-local 'org-todo-key-trigger)
2385 (defcustom org-todo-interpretation 'sequence
2386 "Controls how TODO keywords are interpreted.
2387 This variable is in principle obsolete and is only used for
2388 backward compatibility, if the interpretation of todo keywords is
2389 not given already in `org-todo-keywords'. See that variable for
2390 more information."
2391 :group 'org-todo
2392 :group 'org-keywords
2393 :type '(choice (const sequence)
2394 (const type)))
2396 (defcustom org-use-fast-todo-selection t
2397 "Non-nil means use the fast todo selection scheme with C-c C-t.
2398 This variable describes if and under what circumstances the cycling
2399 mechanism for TODO keywords will be replaced by a single-key, direct
2400 selection scheme.
2402 When nil, fast selection is never used.
2404 When the symbol `prefix', it will be used when `org-todo' is called
2405 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2406 `C-u t' in an agenda buffer.
2408 When t, fast selection is used by default. In this case, the prefix
2409 argument forces cycling instead.
2411 In all cases, the special interface is only used if access keys have
2412 actually been assigned by the user, i.e. if keywords in the configuration
2413 are followed by a letter in parenthesis, like TODO(t)."
2414 :group 'org-todo
2415 :type '(choice
2416 (const :tag "Never" nil)
2417 (const :tag "By default" t)
2418 (const :tag "Only with C-u C-c C-t" prefix)))
2420 (defcustom org-provide-todo-statistics t
2421 "Non-nil means update todo statistics after insert and toggle.
2422 ALL-HEADLINES means update todo statistics by including headlines
2423 with no TODO keyword as well, counting them as not done.
2424 A list of TODO keywords means the same, but skip keywords that are
2425 not in this list.
2427 When this is set, todo statistics is updated in the parent of the
2428 current entry each time a todo state is changed."
2429 :group 'org-todo
2430 :type '(choice
2431 (const :tag "Yes, only for TODO entries" t)
2432 (const :tag "Yes, including all entries" all-headlines)
2433 (repeat :tag "Yes, for TODOs in this list"
2434 (string :tag "TODO keyword"))
2435 (other :tag "No TODO statistics" nil)))
2437 (defcustom org-hierarchical-todo-statistics t
2438 "Non-nil means TODO statistics covers just direct children.
2439 When nil, all entries in the subtree are considered.
2440 This has only an effect if `org-provide-todo-statistics' is set.
2441 To set this to nil for only a single subtree, use a COOKIE_DATA
2442 property and include the word \"recursive\" into the value."
2443 :group 'org-todo
2444 :type 'boolean)
2446 (defcustom org-after-todo-state-change-hook nil
2447 "Hook which is run after the state of a TODO item was changed.
2448 The new state (a string with a TODO keyword, or nil) is available in the
2449 Lisp variable `org-state'."
2450 :group 'org-todo
2451 :type 'hook)
2453 (defvar org-blocker-hook nil
2454 "Hook for functions that are allowed to block a state change.
2456 Functions in this hook should not modify the buffer.
2457 Each function gets as its single argument a property list,
2458 see `org-trigger-hook' for more information about this list.
2460 If any of the functions in this hook returns nil, the state change
2461 is blocked.")
2463 (defvar org-trigger-hook nil
2464 "Hook for functions that are triggered by a state change.
2466 Each function gets as its single argument a property list with at
2467 least the following elements:
2469 (:type type-of-change :position pos-at-entry-start
2470 :from old-state :to new-state)
2472 Depending on the type, more properties may be present.
2474 This mechanism is currently implemented for:
2476 TODO state changes
2477 ------------------
2478 :type todo-state-change
2479 :from previous state (keyword as a string), or nil, or a symbol
2480 'todo' or 'done', to indicate the general type of state.
2481 :to new state, like in :from")
2483 (defcustom org-enforce-todo-dependencies nil
2484 "Non-nil means undone TODO entries will block switching the parent to DONE.
2485 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2486 be blocked if any prior sibling is not yet done.
2487 Finally, if the parent is blocked because of ordered siblings of its own,
2488 the child will also be blocked."
2489 :set (lambda (var val)
2490 (set var val)
2491 (if val
2492 (add-hook 'org-blocker-hook
2493 'org-block-todo-from-children-or-siblings-or-parent)
2494 (remove-hook 'org-blocker-hook
2495 'org-block-todo-from-children-or-siblings-or-parent)))
2496 :group 'org-todo
2497 :type 'boolean)
2499 (defcustom org-enforce-todo-checkbox-dependencies nil
2500 "Non-nil means unchecked boxes will block switching the parent to DONE.
2501 When this is nil, checkboxes have no influence on switching TODO states.
2502 When non-nil, you first need to check off all check boxes before the TODO
2503 entry can be switched to DONE.
2504 This variable needs to be set before org.el is loaded, and you need to
2505 restart Emacs after a change to make the change effective. The only way
2506 to change is while Emacs is running is through the customize interface."
2507 :set (lambda (var val)
2508 (set var val)
2509 (if val
2510 (add-hook 'org-blocker-hook
2511 'org-block-todo-from-checkboxes)
2512 (remove-hook 'org-blocker-hook
2513 'org-block-todo-from-checkboxes)))
2514 :group 'org-todo
2515 :type 'boolean)
2517 (defcustom org-treat-insert-todo-heading-as-state-change nil
2518 "Non-nil means inserting a TODO heading is treated as state change.
2519 So when the command \\[org-insert-todo-heading] is used, state change
2520 logging will apply if appropriate. When nil, the new TODO item will
2521 be inserted directly, and no logging will take place."
2522 :group 'org-todo
2523 :type 'boolean)
2525 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2526 "Non-nil means switching TODO states with S-cursor counts as state change.
2527 This is the default behavior. However, setting this to nil allows a
2528 convenient way to select a TODO state and bypass any logging associated
2529 with that."
2530 :group 'org-todo
2531 :type 'boolean)
2533 (defcustom org-todo-state-tags-triggers nil
2534 "Tag changes that should be triggered by TODO state changes.
2535 This is a list. Each entry is
2537 (state-change (tag . flag) .......)
2539 State-change can be a string with a state, and empty string to indicate the
2540 state that has no TODO keyword, or it can be one of the symbols `todo'
2541 or `done', meaning any not-done or done state, respectively."
2542 :group 'org-todo
2543 :group 'org-tags
2544 :type '(repeat
2545 (cons (choice :tag "When changing to"
2546 (const :tag "Not-done state" todo)
2547 (const :tag "Done state" done)
2548 (string :tag "State"))
2549 (repeat
2550 (cons :tag "Tag action"
2551 (string :tag "Tag")
2552 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2554 (defcustom org-log-done nil
2555 "Information to record when a task moves to the DONE state.
2557 Possible values are:
2559 nil Don't add anything, just change the keyword
2560 time Add a time stamp to the task
2561 note Prompt for a note and add it with template `org-log-note-headings'
2563 This option can also be set with on a per-file-basis with
2565 #+STARTUP: nologdone
2566 #+STARTUP: logdone
2567 #+STARTUP: lognotedone
2569 You can have local logging settings for a subtree by setting the LOGGING
2570 property to one or more of these keywords."
2571 :group 'org-todo
2572 :group 'org-progress
2573 :type '(choice
2574 (const :tag "No logging" nil)
2575 (const :tag "Record CLOSED timestamp" time)
2576 (const :tag "Record CLOSED timestamp with note." note)))
2578 ;; Normalize old uses of org-log-done.
2579 (cond
2580 ((eq org-log-done t) (setq org-log-done 'time))
2581 ((and (listp org-log-done) (memq 'done org-log-done))
2582 (setq org-log-done 'note)))
2584 (defcustom org-log-reschedule nil
2585 "Information to record when the scheduling date of a tasks is modified.
2587 Possible values are:
2589 nil Don't add anything, just change the date
2590 time Add a time stamp to the task
2591 note Prompt for a note and add it with template `org-log-note-headings'
2593 This option can also be set with on a per-file-basis with
2595 #+STARTUP: nologreschedule
2596 #+STARTUP: logreschedule
2597 #+STARTUP: lognotereschedule"
2598 :group 'org-todo
2599 :group 'org-progress
2600 :type '(choice
2601 (const :tag "No logging" nil)
2602 (const :tag "Record timestamp" time)
2603 (const :tag "Record timestamp with note." note)))
2605 (defcustom org-log-redeadline nil
2606 "Information to record when the deadline date of a tasks is modified.
2608 Possible values are:
2610 nil Don't add anything, just change the date
2611 time Add a time stamp to the task
2612 note Prompt for a note and add it with template `org-log-note-headings'
2614 This option can also be set with on a per-file-basis with
2616 #+STARTUP: nologredeadline
2617 #+STARTUP: logredeadline
2618 #+STARTUP: lognoteredeadline
2620 You can have local logging settings for a subtree by setting the LOGGING
2621 property to one or more of these keywords."
2622 :group 'org-todo
2623 :group 'org-progress
2624 :type '(choice
2625 (const :tag "No logging" nil)
2626 (const :tag "Record timestamp" time)
2627 (const :tag "Record timestamp with note." note)))
2629 (defcustom org-log-note-clock-out nil
2630 "Non-nil means record a note when clocking out of an item.
2631 This can also be configured on a per-file basis by adding one of
2632 the following lines anywhere in the buffer:
2634 #+STARTUP: lognoteclock-out
2635 #+STARTUP: nolognoteclock-out"
2636 :group 'org-todo
2637 :group 'org-progress
2638 :type 'boolean)
2640 (defcustom org-log-done-with-time t
2641 "Non-nil means the CLOSED time stamp will contain date and time.
2642 When nil, only the date will be recorded."
2643 :group 'org-progress
2644 :type 'boolean)
2646 (defcustom org-log-note-headings
2647 '((done . "CLOSING NOTE %t")
2648 (state . "State %-12s from %-12S %t")
2649 (note . "Note taken on %t")
2650 (reschedule . "Rescheduled from %S on %t")
2651 (delschedule . "Not scheduled, was %S on %t")
2652 (redeadline . "New deadline from %S on %t")
2653 (deldeadline . "Removed deadline, was %S on %t")
2654 (refile . "Refiled on %t")
2655 (clock-out . ""))
2656 "Headings for notes added to entries.
2657 The value is an alist, with the car being a symbol indicating the note
2658 context, and the cdr is the heading to be used. The heading may also be the
2659 empty string.
2660 %t in the heading will be replaced by a time stamp.
2661 %T will be an active time stamp instead the default inactive one
2662 %d will be replaced by a short-format time stamp.
2663 %D will be replaced by an active short-format time stamp.
2664 %s will be replaced by the new TODO state, in double quotes.
2665 %S will be replaced by the old TODO state, in double quotes.
2666 %u will be replaced by the user name.
2667 %U will be replaced by the full user name.
2669 In fact, it is not a good idea to change the `state' entry, because
2670 agenda log mode depends on the format of these entries."
2671 :group 'org-todo
2672 :group 'org-progress
2673 :type '(list :greedy t
2674 (cons (const :tag "Heading when closing an item" done) string)
2675 (cons (const :tag
2676 "Heading when changing todo state (todo sequence only)"
2677 state) string)
2678 (cons (const :tag "Heading when just taking a note" note) string)
2679 (cons (const :tag "Heading when rescheduling" reschedule) string)
2680 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2681 (cons (const :tag "Heading when changing deadline" redeadline) string)
2682 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2683 (cons (const :tag "Heading when refiling" refile) string)
2684 (cons (const :tag "Heading when clocking out" clock-out) string)))
2686 (unless (assq 'note org-log-note-headings)
2687 (push '(note . "%t") org-log-note-headings))
2689 (defcustom org-log-into-drawer nil
2690 "Non-nil means insert state change notes and time stamps into a drawer.
2691 When nil, state changes notes will be inserted after the headline and
2692 any scheduling and clock lines, but not inside a drawer.
2694 The value of this variable should be the name of the drawer to use.
2695 LOGBOOK is proposed as the default drawer for this purpose, you can
2696 also set this to a string to define the drawer of your choice.
2698 A value of t is also allowed, representing \"LOGBOOK\".
2700 A value of t or nil can also be set with on a per-file-basis with
2702 #+STARTUP: logdrawer
2703 #+STARTUP: nologdrawer
2705 If this variable is set, `org-log-state-notes-insert-after-drawers'
2706 will be ignored.
2708 You can set the property LOG_INTO_DRAWER to overrule this setting for
2709 a subtree."
2710 :group 'org-todo
2711 :group 'org-progress
2712 :type '(choice
2713 (const :tag "Not into a drawer" nil)
2714 (const :tag "LOGBOOK" t)
2715 (string :tag "Other")))
2717 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2719 (defun org-log-into-drawer ()
2720 "Return the value of `org-log-into-drawer', but let properties overrule.
2721 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2722 used instead of the default value."
2723 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2724 (cond
2725 ((not p) org-log-into-drawer)
2726 ((equal p "nil") nil)
2727 ((equal p "t") "LOGBOOK")
2728 (t p))))
2730 (defcustom org-log-state-notes-insert-after-drawers nil
2731 "Non-nil means insert state change notes after any drawers in entry.
2732 Only the drawers that *immediately* follow the headline and the
2733 deadline/scheduled line are skipped.
2734 When nil, insert notes right after the heading and perhaps the line
2735 with deadline/scheduling if present.
2737 This variable will have no effect if `org-log-into-drawer' is
2738 set."
2739 :group 'org-todo
2740 :group 'org-progress
2741 :type 'boolean)
2743 (defcustom org-log-states-order-reversed t
2744 "Non-nil means the latest state note will be directly after heading.
2745 When nil, the state change notes will be ordered according to time.
2747 This option can also be set with on a per-file-basis with
2749 #+STARTUP: logstatesreversed
2750 #+STARTUP: nologstatesreversed"
2751 :group 'org-todo
2752 :group 'org-progress
2753 :type 'boolean)
2755 (defcustom org-todo-repeat-to-state nil
2756 "The TODO state to which a repeater should return the repeating task.
2757 By default this is the first task in a TODO sequence, or the previous state
2758 in a TODO_TYP set. But you can specify another task here.
2759 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2760 :group 'org-todo
2761 :version "24.1"
2762 :type '(choice (const :tag "Head of sequence" nil)
2763 (string :tag "Specific state")))
2765 (defcustom org-log-repeat 'time
2766 "Non-nil means record moving through the DONE state when triggering repeat.
2767 An auto-repeating task is immediately switched back to TODO when
2768 marked DONE. If you are not logging state changes (by adding \"@\"
2769 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2770 record a closing note, there will be no record of the task moving
2771 through DONE. This variable forces taking a note anyway.
2773 nil Don't force a record
2774 time Record a time stamp
2775 note Prompt for a note and add it with template `org-log-note-headings'
2777 This option can also be set with on a per-file-basis with
2779 #+STARTUP: nologrepeat
2780 #+STARTUP: logrepeat
2781 #+STARTUP: lognoterepeat
2783 You can have local logging settings for a subtree by setting the LOGGING
2784 property to one or more of these keywords."
2785 :group 'org-todo
2786 :group 'org-progress
2787 :type '(choice
2788 (const :tag "Don't force a record" nil)
2789 (const :tag "Force recording the DONE state" time)
2790 (const :tag "Force recording a note with the DONE state" note)))
2793 (defgroup org-priorities nil
2794 "Priorities in Org-mode."
2795 :tag "Org Priorities"
2796 :group 'org-todo)
2798 (defcustom org-enable-priority-commands t
2799 "Non-nil means priority commands are active.
2800 When nil, these commands will be disabled, so that you never accidentally
2801 set a priority."
2802 :group 'org-priorities
2803 :type 'boolean)
2805 (defcustom org-highest-priority ?A
2806 "The highest priority of TODO items. A character like ?A, ?B etc.
2807 Must have a smaller ASCII number than `org-lowest-priority'."
2808 :group 'org-priorities
2809 :type 'character)
2811 (defcustom org-lowest-priority ?C
2812 "The lowest priority of TODO items. A character like ?A, ?B etc.
2813 Must have a larger ASCII number than `org-highest-priority'."
2814 :group 'org-priorities
2815 :type 'character)
2817 (defcustom org-default-priority ?B
2818 "The default priority of TODO items.
2819 This is the priority an item gets if no explicit priority is given.
2820 When starting to cycle on an empty priority the first step in the cycle
2821 depends on `org-priority-start-cycle-with-default'. The resulting first
2822 step priority must not exceed the range from `org-highest-priority' to
2823 `org-lowest-priority' which means that `org-default-priority' has to be
2824 in this range exclusive or inclusive the range boundaries. Else the
2825 first step refuses to set the default and the second will fall back
2826 to (depending on the command used) the highest or lowest priority."
2827 :group 'org-priorities
2828 :type 'character)
2830 (defcustom org-priority-start-cycle-with-default t
2831 "Non-nil means start with default priority when starting to cycle.
2832 When this is nil, the first step in the cycle will be (depending on the
2833 command used) one higher or lower than the default priority.
2834 See also `org-default-priority'."
2835 :group 'org-priorities
2836 :type 'boolean)
2838 (defcustom org-get-priority-function nil
2839 "Function to extract the priority from a string.
2840 The string is normally the headline. If this is nil Org computes the
2841 priority from the priority cookie like [#A] in the headline. It returns
2842 an integer, increasing by 1000 for each priority level.
2843 The user can set a different function here, which should take a string
2844 as an argument and return the numeric priority."
2845 :group 'org-priorities
2846 :version "24.1"
2847 :type '(choice
2848 (const nil)
2849 (function)))
2851 (defgroup org-time nil
2852 "Options concerning time stamps and deadlines in Org-mode."
2853 :tag "Org Time"
2854 :group 'org)
2856 (defcustom org-insert-labeled-timestamps-at-point nil
2857 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2858 When nil, these labeled time stamps are forces into the second line of an
2859 entry, just after the headline. When scheduling from the global TODO list,
2860 the time stamp will always be forced into the second line."
2861 :group 'org-time
2862 :type 'boolean)
2864 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2865 "Formats for `format-time-string' which are used for time stamps.
2866 It is not recommended to change this constant.")
2868 (defcustom org-time-stamp-rounding-minutes '(0 5)
2869 "Number of minutes to round time stamps to.
2870 These are two values, the first applies when first creating a time stamp.
2871 The second applies when changing it with the commands `S-up' and `S-down'.
2872 When changing the time stamp, this means that it will change in steps
2873 of N minutes, as given by the second value.
2875 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2876 numbers should be factors of 60, so for example 5, 10, 15.
2878 When this is larger than 1, you can still force an exact time stamp by using
2879 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2880 and by using a prefix arg to `S-up/down' to specify the exact number
2881 of minutes to shift."
2882 :group 'org-time
2883 :get #'(lambda (var) ; Make sure both elements are there
2884 (if (integerp (default-value var))
2885 (list (default-value var) 5)
2886 (default-value var)))
2887 :type '(list
2888 (integer :tag "when inserting times")
2889 (integer :tag "when modifying times")))
2891 ;; Normalize old customizations of this variable.
2892 (when (integerp org-time-stamp-rounding-minutes)
2893 (setq org-time-stamp-rounding-minutes
2894 (list org-time-stamp-rounding-minutes
2895 org-time-stamp-rounding-minutes)))
2897 (defcustom org-display-custom-times nil
2898 "Non-nil means overlay custom formats over all time stamps.
2899 The formats are defined through the variable `org-time-stamp-custom-formats'.
2900 To turn this on on a per-file basis, insert anywhere in the file:
2901 #+STARTUP: customtime"
2902 :group 'org-time
2903 :set 'set-default
2904 :type 'sexp)
2905 (make-variable-buffer-local 'org-display-custom-times)
2907 (defcustom org-time-stamp-custom-formats
2908 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2909 "Custom formats for time stamps. See `format-time-string' for the syntax.
2910 These are overlaid over the default ISO format if the variable
2911 `org-display-custom-times' is set. Time like %H:%M should be at the
2912 end of the second format. The custom formats are also honored by export
2913 commands, if custom time display is turned on at the time of export."
2914 :group 'org-time
2915 :type 'sexp)
2917 (defun org-time-stamp-format (&optional long inactive)
2918 "Get the right format for a time string."
2919 (let ((f (if long (cdr org-time-stamp-formats)
2920 (car org-time-stamp-formats))))
2921 (if inactive
2922 (concat "[" (substring f 1 -1) "]")
2923 f)))
2925 (defcustom org-time-clocksum-format
2926 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2927 "The format string used when creating CLOCKSUM lines.
2928 This is also used when Org mode generates a time duration.
2930 The value can be a single format string containing two
2931 %-sequences, which will be filled with the number of hours and
2932 minutes in that order.
2934 Alternatively, the value can be a plist associating any of the
2935 keys :years, :months, :weeks, :days, :hours or :minutes with
2936 format strings. The time duration is formatted using only the
2937 time components that are needed and concatenating the results.
2938 If a time unit in absent, it falls back to the next smallest
2939 unit.
2941 The keys :require-years, :require-months, :require-days,
2942 :require-weeks, :require-hours, :require-minutes are also
2943 meaningful. A non-nil value for these keys indicates that the
2944 corresponding time component should always be included, even if
2945 its value is 0.
2948 For example,
2950 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2951 :require-minutes t)
2953 means durations longer than a day will be expressed in days,
2954 hours and minutes, and durations less than a day will always be
2955 expressed in hours and minutes (even for durations less than an
2956 hour).
2958 The value
2960 \(:days \"%dd\" :minutes \"%dm\")
2962 means durations longer than a day will be expressed in days and
2963 minutes, and durations less than a day will be expressed entirely
2964 in minutes (even for durations longer than an hour)."
2965 :group 'org-time
2966 :group 'org-clock
2967 :version "24.4"
2968 :package-version '(Org . "8.0")
2969 :type '(choice (string :tag "Format string")
2970 (set :tag "Plist"
2971 (group :inline t (const :tag "Years" :years)
2972 (string :tag "Format string"))
2973 (group :inline t
2974 (const :tag "Always show years" :require-years)
2975 (const t))
2976 (group :inline t (const :tag "Months" :months)
2977 (string :tag "Format string"))
2978 (group :inline t
2979 (const :tag "Always show months" :require-months)
2980 (const t))
2981 (group :inline t (const :tag "Weeks" :weeks)
2982 (string :tag "Format string"))
2983 (group :inline t
2984 (const :tag "Always show weeks" :require-weeks)
2985 (const t))
2986 (group :inline t (const :tag "Days" :days)
2987 (string :tag "Format string"))
2988 (group :inline t
2989 (const :tag "Always show days" :require-days)
2990 (const t))
2991 (group :inline t (const :tag "Hours" :hours)
2992 (string :tag "Format string"))
2993 (group :inline t
2994 (const :tag "Always show hours" :require-hours)
2995 (const t))
2996 (group :inline t (const :tag "Minutes" :minutes)
2997 (string :tag "Format string"))
2998 (group :inline t
2999 (const :tag "Always show minutes" :require-minutes)
3000 (const t)))))
3002 (defcustom org-time-clocksum-use-fractional nil
3003 "When non-nil, \\[org-clock-display] uses fractional times.
3004 See `org-time-clocksum-format' for more on time clock formats."
3005 :group 'org-time
3006 :group 'org-clock
3007 :version "24.3"
3008 :type 'boolean)
3010 (defcustom org-time-clocksum-use-effort-durations nil
3011 "When non-nil, \\[org-clock-display] uses effort durations.
3012 E.g. by default, one day is considered to be a 8 hours effort,
3013 so a task that has been clocked for 16 hours will be displayed
3014 as during 2 days in the clock display or in the clocktable.
3016 See `org-effort-durations' on how to set effort durations
3017 and `org-time-clocksum-format' for more on time clock formats."
3018 :group 'org-time
3019 :group 'org-clock
3020 :version "24.4"
3021 :package-version '(Org . "8.0")
3022 :type 'boolean)
3024 (defcustom org-time-clocksum-fractional-format "%.2f"
3025 "The format string used when creating CLOCKSUM lines,
3026 or when Org mode generates a time duration, if
3027 `org-time-clocksum-use-fractional' is enabled.
3029 The value can be a single format string containing one
3030 %-sequence, which will be filled with the number of hours as
3031 a float.
3033 Alternatively, the value can be a plist associating any of the
3034 keys :years, :months, :weeks, :days, :hours or :minutes with
3035 a format string. The time duration is formatted using the
3036 largest time unit which gives a non-zero integer part. If all
3037 specified formats have zero integer part, the smallest time unit
3038 is used."
3039 :group 'org-time
3040 :type '(choice (string :tag "Format string")
3041 (set (group :inline t (const :tag "Years" :years)
3042 (string :tag "Format string"))
3043 (group :inline t (const :tag "Months" :months)
3044 (string :tag "Format string"))
3045 (group :inline t (const :tag "Weeks" :weeks)
3046 (string :tag "Format string"))
3047 (group :inline t (const :tag "Days" :days)
3048 (string :tag "Format string"))
3049 (group :inline t (const :tag "Hours" :hours)
3050 (string :tag "Format string"))
3051 (group :inline t (const :tag "Minutes" :minutes)
3052 (string :tag "Format string")))))
3054 (defcustom org-deadline-warning-days 14
3055 "Number of days before expiration during which a deadline becomes active.
3056 This variable governs the display in sparse trees and in the agenda.
3057 When 0 or negative, it means use this number (the absolute value of it)
3058 even if a deadline has a different individual lead time specified.
3060 Custom commands can set this variable in the options section."
3061 :group 'org-time
3062 :group 'org-agenda-daily/weekly
3063 :type 'integer)
3065 (defcustom org-scheduled-delay-days 0
3066 "Number of days before a scheduled item becomes active.
3067 This variable governs the display in sparse trees and in the agenda.
3068 The default value (i.e. 0) means: don't delay scheduled item.
3069 When negative, it means use this number (the absolute value of it)
3070 even if a scheduled item has a different individual delay time
3071 specified.
3073 Custom commands can set this variable in the options section."
3074 :group 'org-time
3075 :group 'org-agenda-daily/weekly
3076 :version "24.4"
3077 :package-version '(Org . "8.0")
3078 :type 'integer)
3080 (defcustom org-read-date-prefer-future t
3081 "Non-nil means assume future for incomplete date input from user.
3082 This affects the following situations:
3083 1. The user gives a month but not a year.
3084 For example, if it is April and you enter \"feb 2\", this will be read
3085 as Feb 2, *next* year. \"May 5\", however, will be this year.
3086 2. The user gives a day, but no month.
3087 For example, if today is the 15th, and you enter \"3\", Org-mode will
3088 read this as the third of *next* month. However, if you enter \"17\",
3089 it will be considered as *this* month.
3091 If you set this variable to the symbol `time', then also the following
3092 will work:
3094 3. If the user gives a time.
3095 If the time is before now, it will be interpreted as tomorrow.
3097 Currently none of this works for ISO week specifications.
3099 When this option is nil, the current day, month and year will always be
3100 used as defaults.
3102 See also `org-agenda-jump-prefer-future'."
3103 :group 'org-time
3104 :type '(choice
3105 (const :tag "Never" nil)
3106 (const :tag "Check month and day" t)
3107 (const :tag "Check month, day, and time" time)))
3109 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3110 "Should the agenda jump command prefer the future for incomplete dates?
3111 The default is to do the same as configured in `org-read-date-prefer-future'.
3112 But you can also set a deviating value here.
3113 This may t or nil, or the symbol `org-read-date-prefer-future'."
3114 :group 'org-agenda
3115 :group 'org-time
3116 :version "24.1"
3117 :type '(choice
3118 (const :tag "Use org-read-date-prefer-future"
3119 org-read-date-prefer-future)
3120 (const :tag "Never" nil)
3121 (const :tag "Always" t)))
3123 (defcustom org-read-date-force-compatible-dates t
3124 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3126 Depending on the system Emacs is running on, certain dates cannot
3127 be represented with the type used internally to represent time.
3128 Dates between 1970-1-1 and 2038-1-1 can always be represented
3129 correctly. Some systems allow for earlier dates, some for later,
3130 some for both. One way to find out it to insert any date into an
3131 Org buffer, putting the cursor on the year and hitting S-up and
3132 S-down to test the range.
3134 When this variable is set to t, the date/time prompt will not let
3135 you specify dates outside the 1970-2037 range, so it is certain that
3136 these dates will work in whatever version of Emacs you are
3137 running, and also that you can move a file from one Emacs implementation
3138 to another. WHenever Org is forcing the year for you, it will display
3139 a message and beep.
3141 When this variable is nil, Org will check if the date is
3142 representable in the specific Emacs implementation you are using.
3143 If not, it will force a year, usually the current year, and beep
3144 to remind you. Currently this setting is not recommended because
3145 the likelihood that you will open your Org files in an Emacs that
3146 has limited date range is not negligible.
3148 A workaround for this problem is to use diary sexp dates for time
3149 stamps outside of this range."
3150 :group 'org-time
3151 :version "24.1"
3152 :type 'boolean)
3154 (defcustom org-read-date-display-live t
3155 "Non-nil means display current interpretation of date prompt live.
3156 This display will be in an overlay, in the minibuffer."
3157 :group 'org-time
3158 :type 'boolean)
3160 (defcustom org-read-date-popup-calendar t
3161 "Non-nil means pop up a calendar when prompting for a date.
3162 In the calendar, the date can be selected with mouse-1. However, the
3163 minibuffer will also be active, and you can simply enter the date as well.
3164 When nil, only the minibuffer will be available."
3165 :group 'org-time
3166 :type 'boolean)
3167 (org-defvaralias 'org-popup-calendar-for-date-prompt
3168 'org-read-date-popup-calendar)
3170 (make-obsolete-variable
3171 'org-read-date-minibuffer-setup-hook
3172 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3173 (defcustom org-read-date-minibuffer-setup-hook nil
3174 "Hook to be used to set up keys for the date/time interface.
3175 Add key definitions to `minibuffer-local-map', which will be a
3176 temporary copy.
3178 WARNING: This option is obsolete, you should use
3179 `org-read-date-minibuffer-local-map' to set up keys."
3180 :group 'org-time
3181 :type 'hook)
3183 (defcustom org-extend-today-until 0
3184 "The hour when your day really ends. Must be an integer.
3185 This has influence for the following applications:
3186 - When switching the agenda to \"today\". It it is still earlier than
3187 the time given here, the day recognized as TODAY is actually yesterday.
3188 - When a date is read from the user and it is still before the time given
3189 here, the current date and time will be assumed to be yesterday, 23:59.
3190 Also, timestamps inserted in capture templates follow this rule.
3192 IMPORTANT: This is a feature whose implementation is and likely will
3193 remain incomplete. Really, it is only here because past midnight seems to
3194 be the favorite working time of John Wiegley :-)"
3195 :group 'org-time
3196 :type 'integer)
3198 (defcustom org-use-effective-time nil
3199 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3200 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3201 \"effective time\" of any timestamps between midnight and 8am will be
3202 23:59 of the previous day."
3203 :group 'org-time
3204 :version "24.1"
3205 :type 'boolean)
3207 (defcustom org-use-last-clock-out-time-as-effective-time nil
3208 "When non-nil, use the last clock out time for `org-todo'.
3209 Note that this option has precedence over the combined use of
3210 `org-use-effective-time' and `org-extend-today-until'."
3211 :group 'org-time
3212 :version "24.4"
3213 :package-version '(Org . "8.0")
3214 :type 'boolean)
3216 (defcustom org-edit-timestamp-down-means-later nil
3217 "Non-nil means S-down will increase the time in a time stamp.
3218 When nil, S-up will increase."
3219 :group 'org-time
3220 :type 'boolean)
3222 (defcustom org-calendar-follow-timestamp-change t
3223 "Non-nil means make the calendar window follow timestamp changes.
3224 When a timestamp is modified and the calendar window is visible, it will be
3225 moved to the new date."
3226 :group 'org-time
3227 :type 'boolean)
3229 (defgroup org-tags nil
3230 "Options concerning tags in Org-mode."
3231 :tag "Org Tags"
3232 :group 'org)
3234 (defcustom org-tag-alist nil
3235 "List of tags allowed in Org-mode files.
3236 When this list is nil, Org-mode will base TAG input on what is already in the
3237 buffer.
3238 The value of this variable is an alist, the car of each entry must be a
3239 keyword as a string, the cdr may be a character that is used to select
3240 that tag through the fast-tag-selection interface.
3241 See the manual for details."
3242 :group 'org-tags
3243 :type '(repeat
3244 (choice
3245 (cons (string :tag "Tag name")
3246 (character :tag "Access char"))
3247 (list :tag "Start radio group"
3248 (const :startgroup)
3249 (option (string :tag "Group description")))
3250 (list :tag "Group tags delimiter"
3251 (const :grouptags))
3252 (list :tag "End radio group"
3253 (const :endgroup)
3254 (option (string :tag "Group description")))
3255 (const :tag "New line" (:newline)))))
3257 (defcustom org-tag-persistent-alist nil
3258 "List of tags that will always appear in all Org-mode files.
3259 This is in addition to any in buffer settings or customizations
3260 of `org-tag-alist'.
3261 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3262 The value of this variable is an alist, the car of each entry must be a
3263 keyword as a string, the cdr may be a character that is used to select
3264 that tag through the fast-tag-selection interface.
3265 See the manual for details.
3266 To disable these tags on a per-file basis, insert anywhere in the file:
3267 #+STARTUP: noptag"
3268 :group 'org-tags
3269 :type '(repeat
3270 (choice
3271 (cons (string :tag "Tag name")
3272 (character :tag "Access char"))
3273 (const :tag "Start radio group" (:startgroup))
3274 (const :tag "Group tags delimiter" (:grouptags))
3275 (const :tag "End radio group" (:endgroup))
3276 (const :tag "New line" (:newline)))))
3278 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3279 "If non-nil, always offer completion for all tags of all agenda files.
3280 Instead of customizing this variable directly, you might want to
3281 set it locally for capture buffers, because there no list of
3282 tags in that file can be created dynamically (there are none).
3284 (add-hook 'org-capture-mode-hook
3285 (lambda ()
3286 (set (make-local-variable
3287 'org-complete-tags-always-offer-all-agenda-tags)
3288 t)))"
3289 :group 'org-tags
3290 :version "24.1"
3291 :type 'boolean)
3293 (defvar org-file-tags nil
3294 "List of tags that can be inherited by all entries in the file.
3295 The tags will be inherited if the variable `org-use-tag-inheritance'
3296 says they should be.
3297 This variable is populated from #+FILETAGS lines.")
3299 (defcustom org-use-fast-tag-selection 'auto
3300 "Non-nil means use fast tag selection scheme.
3301 This is a special interface to select and deselect tags with single keys.
3302 When nil, fast selection is never used.
3303 When the symbol `auto', fast selection is used if and only if selection
3304 characters for tags have been configured, either through the variable
3305 `org-tag-alist' or through a #+TAGS line in the buffer.
3306 When t, fast selection is always used and selection keys are assigned
3307 automatically if necessary."
3308 :group 'org-tags
3309 :type '(choice
3310 (const :tag "Always" t)
3311 (const :tag "Never" nil)
3312 (const :tag "When selection characters are configured" auto)))
3314 (defcustom org-fast-tag-selection-single-key nil
3315 "Non-nil means fast tag selection exits after first change.
3316 When nil, you have to press RET to exit it.
3317 During fast tag selection, you can toggle this flag with `C-c'.
3318 This variable can also have the value `expert'. In this case, the window
3319 displaying the tags menu is not even shown, until you press C-c again."
3320 :group 'org-tags
3321 :type '(choice
3322 (const :tag "No" nil)
3323 (const :tag "Yes" t)
3324 (const :tag "Expert" expert)))
3326 (defvar org-fast-tag-selection-include-todo nil
3327 "Non-nil means fast tags selection interface will also offer TODO states.
3328 This is an undocumented feature, you should not rely on it.")
3330 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3331 "The column to which tags should be indented in a headline.
3332 If this number is positive, it specifies the column. If it is negative,
3333 it means that the tags should be flushright to that column. For example,
3334 -80 works well for a normal 80 character screen.
3335 When 0, place tags directly after headline text, with only one space in
3336 between."
3337 :group 'org-tags
3338 :type 'integer)
3340 (defcustom org-auto-align-tags t
3341 "Non-nil keeps tags aligned when modifying headlines.
3342 Some operations (i.e. demoting) change the length of a headline and
3343 therefore shift the tags around. With this option turned on, after
3344 each such operation the tags are again aligned to `org-tags-column'."
3345 :group 'org-tags
3346 :type 'boolean)
3348 (defcustom org-use-tag-inheritance t
3349 "Non-nil means tags in levels apply also for sublevels.
3350 When nil, only the tags directly given in a specific line apply there.
3351 This may also be a list of tags that should be inherited, or a regexp that
3352 matches tags that should be inherited. Additional control is possible
3353 with the variable `org-tags-exclude-from-inheritance' which gives an
3354 explicit list of tags to be excluded from inheritance, even if the value of
3355 `org-use-tag-inheritance' would select it for inheritance.
3357 If this option is t, a match early-on in a tree can lead to a large
3358 number of matches in the subtree when constructing the agenda or creating
3359 a sparse tree. If you only want to see the first match in a tree during
3360 a search, check out the variable `org-tags-match-list-sublevels'."
3361 :group 'org-tags
3362 :type '(choice
3363 (const :tag "Not" nil)
3364 (const :tag "Always" t)
3365 (repeat :tag "Specific tags" (string :tag "Tag"))
3366 (regexp :tag "Tags matched by regexp")))
3368 (defcustom org-tags-exclude-from-inheritance nil
3369 "List of tags that should never be inherited.
3370 This is a way to exclude a few tags from inheritance. For way to do
3371 the opposite, to actively allow inheritance for selected tags,
3372 see the variable `org-use-tag-inheritance'."
3373 :group 'org-tags
3374 :type '(repeat (string :tag "Tag")))
3376 (defun org-tag-inherit-p (tag)
3377 "Check if TAG is one that should be inherited."
3378 (cond
3379 ((member tag org-tags-exclude-from-inheritance) nil)
3380 ((eq org-use-tag-inheritance t) t)
3381 ((not org-use-tag-inheritance) nil)
3382 ((stringp org-use-tag-inheritance)
3383 (string-match org-use-tag-inheritance tag))
3384 ((listp org-use-tag-inheritance)
3385 (member tag org-use-tag-inheritance))
3386 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3388 (defcustom org-tags-match-list-sublevels t
3389 "Non-nil means list also sublevels of headlines matching a search.
3390 This variable applies to tags/property searches, and also to stuck
3391 projects because this search is based on a tags match as well.
3393 When set to the symbol `indented', sublevels are indented with
3394 leading dots.
3396 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3397 the sublevels of a headline matching a tag search often also match
3398 the same search. Listing all of them can create very long lists.
3399 Setting this variable to nil causes subtrees of a match to be skipped.
3401 This variable is semi-obsolete and probably should always be true. It
3402 is better to limit inheritance to certain tags using the variables
3403 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3404 :group 'org-tags
3405 :type '(choice
3406 (const :tag "No, don't list them" nil)
3407 (const :tag "Yes, do list them" t)
3408 (const :tag "List them, indented with leading dots" indented)))
3410 (defcustom org-tags-sort-function nil
3411 "When set, tags are sorted using this function as a comparator."
3412 :group 'org-tags
3413 :type '(choice
3414 (const :tag "No sorting" nil)
3415 (const :tag "Alphabetical" string<)
3416 (const :tag "Reverse alphabetical" string>)
3417 (function :tag "Custom function" nil)))
3419 (defvar org-tags-history nil
3420 "History of minibuffer reads for tags.")
3421 (defvar org-last-tags-completion-table nil
3422 "The last used completion table for tags.")
3423 (defvar org-after-tags-change-hook nil
3424 "Hook that is run after the tags in a line have changed.")
3426 (defgroup org-properties nil
3427 "Options concerning properties in Org-mode."
3428 :tag "Org Properties"
3429 :group 'org)
3431 (defcustom org-property-format "%-10s %s"
3432 "How property key/value pairs should be formatted by `indent-line'.
3433 When `indent-line' hits a property definition, it will format the line
3434 according to this format, mainly to make sure that the values are
3435 lined-up with respect to each other."
3436 :group 'org-properties
3437 :type 'string)
3439 (defcustom org-properties-postprocess-alist nil
3440 "Alist of properties and functions to adjust inserted values.
3441 Elements of this alist must be of the form
3443 ([string] [function])
3445 where [string] must be a property name and [function] must be a
3446 lambda expression: this lambda expression must take one argument,
3447 the value to adjust, and return the new value as a string.
3449 For example, this element will allow the property \"Remaining\"
3450 to be updated wrt the relation between the \"Effort\" property
3451 and the clock summary:
3453 ((\"Remaining\" (lambda(value)
3454 (let ((clocksum (org-clock-sum-current-item))
3455 (effort (org-duration-string-to-minutes
3456 (org-entry-get (point) \"Effort\"))))
3457 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3458 :group 'org-properties
3459 :version "24.1"
3460 :type '(alist :key-type (string :tag "Property")
3461 :value-type (function :tag "Function")))
3463 (defcustom org-use-property-inheritance nil
3464 "Non-nil means properties apply also for sublevels.
3466 This setting is chiefly used during property searches. Turning it on can
3467 cause significant overhead when doing a search, which is why it is not
3468 on by default.
3470 When nil, only the properties directly given in the current entry count.
3471 When t, every property is inherited. The value may also be a list of
3472 properties that should have inheritance, or a regular expression matching
3473 properties that should be inherited.
3475 However, note that some special properties use inheritance under special
3476 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3477 and the properties ending in \"_ALL\" when they are used as descriptor
3478 for valid values of a property.
3480 Note for programmers:
3481 When querying an entry with `org-entry-get', you can control if inheritance
3482 should be used. By default, `org-entry-get' looks only at the local
3483 properties. You can request inheritance by setting the inherit argument
3484 to t (to force inheritance) or to `selective' (to respect the setting
3485 in this variable)."
3486 :group 'org-properties
3487 :type '(choice
3488 (const :tag "Not" nil)
3489 (const :tag "Always" t)
3490 (repeat :tag "Specific properties" (string :tag "Property"))
3491 (regexp :tag "Properties matched by regexp")))
3493 (defun org-property-inherit-p (property)
3494 "Check if PROPERTY is one that should be inherited."
3495 (cond
3496 ((eq org-use-property-inheritance t) t)
3497 ((not org-use-property-inheritance) nil)
3498 ((stringp org-use-property-inheritance)
3499 (string-match org-use-property-inheritance property))
3500 ((listp org-use-property-inheritance)
3501 (member property org-use-property-inheritance))
3502 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3504 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3505 "The default column format, if no other format has been defined.
3506 This variable can be set on the per-file basis by inserting a line
3508 #+COLUMNS: %25ITEM ....."
3509 :group 'org-properties
3510 :type 'string)
3512 (defcustom org-columns-ellipses ".."
3513 "The ellipses to be used when a field in column view is truncated.
3514 When this is the empty string, as many characters as possible are shown,
3515 but then there will be no visual indication that the field has been truncated.
3516 When this is a string of length N, the last N characters of a truncated
3517 field are replaced by this string. If the column is narrower than the
3518 ellipses string, only part of the ellipses string will be shown."
3519 :group 'org-properties
3520 :type 'string)
3522 (defcustom org-columns-modify-value-for-display-function nil
3523 "Function that modifies values for display in column view.
3524 For example, it can be used to cut out a certain part from a time stamp.
3525 The function must take 2 arguments:
3527 column-title The title of the column (*not* the property name)
3528 value The value that should be modified.
3530 The function should return the value that should be displayed,
3531 or nil if the normal value should be used."
3532 :group 'org-properties
3533 :type '(choice (const nil) (function)))
3535 (defcustom org-effort-property "Effort"
3536 "The property that is being used to keep track of effort estimates.
3537 Effort estimates given in this property need to have the format H:MM."
3538 :group 'org-properties
3539 :group 'org-progress
3540 :type '(string :tag "Property"))
3542 (defconst org-global-properties-fixed
3543 '(("VISIBILITY_ALL" . "folded children content all")
3544 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3545 "List of property/value pairs that can be inherited by any entry.
3547 These are fixed values, for the preset properties. The user variable
3548 that can be used to add to this list is `org-global-properties'.
3550 The entries in this list are cons cells where the car is a property
3551 name and cdr is a string with the value. If the value represents
3552 multiple items like an \"_ALL\" property, separate the items by
3553 spaces.")
3555 (defcustom org-global-properties nil
3556 "List of property/value pairs that can be inherited by any entry.
3558 This list will be combined with the constant `org-global-properties-fixed'.
3560 The entries in this list are cons cells where the car is a property
3561 name and cdr is a string with the value.
3563 You can set buffer-local values for the same purpose in the variable
3564 `org-file-properties' this by adding lines like
3566 #+PROPERTY: NAME VALUE"
3567 :group 'org-properties
3568 :type '(repeat
3569 (cons (string :tag "Property")
3570 (string :tag "Value"))))
3572 (defvar org-file-properties nil
3573 "List of property/value pairs that can be inherited by any entry.
3574 Valid for the current buffer.
3575 This variable is populated from #+PROPERTY lines.")
3576 (make-variable-buffer-local 'org-file-properties)
3578 (defgroup org-agenda nil
3579 "Options concerning agenda views in Org-mode."
3580 :tag "Org Agenda"
3581 :group 'org)
3583 (defvar org-category nil
3584 "Variable used by org files to set a category for agenda display.
3585 Such files should use a file variable to set it, for example
3587 # -*- mode: org; org-category: \"ELisp\"
3589 or contain a special line
3591 #+CATEGORY: ELisp
3593 If the file does not specify a category, then file's base name
3594 is used instead.")
3595 (make-variable-buffer-local 'org-category)
3596 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3598 (defcustom org-agenda-files nil
3599 "The files to be used for agenda display.
3600 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3601 \\[org-remove-file]. You can also use customize to edit the list.
3603 If an entry is a directory, all files in that directory that are matched by
3604 `org-agenda-file-regexp' will be part of the file list.
3606 If the value of the variable is not a list but a single file name, then
3607 the list of agenda files is actually stored and maintained in that file, one
3608 agenda file per line. In this file paths can be given relative to
3609 `org-directory'. Tilde expansion and environment variable substitution
3610 are also made."
3611 :group 'org-agenda
3612 :type '(choice
3613 (repeat :tag "List of files and directories" file)
3614 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3616 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3617 "Regular expression to match files for `org-agenda-files'.
3618 If any element in the list in that variable contains a directory instead
3619 of a normal file, all files in that directory that are matched by this
3620 regular expression will be included."
3621 :group 'org-agenda
3622 :type 'regexp)
3624 (defcustom org-agenda-text-search-extra-files nil
3625 "List of extra files to be searched by text search commands.
3626 These files will be searched in addition to the agenda files by the
3627 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3628 Note that these files will only be searched for text search commands,
3629 not for the other agenda views like todo lists, tag searches or the weekly
3630 agenda. This variable is intended to list notes and possibly archive files
3631 that should also be searched by these two commands.
3632 In fact, if the first element in the list is the symbol `agenda-archives',
3633 then all archive files of all agenda files will be added to the search
3634 scope."
3635 :group 'org-agenda
3636 :type '(set :greedy t
3637 (const :tag "Agenda Archives" agenda-archives)
3638 (repeat :inline t (file))))
3640 (org-defvaralias 'org-agenda-multi-occur-extra-files
3641 'org-agenda-text-search-extra-files)
3643 (defcustom org-agenda-skip-unavailable-files nil
3644 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3645 A nil value means to remove them, after a query, from the list."
3646 :group 'org-agenda
3647 :type 'boolean)
3649 (defcustom org-calendar-to-agenda-key [?c]
3650 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3651 The command `org-calendar-goto-agenda' will be bound to this key. The
3652 default is the character `c' because then `c' can be used to switch back and
3653 forth between agenda and calendar."
3654 :group 'org-agenda
3655 :type 'sexp)
3657 (defcustom org-calendar-insert-diary-entry-key [?i]
3658 "The key to be installed in `calendar-mode-map' for adding diary entries.
3659 This option is irrelevant until `org-agenda-diary-file' has been configured
3660 to point to an Org-mode file. When that is the case, the command
3661 `org-agenda-diary-entry' will be bound to the key given here, by default
3662 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3663 if you want to continue doing this, you need to change this to a different
3664 key."
3665 :group 'org-agenda
3666 :type 'sexp)
3668 (defcustom org-agenda-diary-file 'diary-file
3669 "File to which to add new entries with the `i' key in agenda and calendar.
3670 When this is the symbol `diary-file', the functionality in the Emacs
3671 calendar will be used to add entries to the `diary-file'. But when this
3672 points to a file, `org-agenda-diary-entry' will be used instead."
3673 :group 'org-agenda
3674 :type '(choice
3675 (const :tag "The standard Emacs diary file" diary-file)
3676 (file :tag "Special Org file diary entries")))
3678 (eval-after-load "calendar"
3679 '(progn
3680 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3681 'org-calendar-goto-agenda)
3682 (add-hook 'calendar-mode-hook
3683 (lambda ()
3684 (unless (eq org-agenda-diary-file 'diary-file)
3685 (define-key calendar-mode-map
3686 org-calendar-insert-diary-entry-key
3687 'org-agenda-diary-entry))))))
3689 (defgroup org-latex nil
3690 "Options for embedding LaTeX code into Org-mode."
3691 :tag "Org LaTeX"
3692 :group 'org)
3694 (defcustom org-format-latex-options
3695 '(:foreground default :background default :scale 1.0
3696 :html-foreground "Black" :html-background "Transparent"
3697 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3698 "Options for creating images from LaTeX fragments.
3699 This is a property list with the following properties:
3700 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3701 `default' means use the foreground of the default face.
3702 `auto' means use the foreground from the text face.
3703 :background the background color, or \"Transparent\".
3704 `default' means use the background of the default face.
3705 `auto' means use the background from the text face.
3706 :scale a scaling factor for the size of the images, to get more pixels
3707 :html-foreground, :html-background, :html-scale
3708 the same numbers for HTML export.
3709 :matchers a list indicating which matchers should be used to
3710 find LaTeX fragments. Valid members of this list are:
3711 \"begin\" find environments
3712 \"$1\" find single characters surrounded by $.$
3713 \"$\" find math expressions surrounded by $...$
3714 \"$$\" find math expressions surrounded by $$....$$
3715 \"\\(\" find math expressions surrounded by \\(...\\)
3716 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3717 :group 'org-latex
3718 :type 'plist)
3720 (defcustom org-format-latex-signal-error t
3721 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3722 When nil, just push out a message."
3723 :group 'org-latex
3724 :version "24.1"
3725 :type 'boolean)
3727 (defcustom org-latex-to-mathml-jar-file nil
3728 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3729 Use this to specify additional executable file say a jar file.
3731 When using MathToWeb as the converter, specify the full-path to
3732 your mathtoweb.jar file."
3733 :group 'org-latex
3734 :version "24.1"
3735 :type '(choice
3736 (const :tag "None" nil)
3737 (file :tag "JAR file" :must-match t)))
3739 (defcustom org-latex-to-mathml-convert-command nil
3740 "Command to convert LaTeX fragments to MathML.
3741 Replace format-specifiers in the command as noted below and use
3742 `shell-command' to convert LaTeX to MathML.
3743 %j: Executable file in fully expanded form as specified by
3744 `org-latex-to-mathml-jar-file'.
3745 %I: Input LaTeX file in fully expanded form
3746 %o: Output MathML file
3747 This command is used by `org-create-math-formula'.
3749 When using MathToWeb as the converter, set this to
3750 \"java -jar %j -unicode -force -df %o %I\"."
3751 :group 'org-latex
3752 :version "24.1"
3753 :type '(choice
3754 (const :tag "None" nil)
3755 (string :tag "\nShell command")))
3757 (defcustom org-latex-create-formula-image-program 'dvipng
3758 "Program to convert LaTeX fragments with.
3760 dvipng Process the LaTeX fragments to dvi file, then convert
3761 dvi files to png files using dvipng.
3762 This will also include processing of non-math environments.
3763 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3764 to convert pdf files to png files"
3765 :group 'org-latex
3766 :version "24.1"
3767 :type '(choice
3768 (const :tag "dvipng" dvipng)
3769 (const :tag "imagemagick" imagemagick)))
3771 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3772 "Path to store latex preview images.
3773 A relative path here creates many directories relative to the
3774 processed org files paths. An absolute path puts all preview
3775 images at the same place."
3776 :group 'org-latex
3777 :version "24.3"
3778 :type 'string)
3780 (defun org-format-latex-mathml-available-p ()
3781 "Return t if `org-latex-to-mathml-convert-command' is usable."
3782 (save-match-data
3783 (when (and (boundp 'org-latex-to-mathml-convert-command)
3784 org-latex-to-mathml-convert-command)
3785 (let ((executable (car (split-string
3786 org-latex-to-mathml-convert-command))))
3787 (when (executable-find executable)
3788 (if (string-match
3789 "%j" org-latex-to-mathml-convert-command)
3790 (file-readable-p org-latex-to-mathml-jar-file)
3791 t))))))
3793 (defcustom org-format-latex-header "\\documentclass{article}
3794 \\usepackage[usenames]{color}
3795 \[PACKAGES]
3796 \[DEFAULT-PACKAGES]
3797 \\pagestyle{empty} % do not remove
3798 % The settings below are copied from fullpage.sty
3799 \\setlength{\\textwidth}{\\paperwidth}
3800 \\addtolength{\\textwidth}{-3cm}
3801 \\setlength{\\oddsidemargin}{1.5cm}
3802 \\addtolength{\\oddsidemargin}{-2.54cm}
3803 \\setlength{\\evensidemargin}{\\oddsidemargin}
3804 \\setlength{\\textheight}{\\paperheight}
3805 \\addtolength{\\textheight}{-\\headheight}
3806 \\addtolength{\\textheight}{-\\headsep}
3807 \\addtolength{\\textheight}{-\\footskip}
3808 \\addtolength{\\textheight}{-3cm}
3809 \\setlength{\\topmargin}{1.5cm}
3810 \\addtolength{\\topmargin}{-2.54cm}"
3811 "The document header used for processing LaTeX fragments.
3812 It is imperative that this header make sure that no page number
3813 appears on the page. The package defined in the variables
3814 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3815 will either replace the placeholder \"[PACKAGES]\" in this
3816 header, or they will be appended."
3817 :group 'org-latex
3818 :type 'string)
3820 (defun org-set-packages-alist (var val)
3821 "Set the packages alist and make sure it has 3 elements per entry."
3822 (set var (mapcar (lambda (x)
3823 (if (and (consp x) (= (length x) 2))
3824 (list (car x) (nth 1 x) t)
3826 val)))
3828 (defun org-get-packages-alist (var)
3829 "Get the packages alist and make sure it has 3 elements per entry."
3830 (mapcar (lambda (x)
3831 (if (and (consp x) (= (length x) 2))
3832 (list (car x) (nth 1 x) t)
3834 (default-value var)))
3836 (defcustom org-latex-default-packages-alist
3837 '(("AUTO" "inputenc" t)
3838 ("T1" "fontenc" t)
3839 ("" "fixltx2e" nil)
3840 ("" "graphicx" t)
3841 ("" "longtable" nil)
3842 ("" "float" nil)
3843 ("" "wrapfig" nil)
3844 ("" "rotating" nil)
3845 ("normalem" "ulem" t)
3846 ("" "amsmath" t)
3847 ("" "textcomp" t)
3848 ("" "marvosym" t)
3849 ("" "wasysym" t)
3850 ("" "amssymb" t)
3851 ("" "hyperref" nil)
3852 "\\tolerance=1000")
3853 "Alist of default packages to be inserted in the header.
3855 Change this only if one of the packages here causes an
3856 incompatibility with another package you are using.
3858 The packages in this list are needed by one part or another of
3859 Org mode to function properly:
3861 - inputenc, fontenc: for basic font and character selection
3862 - fixltx2e: Important patches of LaTeX itself
3863 - graphicx: for including images
3864 - longtable: For multipage tables
3865 - float, wrapfig: for figure placement
3866 - rotating: for sideways figures and tables
3867 - ulem: for underline and strike-through
3868 - amsmath: for subscript and superscript and math environments
3869 - textcomp, marvosymb, wasysym, amssymb: for various symbols used
3870 for interpreting the entities in `org-entities'. You can skip
3871 some of these packages if you don't use any of their symbols.
3872 - hyperref: for cross references
3874 Therefore you should not modify this variable unless you know
3875 what you are doing. The one reason to change it anyway is that
3876 you might be loading some other package that conflicts with one
3877 of the default packages. Each cell is of the format
3878 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
3879 the package also needs to be included when compiling LaTeX
3880 snippets into images for inclusion into non-LaTeX output."
3881 :group 'org-latex
3882 :group 'org-export-latex
3883 :set 'org-set-packages-alist
3884 :get 'org-get-packages-alist
3885 :version "24.1"
3886 :type '(repeat
3887 (choice
3888 (list :tag "options/package pair"
3889 (string :tag "options")
3890 (string :tag "package")
3891 (boolean :tag "Snippet"))
3892 (string :tag "A line of LaTeX"))))
3894 (defcustom org-latex-packages-alist nil
3895 "Alist of packages to be inserted in every LaTeX header.
3897 These will be inserted after `org-latex-default-packages-alist'.
3898 Each cell is of the format:
3900 \(\"options\" \"package\" snippet-flag)
3902 SNIPPET-FLAG, when t, indicates that this package is also needed
3903 when turning LaTeX snippets into images for inclusion into
3904 non-LaTeX output.
3906 Make sure that you only list packages here which:
3908 - you want in every file
3909 - do not conflict with the setup in `org-format-latex-header'.
3910 - do not conflict with the default packages in
3911 `org-latex-default-packages-alist'."
3912 :group 'org-latex
3913 :group 'org-export-latex
3914 :set 'org-set-packages-alist
3915 :get 'org-get-packages-alist
3916 :type '(repeat
3917 (choice
3918 (list :tag "options/package pair"
3919 (string :tag "options")
3920 (string :tag "package")
3921 (boolean :tag "Snippet"))
3922 (string :tag "A line of LaTeX"))))
3924 (defgroup org-appearance nil
3925 "Settings for Org-mode appearance."
3926 :tag "Org Appearance"
3927 :group 'org)
3929 (defcustom org-level-color-stars-only nil
3930 "Non-nil means fontify only the stars in each headline.
3931 When nil, the entire headline is fontified.
3932 Changing it requires restart of `font-lock-mode' to become effective
3933 also in regions already fontified."
3934 :group 'org-appearance
3935 :type 'boolean)
3937 (defcustom org-hide-leading-stars nil
3938 "Non-nil means hide the first N-1 stars in a headline.
3939 This works by using the face `org-hide' for these stars. This
3940 face is white for a light background, and black for a dark
3941 background. You may have to customize the face `org-hide' to
3942 make this work.
3943 Changing it requires restart of `font-lock-mode' to become effective
3944 also in regions already fontified.
3945 You may also set this on a per-file basis by adding one of the following
3946 lines to the buffer:
3948 #+STARTUP: hidestars
3949 #+STARTUP: showstars"
3950 :group 'org-appearance
3951 :type 'boolean)
3953 (defcustom org-hidden-keywords nil
3954 "List of symbols corresponding to keywords to be hidden the org buffer.
3955 For example, a value '(title) for this list will make the document's title
3956 appear in the buffer without the initial #+TITLE: keyword."
3957 :group 'org-appearance
3958 :version "24.1"
3959 :type '(set (const :tag "#+AUTHOR" author)
3960 (const :tag "#+DATE" date)
3961 (const :tag "#+EMAIL" email)
3962 (const :tag "#+TITLE" title)))
3964 (defcustom org-custom-properties nil
3965 "List of properties (as strings) with a special meaning.
3966 The default use of these custom properties is to let the user
3967 hide them with `org-toggle-custom-properties-visibility'."
3968 :group 'org-properties
3969 :group 'org-appearance
3970 :version "24.3"
3971 :type '(repeat (string :tag "Property Name")))
3973 (defcustom org-fontify-done-headline nil
3974 "Non-nil means change the face of a headline if it is marked DONE.
3975 Normally, only the TODO/DONE keyword indicates the state of a headline.
3976 When this is non-nil, the headline after the keyword is set to the
3977 `org-headline-done' as an additional indication."
3978 :group 'org-appearance
3979 :type 'boolean)
3981 (defcustom org-fontify-emphasized-text t
3982 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3983 Changing this variable requires a restart of Emacs to take effect."
3984 :group 'org-appearance
3985 :type 'boolean)
3987 (defcustom org-fontify-whole-heading-line nil
3988 "Non-nil means fontify the whole line for headings.
3989 This is useful when setting a background color for the
3990 org-level-* faces."
3991 :group 'org-appearance
3992 :type 'boolean)
3994 (defcustom org-highlight-latex-and-related nil
3995 "Non-nil means highlight LaTeX related syntax in the buffer.
3996 When non nil, the value should be a list containing any of the
3997 following symbols:
3998 `latex' Highlight LaTeX snippets and environments.
3999 `script' Highlight subscript and superscript.
4000 `entities' Highlight entities."
4001 :group 'org-appearance
4002 :version "24.4"
4003 :package-version '(Org . "8.0")
4004 :type '(choice
4005 (const :tag "No highlighting" nil)
4006 (set :greedy t :tag "Highlight"
4007 (const :tag "LaTeX snippets and environments" latex)
4008 (const :tag "Subscript and superscript" script)
4009 (const :tag "Entities" entities))))
4011 (defcustom org-hide-emphasis-markers nil
4012 "Non-nil mean font-lock should hide the emphasis marker characters."
4013 :group 'org-appearance
4014 :type 'boolean)
4016 (defcustom org-pretty-entities nil
4017 "Non-nil means show entities as UTF8 characters.
4018 When nil, the \\name form remains in the buffer."
4019 :group 'org-appearance
4020 :version "24.1"
4021 :type 'boolean)
4023 (defcustom org-pretty-entities-include-sub-superscripts t
4024 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4025 :group 'org-appearance
4026 :version "24.1"
4027 :type 'boolean)
4029 (defvar org-emph-re nil
4030 "Regular expression for matching emphasis.
4031 After a match, the match groups contain these elements:
4032 0 The match of the full regular expression, including the characters
4033 before and after the proper match
4034 1 The character before the proper match, or empty at beginning of line
4035 2 The proper match, including the leading and trailing markers
4036 3 The leading marker like * or /, indicating the type of highlighting
4037 4 The text between the emphasis markers, not including the markers
4038 5 The character after the match, empty at the end of a line")
4039 (defvar org-verbatim-re nil
4040 "Regular expression for matching verbatim text.")
4041 (defvar org-emphasis-regexp-components) ; defined just below
4042 (defvar org-emphasis-alist) ; defined just below
4043 (defun org-set-emph-re (var val)
4044 "Set variable and compute the emphasis regular expression."
4045 (set var val)
4046 (when (and (boundp 'org-emphasis-alist)
4047 (boundp 'org-emphasis-regexp-components)
4048 org-emphasis-alist org-emphasis-regexp-components)
4049 (let* ((e org-emphasis-regexp-components)
4050 (pre (car e))
4051 (post (nth 1 e))
4052 (border (nth 2 e))
4053 (body (nth 3 e))
4054 (nl (nth 4 e))
4055 (body1 (concat body "*?"))
4056 (markers (mapconcat 'car org-emphasis-alist ""))
4057 (vmarkers (mapconcat
4058 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4059 org-emphasis-alist "")))
4060 ;; make sure special characters appear at the right position in the class
4061 (if (string-match "\\^" markers)
4062 (setq markers (concat (replace-match "" t t markers) "^")))
4063 (if (string-match "-" markers)
4064 (setq markers (concat (replace-match "" t t markers) "-")))
4065 (if (string-match "\\^" vmarkers)
4066 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4067 (if (string-match "-" vmarkers)
4068 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4069 (if (> nl 0)
4070 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4071 (int-to-string nl) "\\}")))
4072 ;; Make the regexp
4073 (setq org-emph-re
4074 (concat "\\([" pre "]\\|^\\)"
4075 "\\("
4076 "\\([" markers "]\\)"
4077 "\\("
4078 "[^" border "]\\|"
4079 "[^" border "]"
4080 body1
4081 "[^" border "]"
4082 "\\)"
4083 "\\3\\)"
4084 "\\([" post "]\\|$\\)"))
4085 (setq org-verbatim-re
4086 (concat "\\([" pre "]\\|^\\)"
4087 "\\("
4088 "\\([" vmarkers "]\\)"
4089 "\\("
4090 "[^" border "]\\|"
4091 "[^" border "]"
4092 body1
4093 "[^" border "]"
4094 "\\)"
4095 "\\3\\)"
4096 "\\([" post "]\\|$\\)")))))
4098 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4099 ;; set this option proved cumbersome. See this message/thread:
4100 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4101 (defvar org-emphasis-regexp-components
4102 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4103 "Components used to build the regular expression for emphasis.
4104 This is a list with five entries. Terminology: In an emphasis string
4105 like \" *strong word* \", we call the initial space PREMATCH, the final
4106 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4107 and \"trong wor\" is the body. The different components in this variable
4108 specify what is allowed/forbidden in each part:
4110 pre Chars allowed as prematch. Beginning of line will be allowed too.
4111 post Chars allowed as postmatch. End of line will be allowed too.
4112 border The chars *forbidden* as border characters.
4113 body-regexp A regexp like \".\" to match a body character. Don't use
4114 non-shy groups here, and don't allow newline here.
4115 newline The maximum number of newlines allowed in an emphasis exp.
4117 You need to reload Org or to restart Emacs after customizing this.")
4119 (defcustom org-emphasis-alist
4120 `(("*" bold)
4121 ("/" italic)
4122 ("_" underline)
4123 ("=" org-verbatim verbatim)
4124 ("~" org-code verbatim)
4125 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4126 "Alist of characters and faces to emphasize text.
4127 Text starting and ending with a special character will be emphasized,
4128 for example *bold*, _underlined_ and /italic/. This variable sets the
4129 marker characters and the face to be used by font-lock for highlighting
4130 in Org-mode Emacs buffers.
4132 You need to reload Org or to restart Emacs after customizing this."
4133 :group 'org-appearance
4134 :set 'org-set-emph-re
4135 :version "24.4"
4136 :package-version '(Org . "8.0")
4137 :type '(repeat
4138 (list
4139 (string :tag "Marker character")
4140 (choice
4141 (face :tag "Font-lock-face")
4142 (plist :tag "Face property list"))
4143 (option (const verbatim)))))
4145 (defvar org-protecting-blocks
4146 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4147 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4148 This is needed for font-lock setup.")
4150 ;;; Miscellaneous options
4152 (defgroup org-completion nil
4153 "Completion in Org-mode."
4154 :tag "Org Completion"
4155 :group 'org)
4157 (defcustom org-completion-use-ido nil
4158 "Non-nil means use ido completion wherever possible.
4159 Note that `ido-mode' must be active for this variable to be relevant.
4160 If you decide to turn this variable on, you might well want to turn off
4161 `org-outline-path-complete-in-steps'.
4162 See also `org-completion-use-iswitchb'."
4163 :group 'org-completion
4164 :type 'boolean)
4166 (defcustom org-completion-use-iswitchb nil
4167 "Non-nil means use iswitchb completion wherever possible.
4168 Note that `iswitchb-mode' must be active for this variable to be relevant.
4169 If you decide to turn this variable on, you might well want to turn off
4170 `org-outline-path-complete-in-steps'.
4171 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4172 :group 'org-completion
4173 :type 'boolean)
4175 (defcustom org-completion-fallback-command 'hippie-expand
4176 "The expansion command called by \\[pcomplete] in normal context.
4177 Normal means, no org-mode-specific context."
4178 :group 'org-completion
4179 :type 'function)
4181 ;;; Functions and variables from their packages
4182 ;; Declared here to avoid compiler warnings
4184 ;; XEmacs only
4185 (defvar outline-mode-menu-heading)
4186 (defvar outline-mode-menu-show)
4187 (defvar outline-mode-menu-hide)
4188 (defvar zmacs-regions) ; XEmacs regions
4190 ;; Emacs only
4191 (defvar mark-active)
4193 ;; Various packages
4194 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4195 (declare-function calendar-forward-day "cal-move" (arg))
4196 (declare-function calendar-goto-date "cal-move" (date))
4197 (declare-function calendar-goto-today "cal-move" ())
4198 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4199 (defvar calc-embedded-close-formula)
4200 (defvar calc-embedded-open-formula)
4201 (declare-function cdlatex-tab "ext:cdlatex" ())
4202 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4203 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4204 (defvar font-lock-unfontify-region-function)
4205 (declare-function iswitchb-read-buffer "iswitchb"
4206 (prompt &optional default require-match start matches-set))
4207 (defvar iswitchb-temp-buflist)
4208 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4209 (defvar org-agenda-tags-todo-honor-ignore-options)
4210 (declare-function org-agenda-skip "org-agenda" ())
4211 (declare-function
4212 org-agenda-format-item "org-agenda"
4213 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4214 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4215 (declare-function org-agenda-change-all-lines "org-agenda"
4216 (newhead hdmarker &optional fixface just-this))
4217 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4218 (declare-function org-agenda-maybe-redo "org-agenda" ())
4219 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4220 (beg end))
4221 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4222 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4223 "org-agenda" (&optional end))
4224 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4225 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4226 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4227 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4228 (declare-function org-indent-mode "org-indent" (&optional arg))
4229 (declare-function parse-time-string "parse-time" (string))
4230 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4231 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4232 (defvar remember-data-file)
4233 (defvar texmathp-why)
4234 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4235 (declare-function table--at-cell-p "table" (position &optional object at-column))
4237 (defvar org-latex-regexps)
4239 ;;; Autoload and prepare some org modules
4241 ;; Some table stuff that needs to be defined here, because it is used
4242 ;; by the functions setting up org-mode or checking for table context.
4244 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4245 "Detect an org-type or table-type table.")
4246 (defconst org-table-line-regexp "^[ \t]*|"
4247 "Detect an org-type table line.")
4248 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4249 "Detect an org-type table line.")
4250 (defconst org-table-hline-regexp "^[ \t]*|-"
4251 "Detect an org-type table hline.")
4252 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4253 "Detect a table-type table hline.")
4254 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4255 "Detect the first line outside a table when searching from within it.
4256 This works for both table types.")
4258 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
4259 "Detect a #+TBLFM line.")
4261 ;;;###autoload
4262 (defun turn-on-orgtbl ()
4263 "Unconditionally turn on `orgtbl-mode'."
4264 (require 'org-table)
4265 (orgtbl-mode 1))
4267 (defun org-at-table-p (&optional table-type)
4268 "Return t if the cursor is inside an org-type table.
4269 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4270 (if org-enable-table-editor
4271 (save-excursion
4272 (beginning-of-line 1)
4273 (looking-at (if table-type org-table-any-line-regexp
4274 org-table-line-regexp)))
4275 nil))
4276 (defsubst org-table-p () (org-at-table-p))
4278 (defun org-at-table.el-p ()
4279 "Return t if and only if we are at a table.el table."
4280 (and (org-at-table-p 'any)
4281 (save-excursion
4282 (goto-char (org-table-begin 'any))
4283 (looking-at org-table1-hline-regexp))))
4285 (defun org-table-recognize-table.el ()
4286 "If there is a table.el table nearby, recognize it and move into it."
4287 (if org-table-tab-recognizes-table.el
4288 (if (org-at-table.el-p)
4289 (progn
4290 (beginning-of-line 1)
4291 (if (looking-at org-table-dataline-regexp)
4293 (if (looking-at org-table1-hline-regexp)
4294 (progn
4295 (beginning-of-line 2)
4296 (if (looking-at org-table-any-border-regexp)
4297 (beginning-of-line -1)))))
4298 (if (re-search-forward "|" (org-table-end t) t)
4299 (progn
4300 (require 'table)
4301 (if (table--at-cell-p (point))
4303 (message "recognizing table.el table...")
4304 (table-recognize-table)
4305 (message "recognizing table.el table...done")))
4306 (error "This should not happen"))
4308 nil)
4309 nil))
4311 (defun org-at-table-hline-p ()
4312 "Return t if the cursor is inside a hline in a table."
4313 (if org-enable-table-editor
4314 (save-excursion
4315 (beginning-of-line 1)
4316 (looking-at org-table-hline-regexp))
4317 nil))
4319 (defun org-table-map-tables (function &optional quietly)
4320 "Apply FUNCTION to the start of all tables in the buffer."
4321 (save-excursion
4322 (save-restriction
4323 (widen)
4324 (goto-char (point-min))
4325 (while (re-search-forward org-table-any-line-regexp nil t)
4326 (unless quietly
4327 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4328 (beginning-of-line 1)
4329 (when (and (looking-at org-table-line-regexp)
4330 ;; Exclude tables in src/example/verbatim/clocktable blocks
4331 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4332 (save-excursion (funcall function))
4333 (or (looking-at org-table-line-regexp)
4334 (forward-char 1)))
4335 (re-search-forward org-table-any-border-regexp nil 1))))
4336 (unless quietly (message "Mapping tables: done")))
4338 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4339 (declare-function org-clock-update-mode-line "org-clock" ())
4340 (declare-function org-resolve-clocks "org-clock"
4341 (&optional also-non-dangling-p prompt last-valid))
4343 (defun org-at-TBLFM-p (&optional pos)
4344 "Return t when point (or POS) is in #+TBLFM line."
4345 (save-excursion
4346 (let ((pos pos)))
4347 (goto-char (or pos (point)))
4348 (beginning-of-line 1)
4349 (looking-at org-TBLFM-regexp)))
4351 (defvar org-clock-start-time)
4352 (defvar org-clock-marker (make-marker)
4353 "Marker recording the last clock-in.")
4354 (defvar org-clock-hd-marker (make-marker)
4355 "Marker recording the last clock-in, but the headline position.")
4356 (defvar org-clock-heading ""
4357 "The heading of the current clock entry.")
4358 (defun org-clock-is-active ()
4359 "Return the buffer where the clock is currently running.
4360 Return nil if no clock is running."
4361 (marker-buffer org-clock-marker))
4363 (defun org-check-running-clock ()
4364 "Check if the current buffer contains the running clock.
4365 If yes, offer to stop it and to save the buffer with the changes."
4366 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4367 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4368 (buffer-name))))
4369 (org-clock-out)
4370 (when (y-or-n-p "Save changed buffer?")
4371 (save-buffer))))
4373 (defun org-clocktable-try-shift (dir n)
4374 "Check if this line starts a clock table, if yes, shift the time block."
4375 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4376 (org-clocktable-shift dir n)))
4378 ;;;###autoload
4379 (defun org-clock-persistence-insinuate ()
4380 "Set up hooks for clock persistence."
4381 (require 'org-clock)
4382 (add-hook 'org-mode-hook 'org-clock-load)
4383 (add-hook 'kill-emacs-hook 'org-clock-save))
4385 (defgroup org-archive nil
4386 "Options concerning archiving in Org-mode."
4387 :tag "Org Archive"
4388 :group 'org-structure)
4390 (defcustom org-archive-location "%s_archive::"
4391 "The location where subtrees should be archived.
4393 The value of this variable is a string, consisting of two parts,
4394 separated by a double-colon. The first part is a filename and
4395 the second part is a headline.
4397 When the filename is omitted, archiving happens in the same file.
4398 %s in the filename will be replaced by the current file
4399 name (without the directory part). Archiving to a different file
4400 is useful to keep archived entries from contributing to the
4401 Org-mode Agenda.
4403 The archived entries will be filed as subtrees of the specified
4404 headline. When the headline is omitted, the subtrees are simply
4405 filed away at the end of the file, as top-level entries. Also in
4406 the heading you can use %s to represent the file name, this can be
4407 useful when using the same archive for a number of different files.
4409 Here are a few examples:
4410 \"%s_archive::\"
4411 If the current file is Projects.org, archive in file
4412 Projects.org_archive, as top-level trees. This is the default.
4414 \"::* Archived Tasks\"
4415 Archive in the current file, under the top-level headline
4416 \"* Archived Tasks\".
4418 \"~/org/archive.org::\"
4419 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4421 \"~/org/archive.org::* From %s\"
4422 Archive in file ~/org/archive.org (absolute path), under headlines
4423 \"From FILENAME\" where file name is the current file name.
4425 \"~/org/datetree.org::datetree/* Finished Tasks\"
4426 The \"datetree/\" string is special, signifying to archive
4427 items to the datetree. Items are placed in either the CLOSED
4428 date of the item, or the current date if there is no CLOSED date.
4429 The heading will be a subentry to the current date. There doesn't
4430 need to be a heading, but there always needs to be a slash after
4431 datetree. For example, to store archived items directly in the
4432 datetree, use \"~/org/datetree.org::datetree/\".
4434 \"basement::** Finished Tasks\"
4435 Archive in file ./basement (relative path), as level 3 trees
4436 below the level 2 heading \"** Finished Tasks\".
4438 You may set this option on a per-file basis by adding to the buffer a
4439 line like
4441 #+ARCHIVE: basement::** Finished Tasks
4443 You may also define it locally for a subtree by setting an ARCHIVE property
4444 in the entry. If such a property is found in an entry, or anywhere up
4445 the hierarchy, it will be used."
4446 :group 'org-archive
4447 :type 'string)
4449 (defcustom org-archive-tag "ARCHIVE"
4450 "The tag that marks a subtree as archived.
4451 An archived subtree does not open during visibility cycling, and does
4452 not contribute to the agenda listings.
4453 After changing this, font-lock must be restarted in the relevant buffers to
4454 get the proper fontification."
4455 :group 'org-archive
4456 :group 'org-keywords
4457 :type 'string)
4459 (defcustom org-agenda-skip-archived-trees t
4460 "Non-nil means the agenda will skip any items located in archived trees.
4461 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4462 variable is no longer recommended, you should leave it at the value t.
4463 Instead, use the key `v' to cycle the archives-mode in the agenda."
4464 :group 'org-archive
4465 :group 'org-agenda-skip
4466 :type 'boolean)
4468 (defcustom org-columns-skip-archived-trees t
4469 "Non-nil means ignore archived trees when creating column view."
4470 :group 'org-archive
4471 :group 'org-properties
4472 :type 'boolean)
4474 (defcustom org-cycle-open-archived-trees nil
4475 "Non-nil means `org-cycle' will open archived trees.
4476 An archived tree is a tree marked with the tag ARCHIVE.
4477 When nil, archived trees will stay folded. You can still open them with
4478 normal outline commands like `show-all', but not with the cycling commands."
4479 :group 'org-archive
4480 :group 'org-cycle
4481 :type 'boolean)
4483 (defcustom org-sparse-tree-open-archived-trees nil
4484 "Non-nil means sparse tree construction shows matches in archived trees.
4485 When nil, matches in these trees are highlighted, but the trees are kept in
4486 collapsed state."
4487 :group 'org-archive
4488 :group 'org-sparse-trees
4489 :type 'boolean)
4491 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4492 "The default date type when building a sparse tree.
4493 When this is nil, a date is a scheduled or a deadline timestamp.
4494 Otherwise, these types are allowed:
4496 all: all timestamps
4497 active: only active timestamps (<...>)
4498 inactive: only inactive timestamps (<...)
4499 scheduled: only scheduled timestamps
4500 deadline: only deadline timestamps"
4501 :type '(choice (const :tag "Scheduled or deadline" scheduled-or-deadline)
4502 (const :tag "All timestamps" all)
4503 (const :tag "Only active timestamps" active)
4504 (const :tag "Only inactive timestamps" inactive)
4505 (const :tag "Only scheduled timestamps" scheduled)
4506 (const :tag "Only deadline timestamps" deadline)
4507 (const :tag "Only closed timestamps" closed))
4508 :version "24.3"
4509 :group 'org-sparse-trees)
4511 (defun org-cycle-hide-archived-subtrees (state)
4512 "Re-hide all archived subtrees after a visibility state change."
4513 (when (and (not org-cycle-open-archived-trees)
4514 (not (memq state '(overview folded))))
4515 (save-excursion
4516 (let* ((globalp (memq state '(contents all)))
4517 (beg (if globalp (point-min) (point)))
4518 (end (if globalp (point-max) (org-end-of-subtree t))))
4519 (org-hide-archived-subtrees beg end)
4520 (goto-char beg)
4521 (if (looking-at (concat ".*:" org-archive-tag ":"))
4522 (message "%s" (substitute-command-keys
4523 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4525 (defun org-force-cycle-archived ()
4526 "Cycle subtree even if it is archived."
4527 (interactive)
4528 (setq this-command 'org-cycle)
4529 (let ((org-cycle-open-archived-trees t))
4530 (call-interactively 'org-cycle)))
4532 (defun org-hide-archived-subtrees (beg end)
4533 "Re-hide all archived subtrees after a visibility state change."
4534 (save-excursion
4535 (let* ((re (concat ":" org-archive-tag ":")))
4536 (goto-char beg)
4537 (while (re-search-forward re end t)
4538 (when (org-at-heading-p)
4539 (org-flag-subtree t)
4540 (org-end-of-subtree t))))))
4542 (declare-function outline-end-of-heading "outline" ())
4543 (declare-function outline-flag-region "outline" (from to flag))
4544 (defun org-flag-subtree (flag)
4545 (save-excursion
4546 (org-back-to-heading t)
4547 (outline-end-of-heading)
4548 (outline-flag-region (point)
4549 (progn (org-end-of-subtree t) (point))
4550 flag)))
4552 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4554 ;; Declare Column View Code
4556 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4557 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4558 (declare-function org-columns-compute "org-colview" (property))
4560 ;; Declare ID code
4562 (declare-function org-id-store-link "org-id")
4563 (declare-function org-id-locations-load "org-id")
4564 (declare-function org-id-locations-save "org-id")
4565 (defvar org-id-track-globally)
4567 ;;; Variables for pre-computed regular expressions, all buffer local
4569 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4570 "Matches first line of a hidden block.")
4571 (make-variable-buffer-local 'org-drawer-regexp)
4572 (defvar org-todo-regexp nil
4573 "Matches any of the TODO state keywords.")
4574 (make-variable-buffer-local 'org-todo-regexp)
4575 (defvar org-not-done-regexp nil
4576 "Matches any of the TODO state keywords except the last one.")
4577 (make-variable-buffer-local 'org-not-done-regexp)
4578 (defvar org-not-done-heading-regexp nil
4579 "Matches a TODO headline that is not done.")
4580 (make-variable-buffer-local 'org-not-done-regexp)
4581 (defvar org-todo-line-regexp nil
4582 "Matches a headline and puts TODO state into group 2 if present.")
4583 (make-variable-buffer-local 'org-todo-line-regexp)
4584 (defvar org-complex-heading-regexp nil
4585 "Matches a headline and puts everything into groups:
4586 group 1: the stars
4587 group 2: The todo keyword, maybe
4588 group 3: Priority cookie
4589 group 4: True headline
4590 group 5: Tags")
4591 (make-variable-buffer-local 'org-complex-heading-regexp)
4592 (defvar org-complex-heading-regexp-format nil
4593 "Printf format to make regexp to match an exact headline.
4594 This regexp will match the headline of any node which has the
4595 exact headline text that is put into the format, but may have any
4596 TODO state, priority and tags.")
4597 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4598 (defvar org-todo-line-tags-regexp nil
4599 "Matches a headline and puts TODO state into group 2 if present.
4600 Also put tags into group 4 if tags are present.")
4601 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4602 (defvar org-ds-keyword-length 12
4603 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4604 (make-variable-buffer-local 'org-ds-keyword-length)
4605 (defvar org-deadline-regexp nil
4606 "Matches the DEADLINE keyword.")
4607 (make-variable-buffer-local 'org-deadline-regexp)
4608 (defvar org-deadline-time-regexp nil
4609 "Matches the DEADLINE keyword together with a time stamp.")
4610 (make-variable-buffer-local 'org-deadline-time-regexp)
4611 (defvar org-deadline-time-hour-regexp nil
4612 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4613 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4614 (defvar org-deadline-line-regexp nil
4615 "Matches the DEADLINE keyword and the rest of the line.")
4616 (make-variable-buffer-local 'org-deadline-line-regexp)
4617 (defvar org-scheduled-regexp nil
4618 "Matches the SCHEDULED keyword.")
4619 (make-variable-buffer-local 'org-scheduled-regexp)
4620 (defvar org-scheduled-time-regexp nil
4621 "Matches the SCHEDULED keyword together with a time stamp.")
4622 (make-variable-buffer-local 'org-scheduled-time-regexp)
4623 (defvar org-scheduled-time-hour-regexp nil
4624 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4625 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4626 (defvar org-closed-time-regexp nil
4627 "Matches the CLOSED keyword together with a time stamp.")
4628 (make-variable-buffer-local 'org-closed-time-regexp)
4630 (defvar org-keyword-time-regexp nil
4631 "Matches any of the 4 keywords, together with the time stamp.")
4632 (make-variable-buffer-local 'org-keyword-time-regexp)
4633 (defvar org-keyword-time-not-clock-regexp nil
4634 "Matches any of the 3 keywords, together with the time stamp.")
4635 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4636 (defvar org-maybe-keyword-time-regexp nil
4637 "Matches a timestamp, possibly preceded by a keyword.")
4638 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4639 (defvar org-all-time-keywords nil
4640 "List of time keywords.")
4641 (make-variable-buffer-local 'org-all-time-keywords)
4643 (defconst org-plain-time-of-day-regexp
4644 (concat
4645 "\\(\\<[012]?[0-9]"
4646 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4647 "\\(--?"
4648 "\\(\\<[012]?[0-9]"
4649 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4650 "\\)?")
4651 "Regular expression to match a plain time or time range.
4652 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4653 groups carry important information:
4654 0 the full match
4655 1 the first time, range or not
4656 8 the second time, if it is a range.")
4658 (defconst org-plain-time-extension-regexp
4659 (concat
4660 "\\(\\<[012]?[0-9]"
4661 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4662 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4663 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4664 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4665 groups carry important information:
4666 0 the full match
4667 7 hours of duration
4668 9 minutes of duration")
4670 (defconst org-stamp-time-of-day-regexp
4671 (concat
4672 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4673 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4674 "\\(--?"
4675 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4676 "Regular expression to match a timestamp time or time range.
4677 After a match, the following groups carry important information:
4678 0 the full match
4679 1 date plus weekday, for back referencing to make sure both times are on the same day
4680 2 the first time, range or not
4681 4 the second time, if it is a range.")
4683 (defconst org-startup-options
4684 '(("fold" org-startup-folded t)
4685 ("overview" org-startup-folded t)
4686 ("nofold" org-startup-folded nil)
4687 ("showall" org-startup-folded nil)
4688 ("showeverything" org-startup-folded showeverything)
4689 ("content" org-startup-folded content)
4690 ("indent" org-startup-indented t)
4691 ("noindent" org-startup-indented nil)
4692 ("hidestars" org-hide-leading-stars t)
4693 ("showstars" org-hide-leading-stars nil)
4694 ("odd" org-odd-levels-only t)
4695 ("oddeven" org-odd-levels-only nil)
4696 ("align" org-startup-align-all-tables t)
4697 ("noalign" org-startup-align-all-tables nil)
4698 ("inlineimages" org-startup-with-inline-images t)
4699 ("noinlineimages" org-startup-with-inline-images nil)
4700 ("latexpreview" org-startup-with-latex-preview t)
4701 ("nolatexpreview" org-startup-with-latex-preview nil)
4702 ("customtime" org-display-custom-times t)
4703 ("logdone" org-log-done time)
4704 ("lognotedone" org-log-done note)
4705 ("nologdone" org-log-done nil)
4706 ("lognoteclock-out" org-log-note-clock-out t)
4707 ("nolognoteclock-out" org-log-note-clock-out nil)
4708 ("logrepeat" org-log-repeat state)
4709 ("lognoterepeat" org-log-repeat note)
4710 ("logdrawer" org-log-into-drawer t)
4711 ("nologdrawer" org-log-into-drawer nil)
4712 ("logstatesreversed" org-log-states-order-reversed t)
4713 ("nologstatesreversed" org-log-states-order-reversed nil)
4714 ("nologrepeat" org-log-repeat nil)
4715 ("logreschedule" org-log-reschedule time)
4716 ("lognotereschedule" org-log-reschedule note)
4717 ("nologreschedule" org-log-reschedule nil)
4718 ("logredeadline" org-log-redeadline time)
4719 ("lognoteredeadline" org-log-redeadline note)
4720 ("nologredeadline" org-log-redeadline nil)
4721 ("logrefile" org-log-refile time)
4722 ("lognoterefile" org-log-refile note)
4723 ("nologrefile" org-log-refile nil)
4724 ("fninline" org-footnote-define-inline t)
4725 ("nofninline" org-footnote-define-inline nil)
4726 ("fnlocal" org-footnote-section nil)
4727 ("fnauto" org-footnote-auto-label t)
4728 ("fnprompt" org-footnote-auto-label nil)
4729 ("fnconfirm" org-footnote-auto-label confirm)
4730 ("fnplain" org-footnote-auto-label plain)
4731 ("fnadjust" org-footnote-auto-adjust t)
4732 ("nofnadjust" org-footnote-auto-adjust nil)
4733 ("constcgs" constants-unit-system cgs)
4734 ("constSI" constants-unit-system SI)
4735 ("noptag" org-tag-persistent-alist nil)
4736 ("hideblocks" org-hide-block-startup t)
4737 ("nohideblocks" org-hide-block-startup nil)
4738 ("beamer" org-startup-with-beamer-mode t)
4739 ("entitiespretty" org-pretty-entities t)
4740 ("entitiesplain" org-pretty-entities nil))
4741 "Variable associated with STARTUP options for org-mode.
4742 Each element is a list of three items: the startup options (as written
4743 in the #+STARTUP line), the corresponding variable, and the value to set
4744 this variable to if the option is found. An optional forth element PUSH
4745 means to push this value onto the list in the variable.")
4747 (defun org-update-property-plist (key val props)
4748 "Update PROPS with KEY and VAL."
4749 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4750 (key (if appending (substring key 0 (- (length key) 1)) key))
4751 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4752 (previous (cdr (assoc key props))))
4753 (if appending
4754 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4755 (cons (cons key val) remainder))))
4757 (defconst org-block-regexp
4758 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4759 "Regular expression for hiding blocks.")
4760 (defconst org-heading-keyword-regexp-format
4761 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4762 "Printf format for a regexp matching a headline with some keyword.
4763 This regexp will match the headline of any node which has the
4764 exact keyword that is put into the format. The keyword isn't in
4765 any group by default, but the stars and the body are.")
4766 (defconst org-heading-keyword-maybe-regexp-format
4767 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4768 "Printf format for a regexp matching a headline, possibly with some keyword.
4769 This regexp can match any headline with the specified keyword, or
4770 without a keyword. The keyword isn't in any group by default,
4771 but the stars and the body are.")
4773 (defcustom org-group-tags t
4774 "When non-nil (the default), use group tags.
4775 This can be turned on/off through `org-toggle-tags-groups'."
4776 :group 'org-tags
4777 :group 'org-startup
4778 :type 'boolean)
4780 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4782 (defun org-toggle-tags-groups ()
4783 "Toggle support for group tags.
4784 Support for group tags is controlled by the option
4785 `org-group-tags', which is non-nil by default."
4786 (interactive)
4787 (setq org-group-tags (not org-group-tags))
4788 (cond ((and (derived-mode-p 'org-agenda-mode)
4789 org-group-tags)
4790 (org-agenda-redo))
4791 ((derived-mode-p 'org-mode)
4792 (let ((org-inhibit-startup t)) (org-mode))))
4793 (message "Groups tags support has been turned %s"
4794 (if org-group-tags "on" "off")))
4796 (defun org-set-regexps-and-options-for-tags ()
4797 "Precompute variables used for tags."
4798 (when (derived-mode-p 'org-mode)
4799 (org-set-local 'org-file-tags nil)
4800 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4801 (splitre "[ \t]+")
4802 (start 0)
4803 tags ftags key value)
4804 (save-excursion
4805 (save-restriction
4806 (widen)
4807 (goto-char (point-min))
4808 (while (re-search-forward re nil t)
4809 (setq key (upcase (org-match-string-no-properties 1))
4810 value (org-match-string-no-properties 2))
4811 (if (stringp value) (setq value (org-trim value)))
4812 (cond
4813 ((equal key "TAGS")
4814 (setq tags (append tags (if tags '("\\n") nil)
4815 (org-split-string value splitre))))
4816 ((equal key "FILETAGS")
4817 (when (string-match "\\S-" value)
4818 (setq ftags
4819 (append
4820 ftags
4821 (apply 'append
4822 (mapcar (lambda (x) (org-split-string x ":"))
4823 (org-split-string value)))))))))))
4824 ;; Process the file tags.
4825 (and ftags (org-set-local 'org-file-tags
4826 (mapcar 'org-add-prop-inherited ftags)))
4827 (org-set-local 'org-tag-groups-alist nil)
4828 ;; Process the tags.
4829 (when (and (not tags) org-tag-alist)
4830 (setq tags
4831 (mapcar
4832 (lambda (tg) (cond ((eq (car tg) :startgroup) "{")
4833 ((eq (car tg) :endgroup) "}")
4834 ((eq (car tg) :grouptags) ":")
4835 ((eq (car tg) :newline) "\n")
4836 (t (concat (car tg)
4837 (if (characterp (cdr tg))
4838 (format "(%s)" (char-to-string (cdr tg))) "")))))
4839 org-tag-alist)))
4840 (let (e tgs g)
4841 (while (setq e (pop tags))
4842 (cond
4843 ((equal e "{")
4844 (progn (push '(:startgroup) tgs)
4845 (when (equal (nth 1 tags) ":")
4846 (push (list (replace-regexp-in-string
4847 "(.+)$" "" (nth 0 tags)))
4848 org-tag-groups-alist)
4849 (setq g 0))))
4850 ((equal e ":") (push '(:grouptags) tgs))
4851 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4852 ((equal e "\\n") (push '(:newline) tgs))
4853 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4854 (push (cons (match-string 1 e)
4855 (string-to-char (match-string 2 e))) tgs)
4856 (if (and g (> g 0))
4857 (setcar org-tag-groups-alist
4858 (append (car org-tag-groups-alist)
4859 (list (match-string 1 e)))))
4860 (if g (setq g (1+ g))))
4861 (t (push (list e) tgs)
4862 (if (and g (> g 0))
4863 (setcar org-tag-groups-alist
4864 (append (car org-tag-groups-alist) (list e))))
4865 (if g (setq g (1+ g))))))
4866 (org-set-local 'org-tag-alist nil)
4867 (while (setq e (pop tgs))
4868 (or (and (stringp (car e))
4869 (assoc (car e) org-tag-alist))
4870 (push e org-tag-alist)))
4871 ;; Return a list with tag variables
4872 (list org-file-tags org-tag-alist org-tag-groups-alist)))))
4874 (defvar org-ota nil)
4875 (defun org-set-regexps-and-options ()
4876 "Precompute regular expressions used in the current buffer."
4877 (when (derived-mode-p 'org-mode)
4878 (org-set-local 'org-todo-kwd-alist nil)
4879 (org-set-local 'org-todo-key-alist nil)
4880 (org-set-local 'org-todo-key-trigger nil)
4881 (org-set-local 'org-todo-keywords-1 nil)
4882 (org-set-local 'org-done-keywords nil)
4883 (org-set-local 'org-todo-heads nil)
4884 (org-set-local 'org-todo-sets nil)
4885 (org-set-local 'org-todo-log-states nil)
4886 (org-set-local 'org-file-properties nil)
4887 (let ((re (org-make-options-regexp
4888 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
4889 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4890 "SETUPFILE" "OPTIONS")
4891 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4892 (splitre "[ \t]+")
4893 (scripts org-use-sub-superscripts)
4894 kwds kws0 kwsa key log value cat arch const links hw dws
4895 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
4896 (start 0))
4897 (save-excursion
4898 (save-restriction
4899 (widen)
4900 (goto-char (point-min))
4901 (while
4902 (or (and
4903 ext-setup-or-nil
4904 (not org-ota)
4905 (let (ret)
4906 (with-temp-buffer
4907 (insert ext-setup-or-nil)
4908 (let ((major-mode 'org-mode) org-ota)
4909 (setq ret (save-match-data
4910 (org-set-regexps-and-options-for-tags)))))
4911 ;; Append setupfile tags to existing tags
4912 (setq org-ota t)
4913 (setq org-file-tags
4914 (delq nil (append org-file-tags (nth 0 ret)))
4915 org-tag-alist
4916 (delq nil (append org-tag-alist (nth 1 ret)))
4917 org-tag-groups-alist
4918 (delq nil (append org-tag-groups-alist (nth 2 ret))))))
4919 (and ext-setup-or-nil
4920 (string-match re ext-setup-or-nil start)
4921 (setq start (match-end 0)))
4922 (and (setq ext-setup-or-nil nil start 0)
4923 (re-search-forward re nil t)))
4924 (setq key (upcase (match-string 1 ext-setup-or-nil))
4925 value (org-match-string-no-properties 2 ext-setup-or-nil))
4926 (if (stringp value) (setq value (org-trim value)))
4927 (cond
4928 ((equal key "CATEGORY")
4929 (setq cat value))
4930 ((member key '("SEQ_TODO" "TODO"))
4931 (push (cons 'sequence (org-split-string value splitre)) kwds))
4932 ((equal key "TYP_TODO")
4933 (push (cons 'type (org-split-string value splitre)) kwds))
4934 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4935 ;; general TODO-like setup
4936 (push (cons (intern (downcase (match-string 1 key)))
4937 (org-split-string value splitre)) kwds))
4938 ((equal key "COLUMNS")
4939 (org-set-local 'org-columns-default-format value))
4940 ((equal key "LINK")
4941 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4942 (push (cons (match-string 1 value)
4943 (org-trim (match-string 2 value)))
4944 links)))
4945 ((equal key "PRIORITIES")
4946 (setq prio (org-split-string value " +")))
4947 ((equal key "PROPERTY")
4948 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4949 (setq props (org-update-property-plist (match-string 1 value)
4950 (match-string 2 value)
4951 props))))
4952 ((equal key "DRAWERS")
4953 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4954 ((equal key "CONSTANTS")
4955 (org-table-set-constants))
4956 ((equal key "STARTUP")
4957 (let ((opts (org-split-string value splitre))
4958 l var val)
4959 (while (setq l (pop opts))
4960 (when (setq l (assoc l org-startup-options))
4961 (setq var (nth 1 l) val (nth 2 l))
4962 (if (not (nth 3 l))
4963 (set (make-local-variable var) val)
4964 (if (not (listp (symbol-value var)))
4965 (set (make-local-variable var) nil))
4966 (set (make-local-variable var) (symbol-value var))
4967 (add-to-list var val))))))
4968 ((equal key "ARCHIVE")
4969 (setq arch value)
4970 (remove-text-properties 0 (length arch)
4971 '(face t fontified t) arch))
4972 ((equal key "OPTIONS")
4973 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4974 (setq scripts (read (match-string 2 value)))))
4975 ((and (equal key "SETUPFILE")
4976 ;; Prevent checking in Gnus messages
4977 (not buffer-read-only))
4978 (setq setup-contents (org-file-contents
4979 (expand-file-name
4980 (org-remove-double-quotes value))
4981 'noerror))
4982 (if (not ext-setup-or-nil)
4983 (setq ext-setup-or-nil setup-contents start 0)
4984 (setq ext-setup-or-nil
4985 (concat (substring ext-setup-or-nil 0 start)
4986 "\n" setup-contents "\n"
4987 (substring ext-setup-or-nil start)))))))
4988 ;; search for property blocks
4989 (goto-char (point-min))
4990 (while (re-search-forward org-block-regexp nil t)
4991 (when (equal "PROPERTY" (upcase (match-string 1)))
4992 (setq value (replace-regexp-in-string
4993 "[\n\r]" " " (match-string 4)))
4994 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4995 (setq props (org-update-property-plist (match-string 1 value)
4996 (match-string 2 value)
4997 props)))))))
4998 (org-set-local 'org-use-sub-superscripts scripts)
4999 (when cat
5000 (org-set-local 'org-category (intern cat))
5001 (push (cons "CATEGORY" cat) props))
5002 (when prio
5003 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
5004 (setq prio (mapcar 'string-to-char prio))
5005 (org-set-local 'org-highest-priority (nth 0 prio))
5006 (org-set-local 'org-lowest-priority (nth 1 prio))
5007 (org-set-local 'org-default-priority (nth 2 prio)))
5008 (and props (org-set-local 'org-file-properties (nreverse props)))
5009 (and drawers (org-set-local 'org-drawers drawers))
5010 (and arch (org-set-local 'org-archive-location arch))
5011 (and links (setq org-link-abbrev-alist-local (nreverse links)))
5012 ;; Process the TODO keywords
5013 (unless kwds
5014 ;; Use the global values as if they had been given locally.
5015 (setq kwds (default-value 'org-todo-keywords))
5016 (if (stringp (car kwds))
5017 (setq kwds (list (cons org-todo-interpretation
5018 (default-value 'org-todo-keywords)))))
5019 (setq kwds (reverse kwds)))
5020 (setq kwds (nreverse kwds))
5021 (let (inter kws kw)
5022 (while (setq kws (pop kwds))
5023 (let ((kws (or
5024 (run-hook-with-args-until-success
5025 'org-todo-setup-filter-hook kws)
5026 kws)))
5027 (setq inter (pop kws) sep (member "|" kws)
5028 kws0 (delete "|" (copy-sequence kws))
5029 kwsa nil
5030 kws1 (mapcar
5031 (lambda (x)
5032 ;; 1 2
5033 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
5034 (progn
5035 (setq kw (match-string 1 x)
5036 key (and (match-end 2) (match-string 2 x))
5037 log (org-extract-log-state-settings x))
5038 (push (cons kw (and key (string-to-char key))) kwsa)
5039 (and log (push log org-todo-log-states))
5041 (error "Invalid TODO keyword %s" x)))
5042 kws0)
5043 kwsa (if kwsa (append '((:startgroup))
5044 (nreverse kwsa)
5045 '((:endgroup))))
5046 hw (car kws1)
5047 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
5048 tail (list inter hw (car dws) (org-last dws))))
5049 (add-to-list 'org-todo-heads hw 'append)
5050 (push kws1 org-todo-sets)
5051 (setq org-done-keywords (append org-done-keywords dws nil))
5052 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
5053 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
5054 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
5055 (setq org-todo-sets (nreverse org-todo-sets)
5056 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5057 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
5058 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
5059 ;; Compute the regular expressions and other local variables.
5060 ;; Using `org-outline-regexp-bol' would complicate them much,
5061 ;; because of the fixed white space at the end of that string.
5062 (if (not org-done-keywords)
5063 (setq org-done-keywords (and org-todo-keywords-1
5064 (list (org-last org-todo-keywords-1)))))
5065 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5066 (length org-scheduled-string)
5067 (length org-clock-string)
5068 (length org-closed-string)))
5069 org-drawer-regexp
5070 (concat "^[ \t]*:\\("
5071 (mapconcat 'regexp-quote org-drawers "\\|")
5072 "\\):[ \t]*$")
5073 org-not-done-keywords
5074 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5075 org-todo-regexp
5076 (concat "\\("
5077 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5078 "\\)")
5079 org-not-done-regexp
5080 (concat "\\("
5081 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5082 "\\)")
5083 org-not-done-heading-regexp
5084 (format org-heading-keyword-regexp-format org-not-done-regexp)
5085 org-todo-line-regexp
5086 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5087 org-complex-heading-regexp
5088 (concat "^\\(\\*+\\)"
5089 "\\(?: +" org-todo-regexp "\\)?"
5090 "\\(?: +\\(\\[#.\\]\\)\\)?"
5091 "\\(?: +\\(.*?\\)\\)??"
5092 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5093 "[ \t]*$")
5094 org-complex-heading-regexp-format
5095 (concat "^\\(\\*+\\)"
5096 "\\(?: +" org-todo-regexp "\\)?"
5097 "\\(?: +\\(\\[#.\\]\\)\\)?"
5098 "\\(?: +"
5099 ;; Stats cookies can be stuck to body.
5100 "\\(?:\\[[0-9%%/]+\\] *\\)?"
5101 "\\(%s\\)"
5102 "\\(?: *\\[[0-9%%/]+\\]\\)?"
5103 "\\)"
5104 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5105 "[ \t]*$")
5106 org-todo-line-tags-regexp
5107 (concat "^\\(\\*+\\)"
5108 "\\(?: +" org-todo-regexp "\\)?"
5109 "\\(?: +\\(.*?\\)\\)??"
5110 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5111 "[ \t]*$")
5112 org-deadline-regexp (concat "\\<" org-deadline-string)
5113 org-deadline-time-regexp
5114 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5115 org-deadline-time-hour-regexp
5116 (concat "\\<" org-deadline-string
5117 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5118 org-deadline-line-regexp
5119 (concat "\\<\\(" org-deadline-string "\\).*")
5120 org-scheduled-regexp
5121 (concat "\\<" org-scheduled-string)
5122 org-scheduled-time-regexp
5123 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5124 org-scheduled-time-hour-regexp
5125 (concat "\\<" org-scheduled-string
5126 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5127 org-closed-time-regexp
5128 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5129 org-keyword-time-regexp
5130 (concat "\\<\\(" org-scheduled-string
5131 "\\|" org-deadline-string
5132 "\\|" org-closed-string
5133 "\\|" org-clock-string "\\)"
5134 " *[[<]\\([^]>]+\\)[]>]")
5135 org-keyword-time-not-clock-regexp
5136 (concat "\\<\\(" org-scheduled-string
5137 "\\|" org-deadline-string
5138 "\\|" org-closed-string
5139 "\\)"
5140 " *[[<]\\([^]>]+\\)[]>]")
5141 org-maybe-keyword-time-regexp
5142 (concat "\\(\\<\\(" org-scheduled-string
5143 "\\|" org-deadline-string
5144 "\\|" org-closed-string
5145 "\\|" org-clock-string "\\)\\)?"
5146 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5147 org-all-time-keywords
5148 (mapcar (lambda (w) (substring w 0 -1))
5149 (list org-scheduled-string org-deadline-string
5150 org-clock-string org-closed-string)))
5151 (setq org-ota nil)
5152 (org-compute-latex-and-related-regexp))))
5154 (defun org-file-contents (file &optional noerror)
5155 "Return the contents of FILE, as a string."
5156 (if (or (not file) (not (file-readable-p file)))
5157 (if (not noerror)
5158 (error "Cannot read file \"%s\"" file)
5159 (message "Cannot read file \"%s\"" file)
5161 (with-temp-buffer
5162 (insert-file-contents file)
5163 (buffer-string))))
5165 (defun org-extract-log-state-settings (x)
5166 "Extract the log state setting from a TODO keyword string.
5167 This will extract info from a string like \"WAIT(w@/!)\"."
5168 (let (kw key log1 log2)
5169 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5170 (setq kw (match-string 1 x)
5171 key (and (match-end 2) (match-string 2 x))
5172 log1 (and (match-end 3) (match-string 3 x))
5173 log2 (and (match-end 4) (match-string 4 x)))
5174 (and (or log1 log2)
5175 (list kw
5176 (and log1 (if (equal log1 "!") 'time 'note))
5177 (and log2 (if (equal log2 "!") 'time 'note)))))))
5179 (defun org-remove-keyword-keys (list)
5180 "Remove a pair of parenthesis at the end of each string in LIST."
5181 (mapcar (lambda (x)
5182 (if (string-match "(.*)$" x)
5183 (substring x 0 (match-beginning 0))
5185 list))
5187 (defun org-assign-fast-keys (alist)
5188 "Assign fast keys to a keyword-key alist.
5189 Respect keys that are already there."
5190 (let (new e (alt ?0))
5191 (while (setq e (pop alist))
5192 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5193 (cdr e)) ;; Key already assigned.
5194 (push e new)
5195 (let ((clist (string-to-list (downcase (car e))))
5196 (used (append new alist)))
5197 (when (= (car clist) ?@)
5198 (pop clist))
5199 (while (and clist (rassoc (car clist) used))
5200 (pop clist))
5201 (unless clist
5202 (while (rassoc alt used)
5203 (incf alt)))
5204 (push (cons (car e) (or (car clist) alt)) new))))
5205 (nreverse new)))
5207 ;;; Some variables used in various places
5209 (defvar org-window-configuration nil
5210 "Used in various places to store a window configuration.")
5211 (defvar org-selected-window nil
5212 "Used in various places to store a window configuration.")
5213 (defvar org-finish-function nil
5214 "Function to be called when `C-c C-c' is used.
5215 This is for getting out of special buffers like capture.")
5218 ;; FIXME: Occasionally check by commenting these, to make sure
5219 ;; no other functions uses these, forgetting to let-bind them.
5220 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5221 (defvar org-last-state)
5222 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5224 ;; Defined somewhere in this file, but used before definition.
5225 (defvar org-entities) ;; defined in org-entities.el
5226 (defvar org-struct-menu)
5227 (defvar org-org-menu)
5228 (defvar org-tbl-menu)
5230 ;;;; Define the Org-mode
5232 ;; We use a before-change function to check if a table might need
5233 ;; an update.
5234 (defvar org-table-may-need-update t
5235 "Indicates that a table might need an update.
5236 This variable is set by `org-before-change-function'.
5237 `org-table-align' sets it back to nil.")
5238 (defun org-before-change-function (beg end)
5239 "Every change indicates that a table might need an update."
5240 (setq org-table-may-need-update t))
5241 (defvar org-mode-map)
5242 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5243 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5244 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5245 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5246 (defvar org-table-buffer-is-an nil)
5248 (defvar bidi-paragraph-direction)
5249 (defvar buffer-face-mode-face)
5251 (require 'outline)
5252 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5253 (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"))
5254 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5256 ;; Other stuff we need.
5257 (require 'time-date)
5258 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5259 (require 'easymenu)
5260 (require 'overlay)
5262 ;; (require 'org-macs) moved higher up in the file before it is first used
5263 (require 'org-entities)
5264 ;; (require 'org-compat) moved higher up in the file before it is first used
5265 (require 'org-faces)
5266 (require 'org-list)
5267 (require 'org-pcomplete)
5268 (require 'org-src)
5269 (require 'org-footnote)
5270 (require 'org-macro)
5272 ;; babel
5273 (require 'ob)
5275 ;;;###autoload
5276 (define-derived-mode org-mode outline-mode "Org"
5277 "Outline-based notes management and organizer, alias
5278 \"Carsten's outline-mode for keeping track of everything.\"
5280 Org-mode develops organizational tasks around a NOTES file which
5281 contains information about projects as plain text. Org-mode is
5282 implemented on top of outline-mode, which is ideal to keep the content
5283 of large files well structured. It supports ToDo items, deadlines and
5284 time stamps, which magically appear in the diary listing of the Emacs
5285 calendar. Tables are easily created with a built-in table editor.
5286 Plain text URL-like links connect to websites, emails (VM), Usenet
5287 messages (Gnus), BBDB entries, and any files related to the project.
5288 For printing and sharing of notes, an Org-mode file (or a part of it)
5289 can be exported as a structured ASCII or HTML file.
5291 The following commands are available:
5293 \\{org-mode-map}"
5295 ;; Get rid of Outline menus, they are not needed
5296 ;; Need to do this here because define-derived-mode sets up
5297 ;; the keymap so late. Still, it is a waste to call this each time
5298 ;; we switch another buffer into org-mode.
5299 (if (featurep 'xemacs)
5300 (when (boundp 'outline-mode-menu-heading)
5301 ;; Assume this is Greg's port, it uses easymenu
5302 (easy-menu-remove outline-mode-menu-heading)
5303 (easy-menu-remove outline-mode-menu-show)
5304 (easy-menu-remove outline-mode-menu-hide))
5305 (define-key org-mode-map [menu-bar headings] 'undefined)
5306 (define-key org-mode-map [menu-bar hide] 'undefined)
5307 (define-key org-mode-map [menu-bar show] 'undefined))
5309 (org-load-modules-maybe)
5310 (easy-menu-add org-org-menu)
5311 (easy-menu-add org-tbl-menu)
5312 (org-install-agenda-files-menu)
5313 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5314 (add-to-invisibility-spec '(org-cwidth))
5315 (add-to-invisibility-spec '(org-hide-block . t))
5316 (when (featurep 'xemacs)
5317 (org-set-local 'line-move-ignore-invisible t))
5318 (org-set-local 'outline-regexp org-outline-regexp)
5319 (org-set-local 'outline-level 'org-outline-level)
5320 (setq bidi-paragraph-direction 'left-to-right)
5321 (when (and org-ellipsis
5322 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5323 (fboundp 'make-glyph-code))
5324 (unless org-display-table
5325 (setq org-display-table (make-display-table)))
5326 (set-display-table-slot
5327 org-display-table 4
5328 (vconcat (mapcar
5329 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5330 org-ellipsis)))
5331 (if (stringp org-ellipsis) org-ellipsis "..."))))
5332 (setq buffer-display-table org-display-table))
5333 (org-set-regexps-and-options-for-tags)
5334 (org-set-regexps-and-options)
5335 (org-set-font-lock-defaults)
5336 (when (and org-tag-faces (not org-tags-special-faces-re))
5337 ;; tag faces set outside customize.... force initialization.
5338 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5339 ;; Calc embedded
5340 (org-set-local 'calc-embedded-open-mode "# ")
5341 ;; Modify a few syntax entries
5342 (modify-syntax-entry ?@ "w")
5343 (modify-syntax-entry ?\" "\"")
5344 (if org-startup-truncated (setq truncate-lines t))
5345 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5346 (org-set-local 'font-lock-unfontify-region-function
5347 'org-unfontify-region)
5348 ;; Activate before-change-function
5349 (org-set-local 'org-table-may-need-update t)
5350 (org-add-hook 'before-change-functions 'org-before-change-function nil
5351 'local)
5352 ;; Check for running clock before killing a buffer
5353 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5354 ;; Initialize macros templates.
5355 (org-macro-initialize-templates)
5356 ;; Initialize radio targets.
5357 (org-update-radio-target-regexp)
5358 ;; Indentation.
5359 (org-set-local 'indent-line-function 'org-indent-line)
5360 (org-set-local 'indent-region-function 'org-indent-region)
5361 ;; Filling and auto-filling.
5362 (org-setup-filling)
5363 ;; Comments.
5364 (org-setup-comments-handling)
5365 ;; Beginning/end of defun
5366 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5367 (org-set-local 'end-of-defun-function 'org-forward-element)
5368 ;; Next error for sparse trees
5369 (org-set-local 'next-error-function 'org-occur-next-match)
5370 ;; Make sure dependence stuff works reliably, even for users who set it
5371 ;; too late :-(
5372 (if org-enforce-todo-dependencies
5373 (add-hook 'org-blocker-hook
5374 'org-block-todo-from-children-or-siblings-or-parent)
5375 (remove-hook 'org-blocker-hook
5376 'org-block-todo-from-children-or-siblings-or-parent))
5377 (if org-enforce-todo-checkbox-dependencies
5378 (add-hook 'org-blocker-hook
5379 'org-block-todo-from-checkboxes)
5380 (remove-hook 'org-blocker-hook
5381 'org-block-todo-from-checkboxes))
5383 ;; Align options lines
5384 (org-set-local
5385 'align-mode-rules-list
5386 '((org-in-buffer-settings
5387 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5388 (modes . '(org-mode)))))
5390 ;; Imenu
5391 (org-set-local 'imenu-create-index-function
5392 'org-imenu-get-tree)
5394 ;; Make isearch reveal context
5395 (if (or (featurep 'xemacs)
5396 (not (boundp 'outline-isearch-open-invisible-function)))
5397 ;; Emacs 21 and XEmacs make use of the hook
5398 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5399 ;; Emacs 22 deals with this through a special variable
5400 (org-set-local 'outline-isearch-open-invisible-function
5401 (lambda (&rest ignore) (org-show-context 'isearch)))
5402 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5404 ;; Setup the pcomplete hooks
5405 (set (make-local-variable 'pcomplete-command-completion-function)
5406 'org-pcomplete-initial)
5407 (set (make-local-variable 'pcomplete-command-name-function)
5408 'org-command-at-point)
5409 (set (make-local-variable 'pcomplete-default-completion-function)
5410 'ignore)
5411 (set (make-local-variable 'pcomplete-parse-arguments-function)
5412 'org-parse-arguments)
5413 (set (make-local-variable 'pcomplete-termination-string) "")
5414 (when (>= emacs-major-version 23)
5415 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5417 ;; If empty file that did not turn on org-mode automatically, make it to.
5418 (if (and org-insert-mode-line-in-empty-file
5419 (org-called-interactively-p 'any)
5420 (= (point-min) (point-max)))
5421 (insert "# -*- mode: org -*-\n\n"))
5422 (unless org-inhibit-startup
5423 (org-unmodified
5424 (and org-startup-with-beamer-mode (org-beamer-mode))
5425 (when org-startup-align-all-tables
5426 (org-table-map-tables 'org-table-align 'quietly))
5427 (when org-startup-with-inline-images
5428 (org-display-inline-images))
5429 (when org-startup-with-latex-preview
5430 (org-preview-latex-fragment))
5431 (unless org-inhibit-startup-visibility-stuff
5432 (org-set-startup-visibility))))
5433 ;; Try to set org-hide correctly
5434 (let ((foreground (org-find-invisible-foreground)))
5435 (if foreground
5436 (set-face-foreground 'org-hide foreground))))
5438 ;; Update `customize-package-emacs-version-alist'
5439 (add-to-list 'customize-package-emacs-version-alist
5440 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5441 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5442 ("8.2.6" . "24.4")))
5444 (defvar org-mode-transpose-word-syntax-table
5445 (let ((st (make-syntax-table)))
5446 (mapc (lambda(c) (modify-syntax-entry
5447 (string-to-char (car c)) "w p" st))
5448 org-emphasis-alist)
5449 st))
5451 (when (fboundp 'abbrev-table-put)
5452 (abbrev-table-put org-mode-abbrev-table
5453 :parents (list text-mode-abbrev-table)))
5455 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5457 (defsubst org-fix-ellipsis-at-bol ()
5458 (save-excursion (goto-char (window-start)) (recenter 0)))
5460 (defun org-find-invisible-foreground ()
5461 (let ((candidates (remove
5462 "unspecified-bg"
5463 (nconc
5464 (list (face-background 'default)
5465 (face-background 'org-default))
5466 (mapcar
5467 (lambda (alist)
5468 (when (boundp alist)
5469 (cdr (assoc 'background-color (symbol-value alist)))))
5470 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5471 (list (face-foreground 'org-hide))))))
5472 (car (remove nil candidates))))
5474 (defun org-current-time (&optional rounding-minutes past)
5475 "Current time, possibly rounded to ROUNDING-MINUTES.
5476 When ROUNDING-MINUTES is not an integer, fall back on the car of
5477 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5478 the rounding returns a past time."
5479 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5480 (car org-time-stamp-rounding-minutes)))
5481 (time (decode-time)) res)
5482 (if (< r 1)
5483 (current-time)
5484 (setq res
5485 (apply 'encode-time
5486 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5487 (nthcdr 2 time))))
5488 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5489 (seconds-to-time (- (org-float-time res) (* r 60)))
5490 res))))
5492 (defun org-today ()
5493 "Return today date, considering `org-extend-today-until'."
5494 (time-to-days
5495 (time-subtract (current-time)
5496 (list 0 (* 3600 org-extend-today-until) 0))))
5498 ;;;; Font-Lock stuff, including the activators
5500 (defvar org-mouse-map (make-sparse-keymap))
5501 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5502 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5503 (when org-mouse-1-follows-link
5504 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5505 (when org-tab-follows-link
5506 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5507 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5509 (require 'font-lock)
5511 (defconst org-non-link-chars "]\t\n\r<>")
5512 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5513 "shell" "elisp" "doi" "message"))
5514 (defvar org-link-types-re nil
5515 "Matches a link that has a url-like prefix like \"http:\"")
5516 (defvar org-link-re-with-space nil
5517 "Matches a link with spaces, optional angular brackets around it.")
5518 (defvar org-link-re-with-space2 nil
5519 "Matches a link with spaces, optional angular brackets around it.")
5520 (defvar org-link-re-with-space3 nil
5521 "Matches a link with spaces, only for internal part in bracket links.")
5522 (defvar org-angle-link-re nil
5523 "Matches link with angular brackets, spaces are allowed.")
5524 (defvar org-plain-link-re nil
5525 "Matches plain link, without spaces.")
5526 (defvar org-bracket-link-regexp nil
5527 "Matches a link in double brackets.")
5528 (defvar org-bracket-link-analytic-regexp nil
5529 "Regular expression used to analyze links.
5530 Here is what the match groups contain after a match:
5531 1: http:
5532 2: http
5533 3: path
5534 4: [desc]
5535 5: desc")
5536 (defvar org-bracket-link-analytic-regexp++ nil
5537 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5538 (defvar org-any-link-re nil
5539 "Regular expression matching any link.")
5541 (defconst org-match-sexp-depth 3
5542 "Number of stacked braces for sub/superscript matching.")
5544 (defun org-create-multibrace-regexp (left right n)
5545 "Create a regular expression which will match a balanced sexp.
5546 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5547 as single character strings.
5548 The regexp returned will match the entire expression including the
5549 delimiters. It will also define a single group which contains the
5550 match except for the outermost delimiters. The maximum depth of
5551 stacked delimiters is N. Escaping delimiters is not possible."
5552 (let* ((nothing (concat "[^" left right "]*?"))
5553 (or "\\|")
5554 (re nothing)
5555 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5556 (while (> n 1)
5557 (setq n (1- n)
5558 re (concat re or next)
5559 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5560 (concat left "\\(" re "\\)" right)))
5562 (defvar org-match-substring-regexp
5563 (concat
5564 "\\(\\S-\\)\\([_^]\\)\\("
5565 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5566 "\\|"
5567 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5568 "\\|"
5569 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5570 "The regular expression matching a sub- or superscript.")
5572 (defvar org-match-substring-with-braces-regexp
5573 (concat
5574 "\\(\\S-\\)\\([_^]\\)\\("
5575 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5576 "\\)")
5577 "The regular expression matching a sub- or superscript, forcing braces.")
5579 (defun org-make-link-regexps ()
5580 "Update the link regular expressions.
5581 This should be called after the variable `org-link-types' has changed."
5582 (setq org-link-types-re
5583 (concat
5584 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5585 org-link-re-with-space
5586 (concat
5587 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5588 "\\([^" org-non-link-chars " ]"
5589 "[^" org-non-link-chars "]*"
5590 "[^" org-non-link-chars " ]\\)>?")
5591 org-link-re-with-space2
5592 (concat
5593 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5594 "\\([^" org-non-link-chars " ]"
5595 "[^\t\n\r]*"
5596 "[^" org-non-link-chars " ]\\)>?")
5597 org-link-re-with-space3
5598 (concat
5599 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5600 "\\([^" org-non-link-chars " ]"
5601 "[^\t\n\r]*\\)")
5602 org-angle-link-re
5603 (concat
5604 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5605 "\\([^" org-non-link-chars " ]"
5606 "[^" org-non-link-chars "]*"
5607 "\\)>")
5608 org-plain-link-re
5609 (concat
5610 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5611 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5612 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5613 org-bracket-link-regexp
5614 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5615 org-bracket-link-analytic-regexp
5616 (concat
5617 "\\[\\["
5618 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5619 "\\([^]]+\\)"
5620 "\\]"
5621 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5622 "\\]")
5623 org-bracket-link-analytic-regexp++
5624 (concat
5625 "\\[\\["
5626 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5627 "\\([^]]+\\)"
5628 "\\]"
5629 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5630 "\\]")
5631 org-any-link-re
5632 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5633 org-angle-link-re "\\)\\|\\("
5634 org-plain-link-re "\\)")))
5636 (org-make-link-regexps)
5638 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5639 "Regular expression for fast time stamp matching.")
5640 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5641 "Regular expression for fast time stamp matching.")
5642 (defconst org-ts-regexp0
5643 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5644 "Regular expression matching time strings for analysis.
5645 This one does not require the space after the date, so it can be used
5646 on a string that terminates immediately after the date.")
5647 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5648 "Regular expression matching time strings for analysis.")
5649 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5650 "Regular expression matching time stamps, with groups.")
5651 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5652 "Regular expression matching time stamps (also [..]), with groups.")
5653 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5654 "Regular expression matching a time stamp range.")
5655 (defconst org-tr-regexp-both
5656 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5657 "Regular expression matching a time stamp range.")
5658 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5659 org-ts-regexp "\\)?")
5660 "Regular expression matching a time stamp or time stamp range.")
5661 (defconst org-tsr-regexp-both
5662 (concat org-ts-regexp-both "\\(--?-?"
5663 org-ts-regexp-both "\\)?")
5664 "Regular expression matching a time stamp or time stamp range.
5665 The time stamps may be either active or inactive.")
5667 (defvar org-emph-face nil)
5669 (defun org-do-emphasis-faces (limit)
5670 "Run through the buffer and add overlays to emphasized strings."
5671 (let (rtn a)
5672 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5673 (let* ((border (char-after (match-beginning 3)))
5674 (bre (regexp-quote (char-to-string border))))
5675 (if (and (not (= border (char-after (match-beginning 4))))
5676 (not (save-match-data
5677 (string-match (concat bre ".*" bre)
5678 (replace-regexp-in-string
5679 "\n" " "
5680 (substring (match-string 2) 1 -1))))))
5681 (progn
5682 (setq rtn t)
5683 (setq a (assoc (match-string 3) org-emphasis-alist))
5684 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5685 'face
5686 (nth 1 a))
5687 (and (nth 2 a)
5688 (org-remove-flyspell-overlays-in
5689 (match-beginning 0) (match-end 0)))
5690 (add-text-properties (match-beginning 2) (match-end 2)
5691 '(font-lock-multiline t org-emphasis t))
5692 (when org-hide-emphasis-markers
5693 (add-text-properties (match-end 4) (match-beginning 5)
5694 '(invisible org-link))
5695 (add-text-properties (match-beginning 3) (match-end 3)
5696 '(invisible org-link))))))
5697 (goto-char (1+ (match-beginning 0))))
5698 rtn))
5700 (defun org-emphasize (&optional char)
5701 "Insert or change an emphasis, i.e. a font like bold or italic.
5702 If there is an active region, change that region to a new emphasis.
5703 If there is no region, just insert the marker characters and position
5704 the cursor between them.
5705 CHAR should be the marker character. If it is a space, it means to
5706 remove the emphasis of the selected region.
5707 If CHAR is not given (for example in an interactive call) it will be
5708 prompted for."
5709 (interactive)
5710 (let ((erc org-emphasis-regexp-components)
5711 (prompt "")
5712 (string "") beg end move c s)
5713 (if (org-region-active-p)
5714 (setq beg (region-beginning) end (region-end)
5715 string (buffer-substring beg end))
5716 (setq move t))
5718 (unless char
5719 (message "Emphasis marker or tag: [%s]"
5720 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5721 (setq char (read-char-exclusive)))
5722 (if (equal char ?\ )
5723 (setq s "" move nil)
5724 (unless (assoc (char-to-string char) org-emphasis-alist)
5725 (user-error "No such emphasis marker: \"%c\"" char))
5726 (setq s (char-to-string char)))
5727 (while (and (> (length string) 1)
5728 (equal (substring string 0 1) (substring string -1))
5729 (assoc (substring string 0 1) org-emphasis-alist))
5730 (setq string (substring string 1 -1)))
5731 (setq string (concat s string s))
5732 (if beg (delete-region beg end))
5733 (unless (or (bolp)
5734 (string-match (concat "[" (nth 0 erc) "\n]")
5735 (char-to-string (char-before (point)))))
5736 (insert " "))
5737 (unless (or (eobp)
5738 (string-match (concat "[" (nth 1 erc) "\n]")
5739 (char-to-string (char-after (point)))))
5740 (insert " ") (backward-char 1))
5741 (insert string)
5742 (and move (backward-char 1))))
5744 (defconst org-nonsticky-props
5745 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5747 (defsubst org-rear-nonsticky-at (pos)
5748 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5750 (defun org-activate-plain-links (limit)
5751 "Run through the buffer and add overlays to links."
5752 (let (f hl)
5753 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5754 (not (org-in-src-block-p)))
5755 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5756 (setq f (get-text-property (match-beginning 0) 'face))
5757 (setq hl (org-match-string-no-properties 0))
5758 (if (or (eq f 'org-tag)
5759 (and (listp f) (memq 'org-tag f)))
5761 (add-text-properties (match-beginning 0) (match-end 0)
5762 (list 'mouse-face 'highlight
5763 'face 'org-link
5764 'htmlize-link `(:uri ,hl)
5765 'keymap org-mouse-map))
5766 (org-rear-nonsticky-at (match-end 0)))
5767 t)))
5769 (defun org-activate-code (limit)
5770 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5771 (progn
5772 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5773 (remove-text-properties (match-beginning 0) (match-end 0)
5774 '(display t invisible t intangible t))
5775 t)))
5777 (defcustom org-src-fontify-natively nil
5778 "When non-nil, fontify code in code blocks."
5779 :type 'boolean
5780 :version "24.1"
5781 :group 'org-appearance
5782 :group 'org-babel)
5784 (defcustom org-allow-promoting-top-level-subtree nil
5785 "When non-nil, allow promoting a top level subtree.
5786 The leading star of the top level headline will be replaced
5787 by a #."
5788 :type 'boolean
5789 :version "24.1"
5790 :group 'org-appearance)
5792 (defun org-fontify-meta-lines-and-blocks (limit)
5793 (condition-case nil
5794 (org-fontify-meta-lines-and-blocks-1 limit)
5795 (error (message "org-mode fontification error"))))
5797 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5798 "Fontify #+ lines and blocks."
5799 (let ((case-fold-search t))
5800 (if (re-search-forward
5801 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5802 limit t)
5803 (let ((beg (match-beginning 0))
5804 (block-start (match-end 0))
5805 (block-end nil)
5806 (lang (match-string 7))
5807 (beg1 (line-beginning-position 2))
5808 (dc1 (downcase (match-string 2)))
5809 (dc3 (downcase (match-string 3)))
5810 end end1 quoting block-type ovl)
5811 (cond
5812 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5813 ;; a single line of backend-specific content
5814 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5815 (remove-text-properties (match-beginning 0) (match-end 0)
5816 '(display t invisible t intangible t))
5817 (add-text-properties (match-beginning 1) (match-end 3)
5818 '(font-lock-fontified t face org-meta-line))
5819 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5820 '(font-lock-fontified t face org-block))
5821 ; for backend-specific code
5823 ((and (match-end 4) (equal dc3 "+begin"))
5824 ;; Truly a block
5825 (setq block-type (downcase (match-string 5))
5826 quoting (member block-type org-protecting-blocks))
5827 (when (re-search-forward
5828 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5829 nil t) ;; on purpose, we look further than LIMIT
5830 (setq end (min (point-max) (match-end 0))
5831 end1 (min (point-max) (1- (match-beginning 0))))
5832 (setq block-end (match-beginning 0))
5833 (when quoting
5834 (remove-text-properties beg end
5835 '(display t invisible t intangible t)))
5836 (add-text-properties
5837 beg end
5838 '(font-lock-fontified t font-lock-multiline t))
5839 (add-text-properties beg beg1 '(face org-meta-line))
5840 (add-text-properties end1 (min (point-max) (1+ end))
5841 '(face org-meta-line)) ; for end_src
5842 (cond
5843 ((and lang (not (string= lang "")) org-src-fontify-natively)
5844 (org-src-font-lock-fontify-block lang block-start block-end)
5845 ;; remove old background overlays
5846 (mapc (lambda (ov)
5847 (if (eq (overlay-get ov 'face) 'org-block-background)
5848 (delete-overlay ov)))
5849 (overlays-at (/ (+ beg1 block-end) 2)))
5850 ;; add a background overlay
5851 (setq ovl (make-overlay beg1 block-end))
5852 (overlay-put ovl 'face 'org-block-background)
5853 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5854 (quoting
5855 (add-text-properties beg1 (min (point-max) (1+ end1))
5856 '(face org-block))) ; end of source block
5857 ((not org-fontify-quote-and-verse-blocks))
5858 ((string= block-type "quote")
5859 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5860 ((string= block-type "verse")
5861 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5862 (add-text-properties beg beg1 '(face org-block-begin-line))
5863 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5864 '(face org-block-end-line))
5866 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5867 (add-text-properties
5868 beg (match-end 3)
5869 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5870 '(font-lock-fontified t invisible t)
5871 '(font-lock-fontified t face org-document-info-keyword)))
5872 (add-text-properties
5873 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5874 (if (string-equal dc1 "+title:")
5875 '(font-lock-fontified t face org-document-title)
5876 '(font-lock-fontified t face org-document-info))))
5877 ((or (equal dc1 "+results")
5878 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5879 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5880 "+call:" "+header:" "+headers:" "+name:"))
5881 (and (match-end 4) (equal dc3 "+attr")))
5882 (add-text-properties
5883 beg (match-end 0)
5884 '(font-lock-fontified t face org-meta-line))
5886 ((member dc3 '(" " ""))
5887 (add-text-properties
5888 beg (match-end 0)
5889 '(font-lock-fontified t face font-lock-comment-face)))
5890 ((not (member (char-after beg) '(?\ ?\t)))
5891 ;; just any other in-buffer setting, but not indented
5892 (add-text-properties
5893 beg (match-end 0)
5894 '(font-lock-fontified t face org-meta-line))
5896 (t nil))))))
5898 (defun org-activate-angle-links (limit)
5899 "Run through the buffer and add overlays to links."
5900 (if (and (re-search-forward org-angle-link-re limit t)
5901 (not (org-in-src-block-p)))
5902 (progn
5903 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5904 (add-text-properties (match-beginning 0) (match-end 0)
5905 (list 'mouse-face 'highlight
5906 'keymap org-mouse-map))
5907 (org-rear-nonsticky-at (match-end 0))
5908 t)))
5910 (defun org-activate-footnote-links (limit)
5911 "Run through the buffer and add overlays to footnotes."
5912 (let ((fn (org-footnote-next-reference-or-definition limit)))
5913 (when fn
5914 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5915 (org-remove-flyspell-overlays-in beg end)
5916 (add-text-properties beg end
5917 (list 'mouse-face 'highlight
5918 'keymap org-mouse-map
5919 'help-echo
5920 (if (= (point-at-bol) beg)
5921 "Footnote definition"
5922 "Footnote reference")
5923 'font-lock-fontified t
5924 'font-lock-multiline t
5925 'face 'org-footnote))))))
5927 (defun org-activate-bracket-links (limit)
5928 "Run through the buffer and add overlays to bracketed links."
5929 (if (and (re-search-forward org-bracket-link-regexp limit t)
5930 (not (org-in-src-block-p)))
5931 (let* ((hl (org-match-string-no-properties 1))
5932 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
5933 (ip (org-maybe-intangible
5934 (list 'invisible 'org-link
5935 'keymap org-mouse-map 'mouse-face 'highlight
5936 'font-lock-multiline t 'help-echo help
5937 'htmlize-link `(:uri ,hl))))
5938 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5939 'font-lock-multiline t 'help-echo help
5940 'htmlize-link `(:uri ,hl))))
5941 ;; We need to remove the invisible property here. Table narrowing
5942 ;; may have made some of this invisible.
5943 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5944 (remove-text-properties (match-beginning 0) (match-end 0)
5945 '(invisible nil))
5946 (if (match-end 3)
5947 (progn
5948 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5949 (org-rear-nonsticky-at (match-beginning 3))
5950 (add-text-properties (match-beginning 3) (match-end 3) vp)
5951 (org-rear-nonsticky-at (match-end 3))
5952 (add-text-properties (match-end 3) (match-end 0) ip)
5953 (org-rear-nonsticky-at (match-end 0)))
5954 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5955 (org-rear-nonsticky-at (match-beginning 1))
5956 (add-text-properties (match-beginning 1) (match-end 1) vp)
5957 (org-rear-nonsticky-at (match-end 1))
5958 (add-text-properties (match-end 1) (match-end 0) ip)
5959 (org-rear-nonsticky-at (match-end 0)))
5960 t)))
5962 (defun org-activate-dates (limit)
5963 "Run through the buffer and add overlays to dates."
5964 (if (and (re-search-forward org-tsr-regexp-both limit t)
5965 (not (equal (char-before (match-beginning 0)) 91)))
5966 (progn
5967 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5968 (add-text-properties (match-beginning 0) (match-end 0)
5969 (list 'mouse-face 'highlight
5970 'keymap org-mouse-map))
5971 (org-rear-nonsticky-at (match-end 0))
5972 (when org-display-custom-times
5973 (if (match-end 3)
5974 (org-display-custom-time (match-beginning 3) (match-end 3)))
5975 (org-display-custom-time (match-beginning 1) (match-end 1)))
5976 t)))
5978 (defvar org-target-link-regexp nil
5979 "Regular expression matching radio targets in plain text.")
5980 (make-variable-buffer-local 'org-target-link-regexp)
5981 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5982 "Regular expression matching a link target.")
5983 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5984 "Regular expression matching a radio target.")
5985 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5986 "Regular expression matching any target.")
5988 (defun org-activate-target-links (limit)
5989 "Run through the buffer and add overlays to target matches."
5990 (when org-target-link-regexp
5991 (let ((case-fold-search t))
5992 (if (re-search-forward org-target-link-regexp limit t)
5993 (progn
5994 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5995 (add-text-properties (match-beginning 0) (match-end 0)
5996 (list 'mouse-face 'highlight
5997 'keymap org-mouse-map
5998 'help-echo "Radio target link"
5999 'org-linked-text t))
6000 (org-rear-nonsticky-at (match-end 0))
6001 t)))))
6003 (defun org-update-radio-target-regexp ()
6004 "Find all radio targets in this file and update the regular expression."
6005 (interactive)
6006 (when (memq 'radio org-activate-links)
6007 (setq org-target-link-regexp
6008 (org-make-target-link-regexp (org-all-targets 'radio)))
6009 (org-restart-font-lock)))
6011 (defun org-hide-wide-columns (limit)
6012 (let (s e)
6013 (setq s (text-property-any (point) (or limit (point-max))
6014 'org-cwidth t))
6015 (when s
6016 (setq e (next-single-property-change s 'org-cwidth))
6017 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6018 (goto-char e)
6019 t)))
6021 (defvar org-latex-and-related-regexp nil
6022 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6023 (defvar org-match-substring-regexp)
6024 (defvar org-match-substring-with-braces-regexp)
6026 (defun org-compute-latex-and-related-regexp ()
6027 "Compute regular expression for LaTeX, entities and sub/superscript.
6028 Result depends on variable `org-highlight-latex-and-related'."
6029 (org-set-local
6030 'org-latex-and-related-regexp
6031 (let* ((re-sub
6032 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6033 ((eq org-use-sub-superscripts '{})
6034 (list org-match-substring-with-braces-regexp))
6035 (org-use-sub-superscripts (list org-match-substring-regexp))))
6036 (re-latex
6037 (when (memq 'latex org-highlight-latex-and-related)
6038 (let ((matchers (plist-get org-format-latex-options :matchers)))
6039 (delq nil
6040 (mapcar (lambda (x)
6041 (and (member (car x) matchers) (nth 1 x)))
6042 org-latex-regexps)))))
6043 (re-entities
6044 (when (memq 'entities org-highlight-latex-and-related)
6045 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6046 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6048 (defun org-do-latex-and-related (limit)
6049 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6050 LIMIT bounds the search for syntax to highlight. Stop at first
6051 highlighted object, if any. Return t if some highlighting was
6052 done, nil otherwise."
6053 (when (org-string-nw-p org-latex-and-related-regexp)
6054 (catch 'found
6055 (while (re-search-forward org-latex-and-related-regexp limit t)
6056 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6057 'face))
6058 '(org-code org-verbatim underline))
6059 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6060 '(?_ ?^))
6062 0)))
6063 (font-lock-prepend-text-property
6064 (+ offset (match-beginning 0)) (match-end 0)
6065 'face 'org-latex-and-related)
6066 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6067 '(font-lock-multiline t)))
6068 (throw 'found t)))
6069 nil)))
6071 (defun org-restart-font-lock ()
6072 "Restart `font-lock-mode', to force refontification."
6073 (when (and (boundp 'font-lock-mode) font-lock-mode)
6074 (font-lock-mode -1)
6075 (font-lock-mode 1)))
6077 (defun org-all-targets (&optional radio)
6078 "Return a list of all targets in this file.
6079 When optional argument RADIO is non-nil, only find radio
6080 targets."
6081 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
6082 (save-excursion
6083 (goto-char (point-min))
6084 (while (re-search-forward re nil t)
6085 ;; Make sure point is really within the object.
6086 (backward-char)
6087 (let ((obj (org-element-context)))
6088 (when (memq (org-element-type obj) '(radio-target target))
6089 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
6090 rtn)))
6092 (defun org-make-target-link-regexp (targets)
6093 "Make regular expression matching all strings in TARGETS.
6094 The regular expression finds the targets also if there is a line break
6095 between words."
6096 (and targets
6097 (concat
6098 "\\<\\("
6099 (mapconcat
6100 (lambda (x)
6101 (setq x (regexp-quote x))
6102 (while (string-match " +" x)
6103 (setq x (replace-match "\\s-+" t t x)))
6105 targets
6106 "\\|")
6107 "\\)\\>")))
6109 (defun org-activate-tags (limit)
6110 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6111 (progn
6112 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6113 (add-text-properties (match-beginning 1) (match-end 1)
6114 (list 'mouse-face 'highlight
6115 'keymap org-mouse-map))
6116 (org-rear-nonsticky-at (match-end 1))
6117 t)))
6119 (defun org-outline-level ()
6120 "Compute the outline level of the heading at point.
6121 If this is called at a normal headline, the level is the number of stars.
6122 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6123 (save-excursion
6124 (if (not (condition-case nil
6125 (org-back-to-heading t)
6126 (error nil)))
6128 (looking-at org-outline-regexp)
6129 (1- (- (match-end 0) (match-beginning 0))))))
6131 (defvar org-font-lock-keywords nil)
6133 (defsubst org-re-property (property &optional literal)
6134 "Return a regexp matching a PROPERTY line.
6135 Match group 3 will be set to the value if it exists."
6136 (concat "^\\(?4:[ \t]*\\)\\(?1::\\(?2:"
6137 (if literal property (regexp-quote property))
6138 "\\):\\)[ \t]+\\(?3:[^ \t\r\n].*?\\)\\(?5:[ \t]*\\)$"))
6140 (defconst org-property-re
6141 (org-re-property ".*?" 'literal)
6142 "Regular expression matching a property line.
6143 There are four matching groups:
6144 1: :PROPKEY: including the leading and trailing colon,
6145 2: PROPKEY without the leading and trailing colon,
6146 3: PROPVAL without leading or trailing spaces,
6147 4: the indentation of the current line,
6148 5: trailing whitespace.")
6150 (defvar org-font-lock-hook nil
6151 "Functions to be called for special font lock stuff.")
6153 (defvar org-font-lock-set-keywords-hook nil
6154 "Functions that can manipulate `org-font-lock-extra-keywords'.
6155 This is called after `org-font-lock-extra-keywords' is defined, but before
6156 it is installed to be used by font lock. This can be useful if something
6157 needs to be inserted at a specific position in the font-lock sequence.")
6159 (defun org-font-lock-hook (limit)
6160 "Run `org-font-lock-hook' within LIMIT."
6161 (run-hook-with-args 'org-font-lock-hook limit))
6163 (defun org-set-font-lock-defaults ()
6164 "Set font lock defaults for the current buffer."
6165 (let* ((em org-fontify-emphasized-text)
6166 (lk org-activate-links)
6167 (org-font-lock-extra-keywords
6168 (list
6169 ;; Call the hook
6170 '(org-font-lock-hook)
6171 ;; Headlines
6172 `(,(if org-fontify-whole-heading-line
6173 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6174 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6175 (1 (org-get-level-face 1))
6176 (2 (org-get-level-face 2))
6177 (3 (org-get-level-face 3)))
6178 ;; Table lines
6179 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6180 (1 'org-table t))
6181 ;; Table internals
6182 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6183 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6184 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6185 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6186 ;; Drawers
6187 (list org-drawer-regexp '(0 'org-special-keyword t))
6188 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
6189 ;; Properties
6190 (list org-property-re
6191 '(1 'org-special-keyword t)
6192 '(3 'org-property-value t))
6193 ;; Links
6194 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6195 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6196 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6197 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6198 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6199 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6200 (if (memq 'footnote lk) '(org-activate-footnote-links))
6201 ;; Targets.
6202 (list org-any-target-regexp '(0 'org-target t))
6203 ;; Diary sexps.
6204 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6205 ;; Macro
6206 '("{{{.+}}}" (0 'org-macro t))
6207 '(org-hide-wide-columns (0 nil append))
6208 ;; TODO keyword
6209 (list (format org-heading-keyword-regexp-format
6210 org-todo-regexp)
6211 '(2 (org-get-todo-face 2) t))
6212 ;; DONE
6213 (if org-fontify-done-headline
6214 (list (format org-heading-keyword-regexp-format
6215 (concat
6216 "\\(?:"
6217 (mapconcat 'regexp-quote org-done-keywords "\\|")
6218 "\\)"))
6219 '(2 'org-headline-done t))
6220 nil)
6221 ;; Priorities
6222 '(org-font-lock-add-priority-faces)
6223 ;; Tags
6224 '(org-font-lock-add-tag-faces)
6225 ;; Tags groups
6226 (if (and org-group-tags org-tag-groups-alist)
6227 (list (concat org-outline-regexp-bol ".+\\(:"
6228 (regexp-opt (mapcar 'car org-tag-groups-alist))
6229 ":\\).*$")
6230 '(1 'org-tag-group prepend)))
6231 ;; Special keywords
6232 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6233 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6234 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6235 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6236 ;; Emphasis
6237 (if em
6238 (if (featurep 'xemacs)
6239 '(org-do-emphasis-faces (0 nil append))
6240 '(org-do-emphasis-faces)))
6241 ;; Checkboxes
6242 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6243 1 'org-checkbox prepend)
6244 (if (cdr (assq 'checkbox org-list-automatic-rules))
6245 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6246 (0 (org-get-checkbox-statistics-face) t)))
6247 ;; Description list items
6248 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6249 1 'org-list-dt prepend)
6250 ;; ARCHIVEd headings
6251 (list (concat
6252 org-outline-regexp-bol
6253 "\\(.*:" org-archive-tag ":.*\\)")
6254 '(1 'org-archived prepend))
6255 ;; Specials
6256 '(org-do-latex-and-related)
6257 '(org-fontify-entities)
6258 '(org-raise-scripts)
6259 ;; Code
6260 '(org-activate-code (1 'org-code t))
6261 ;; COMMENT
6262 (list (format org-heading-keyword-regexp-format
6263 (concat "\\("
6264 org-comment-string "\\|" org-quote-string
6265 "\\)"))
6266 '(2 'org-special-keyword t))
6267 ;; Blocks and meta lines
6268 '(org-fontify-meta-lines-and-blocks))))
6269 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6270 (run-hooks 'org-font-lock-set-keywords-hook)
6271 ;; Now set the full font-lock-keywords
6272 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6273 (org-set-local 'font-lock-defaults
6274 '(org-font-lock-keywords t nil nil backward-paragraph))
6275 (kill-local-variable 'font-lock-keywords) nil))
6277 (defun org-toggle-pretty-entities ()
6278 "Toggle the composition display of entities as UTF8 characters."
6279 (interactive)
6280 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6281 (org-restart-font-lock)
6282 (if org-pretty-entities
6283 (message "Entities are now displayed as UTF8 characters")
6284 (save-restriction
6285 (widen)
6286 (org-decompose-region (point-min) (point-max))
6287 (message "Entities are now displayed as plain text"))))
6289 (defvar org-custom-properties-overlays nil
6290 "List of overlays used for custom properties.")
6291 (make-variable-buffer-local 'org-custom-properties-overlays)
6293 (defun org-toggle-custom-properties-visibility ()
6294 "Display or hide properties in `org-custom-properties'."
6295 (interactive)
6296 (if org-custom-properties-overlays
6297 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6298 (setq org-custom-properties-overlays nil))
6299 (unless (not org-custom-properties)
6300 (save-excursion
6301 (save-restriction
6302 (widen)
6303 (goto-char (point-min))
6304 (while (re-search-forward org-property-re nil t)
6305 (mapc (lambda(p)
6306 (when (equal p (substring (match-string 1) 1 -1))
6307 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6308 (overlay-put o 'invisible t)
6309 (overlay-put o 'org-custom-property t)
6310 (push o org-custom-properties-overlays))))
6311 org-custom-properties)))))))
6313 (defun org-fontify-entities (limit)
6314 "Find an entity to fontify."
6315 (let (ee)
6316 (when org-pretty-entities
6317 (catch 'match
6318 (while (re-search-forward
6319 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6320 limit t)
6321 (if (and (not (org-in-indented-comment-line))
6322 (setq ee (org-entity-get (match-string 1)))
6323 (= (length (nth 6 ee)) 1))
6324 (let*
6325 ((end (if (equal (match-string 2) "{}")
6326 (match-end 2)
6327 (match-end 1))))
6328 (add-text-properties
6329 (match-beginning 0) end
6330 (list 'font-lock-fontified t))
6331 (compose-region (match-beginning 0) end
6332 (nth 6 ee) nil)
6333 (backward-char 1)
6334 (throw 'match t))))
6335 nil))))
6337 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6338 "Fontify string S like in Org-mode."
6339 (with-temp-buffer
6340 (insert s)
6341 (let ((org-odd-levels-only odd-levels))
6342 (org-mode)
6343 (font-lock-fontify-buffer)
6344 (buffer-string))))
6346 (defvar org-m nil)
6347 (defvar org-l nil)
6348 (defvar org-f nil)
6349 (defun org-get-level-face (n)
6350 "Get the right face for match N in font-lock matching of headlines."
6351 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6352 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6353 (if org-cycle-level-faces
6354 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6355 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6356 (cond
6357 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6358 ((eq n 2) org-f)
6359 (t (if org-level-color-stars-only nil org-f))))
6362 (defun org-get-todo-face (kwd)
6363 "Get the right face for a TODO keyword KWD.
6364 If KWD is a number, get the corresponding match group."
6365 (if (numberp kwd) (setq kwd (match-string kwd)))
6366 (or (org-face-from-face-or-color
6367 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6368 (and (member kwd org-done-keywords) 'org-done)
6369 'org-todo))
6371 (defun org-face-from-face-or-color (context inherit face-or-color)
6372 "Create a face list that inherits INHERIT, but sets the foreground color.
6373 When FACE-OR-COLOR is not a string, just return it."
6374 (if (stringp face-or-color)
6375 (list :inherit inherit
6376 (cdr (assoc context org-faces-easy-properties))
6377 face-or-color)
6378 face-or-color))
6380 (defun org-font-lock-add-tag-faces (limit)
6381 "Add the special tag faces."
6382 (when (and org-tag-faces org-tags-special-faces-re)
6383 (while (re-search-forward org-tags-special-faces-re limit t)
6384 (add-text-properties (match-beginning 1) (match-end 1)
6385 (list 'face (org-get-tag-face 1)
6386 'font-lock-fontified t))
6387 (backward-char 1))))
6389 (defun org-font-lock-add-priority-faces (limit)
6390 "Add the special priority faces."
6391 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6392 (when (save-match-data (org-at-heading-p))
6393 (add-text-properties
6394 (match-beginning 0) (match-end 0)
6395 (list 'face (or (org-face-from-face-or-color
6396 'priority 'org-priority
6397 (cdr (assoc (char-after (match-beginning 1))
6398 org-priority-faces)))
6399 'org-priority)
6400 'font-lock-fontified t)))))
6402 (defun org-get-tag-face (kwd)
6403 "Get the right face for a TODO keyword KWD.
6404 If KWD is a number, get the corresponding match group."
6405 (if (numberp kwd) (setq kwd (match-string kwd)))
6406 (or (org-face-from-face-or-color
6407 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6408 'org-tag))
6410 (defun org-unfontify-region (beg end &optional maybe_loudly)
6411 "Remove fontification and activation overlays from links."
6412 (font-lock-default-unfontify-region beg end)
6413 (let* ((buffer-undo-list t)
6414 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6415 (inhibit-modification-hooks t)
6416 deactivate-mark buffer-file-name buffer-file-truename)
6417 (org-decompose-region beg end)
6418 (remove-text-properties beg end
6419 '(mouse-face t keymap t org-linked-text t
6420 invisible t intangible t
6421 org-no-flyspell t org-emphasis t))
6422 (org-remove-font-lock-display-properties beg end)))
6424 (defconst org-script-display '(((raise -0.3) (height 0.7))
6425 ((raise 0.3) (height 0.7))
6426 ((raise -0.5))
6427 ((raise 0.5)))
6428 "Display properties for showing superscripts and subscripts.")
6430 (defun org-remove-font-lock-display-properties (beg end)
6431 "Remove specific display properties that have been added by font lock.
6432 The will remove the raise properties that are used to show superscripts
6433 and subscripts."
6434 (let (next prop)
6435 (while (< beg end)
6436 (setq next (next-single-property-change beg 'display nil end)
6437 prop (get-text-property beg 'display))
6438 (if (member prop org-script-display)
6439 (put-text-property beg next 'display nil))
6440 (setq beg next))))
6442 (defun org-raise-scripts (limit)
6443 "Add raise properties to sub/superscripts."
6444 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6445 (if (re-search-forward
6446 (if (eq org-use-sub-superscripts t)
6447 org-match-substring-regexp
6448 org-match-substring-with-braces-regexp)
6449 limit t)
6450 (let* ((pos (point)) table-p comment-p
6451 (mpos (match-beginning 3))
6452 (emph-p (get-text-property mpos 'org-emphasis))
6453 (link-p (get-text-property mpos 'mouse-face))
6454 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6455 (goto-char (point-at-bol))
6456 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6457 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6458 (goto-char pos)
6459 ;; Handle a_b^c
6460 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6461 (if (or comment-p emph-p link-p keyw-p)
6463 (put-text-property (match-beginning 3) (match-end 0)
6464 'display
6465 (if (equal (char-after (match-beginning 2)) ?^)
6466 (nth (if table-p 3 1) org-script-display)
6467 (nth (if table-p 2 0) org-script-display)))
6468 (add-text-properties (match-beginning 2) (match-end 2)
6469 (list 'invisible t
6470 'org-dwidth t 'org-dwidth-n 1))
6471 (if (and (eq (char-after (match-beginning 3)) ?{)
6472 (eq (char-before (match-end 3)) ?}))
6473 (progn
6474 (add-text-properties
6475 (match-beginning 3) (1+ (match-beginning 3))
6476 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6477 (add-text-properties
6478 (1- (match-end 3)) (match-end 3)
6479 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6480 t)))))
6482 ;;;; Visibility cycling, including org-goto and indirect buffer
6484 ;;; Cycling
6486 (defvar org-cycle-global-status nil)
6487 (make-variable-buffer-local 'org-cycle-global-status)
6488 (put 'org-cycle-global-status 'org-state t)
6489 (defvar org-cycle-subtree-status nil)
6490 (make-variable-buffer-local 'org-cycle-subtree-status)
6491 (put 'org-cycle-subtree-status 'org-state t)
6493 (defvar org-inlinetask-min-level)
6495 (defun org-unlogged-message (&rest args)
6496 "Display a message, but avoid logging it in the *Messages* buffer."
6497 (let ((message-log-max nil))
6498 (apply 'message args)))
6500 ;;;###autoload
6501 (defun org-cycle (&optional arg)
6502 "TAB-action and visibility cycling for Org-mode.
6504 This is the command invoked in Org-mode by the TAB key. Its main purpose
6505 is outline visibility cycling, but it also invokes other actions
6506 in special contexts.
6508 - When this function is called with a prefix argument, rotate the entire
6509 buffer through 3 states (global cycling)
6510 1. OVERVIEW: Show only top-level headlines.
6511 2. CONTENTS: Show all headlines of all levels, but no body text.
6512 3. SHOW ALL: Show everything.
6513 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6514 determined by the variable `org-startup-folded', and by any VISIBILITY
6515 properties in the buffer.
6516 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6517 including any drawers.
6519 - When inside a table, re-align the table and move to the next field.
6521 - When point is at the beginning of a headline, rotate the subtree started
6522 by this line through 3 different states (local cycling)
6523 1. FOLDED: Only the main headline is shown.
6524 2. CHILDREN: The main headline and the direct children are shown.
6525 From this state, you can move to one of the children
6526 and zoom in further.
6527 3. SUBTREE: Show the entire subtree, including body text.
6528 If there is no subtree, switch directly from CHILDREN to FOLDED.
6530 - When point is at the beginning of an empty headline and the variable
6531 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6532 of the headline by demoting and promoting it to likely levels. This
6533 speeds up creation document structure by pressing TAB once or several
6534 times right after creating a new headline.
6536 - When there is a numeric prefix, go up to a heading with level ARG, do
6537 a `show-subtree' and return to the previous cursor position. If ARG
6538 is negative, go up that many levels.
6540 - When point is not at the beginning of a headline, execute the global
6541 binding for TAB, which is re-indenting the line. See the option
6542 `org-cycle-emulate-tab' for details.
6544 - Special case: if point is at the beginning of the buffer and there is
6545 no headline in line 1, this function will act as if called with prefix arg
6546 (C-u TAB, same as S-TAB) also when called without prefix arg.
6547 But only if also the variable `org-cycle-global-at-bob' is t."
6548 (interactive "P")
6549 (org-load-modules-maybe)
6550 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6551 (and org-cycle-level-after-item/entry-creation
6552 (or (org-cycle-level)
6553 (org-cycle-item-indentation))))
6554 (let* ((limit-level
6555 (or org-cycle-max-level
6556 (and (boundp 'org-inlinetask-min-level)
6557 org-inlinetask-min-level
6558 (1- org-inlinetask-min-level))))
6559 (nstars (and limit-level
6560 (if org-odd-levels-only
6561 (and limit-level (1- (* limit-level 2)))
6562 limit-level)))
6563 (org-outline-regexp
6564 (if (not (derived-mode-p 'org-mode))
6565 outline-regexp
6566 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6567 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6568 (not (looking-at org-outline-regexp))))
6569 (org-cycle-hook
6570 (if bob-special
6571 (delq 'org-optimize-window-after-visibility-change
6572 (copy-sequence org-cycle-hook))
6573 org-cycle-hook))
6574 (pos (point)))
6576 (if (or bob-special (equal arg '(4)))
6577 ;; special case: use global cycling
6578 (setq arg t))
6580 (cond
6582 ((equal arg '(16))
6583 (setq last-command 'dummy)
6584 (org-set-startup-visibility)
6585 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6587 ((equal arg '(64))
6588 (show-all)
6589 (org-unlogged-message "Entire buffer visible, including drawers"))
6591 ;; Table: enter it or move to the next field.
6592 ((org-at-table-p 'any)
6593 (if (org-at-table.el-p)
6594 (message "Use C-c ' to edit table.el tables")
6595 (if arg (org-table-edit-field t)
6596 (org-table-justify-field-maybe)
6597 (call-interactively 'org-table-next-field))))
6599 ((run-hook-with-args-until-success
6600 'org-tab-after-check-for-table-hook))
6602 ;; Global cycling: delegate to `org-cycle-internal-global'.
6603 ((eq arg t) (org-cycle-internal-global))
6605 ;; Drawers: delegate to `org-flag-drawer'.
6606 ((and org-drawers org-drawer-regexp
6607 (save-excursion
6608 (beginning-of-line 1)
6609 (looking-at org-drawer-regexp)))
6610 (org-flag-drawer ; toggle block visibility
6611 (not (get-char-property (match-end 0) 'invisible))))
6613 ;; Show-subtree, ARG levels up from here.
6614 ((integerp arg)
6615 (save-excursion
6616 (org-back-to-heading)
6617 (outline-up-heading (if (< arg 0) (- arg)
6618 (- (funcall outline-level) arg)))
6619 (org-show-subtree)))
6621 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6622 ((and (featurep 'org-inlinetask)
6623 (org-inlinetask-at-task-p)
6624 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6625 (org-inlinetask-toggle-visibility))
6627 ((org-try-cdlatex-tab))
6629 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6630 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6631 (save-excursion (beginning-of-line 1)
6632 (looking-at org-outline-regexp)))
6633 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6634 (org-cycle-internal-local))
6636 ;; From there: TAB emulation and template completion.
6637 (buffer-read-only (org-back-to-heading))
6639 ((run-hook-with-args-until-success
6640 'org-tab-after-check-for-cycling-hook))
6642 ((org-try-structure-completion))
6644 ((run-hook-with-args-until-success
6645 'org-tab-before-tab-emulation-hook))
6647 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6648 (or (not (bolp))
6649 (not (looking-at org-outline-regexp))))
6650 (call-interactively (global-key-binding "\t")))
6652 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6653 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6654 (or (and (eq org-cycle-emulate-tab 'white)
6655 (= (match-end 0) (point-at-eol)))
6656 (and (eq org-cycle-emulate-tab 'whitestart)
6657 (>= (match-end 0) pos))))
6659 (eq org-cycle-emulate-tab t))
6660 (call-interactively (global-key-binding "\t")))
6662 (t (save-excursion
6663 (org-back-to-heading)
6664 (org-cycle)))))))
6666 (defun org-cycle-internal-global ()
6667 "Do the global cycling action."
6668 ;; Hack to avoid display of messages for .org attachments in Gnus
6669 (let ((ga (string-match "\\*fontification" (buffer-name))))
6670 (cond
6671 ((and (eq last-command this-command)
6672 (eq org-cycle-global-status 'overview))
6673 ;; We just created the overview - now do table of contents
6674 ;; This can be slow in very large buffers, so indicate action
6675 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6676 (unless ga (org-unlogged-message "CONTENTS..."))
6677 (org-content)
6678 (unless ga (org-unlogged-message "CONTENTS...done"))
6679 (setq org-cycle-global-status 'contents)
6680 (run-hook-with-args 'org-cycle-hook 'contents))
6682 ((and (eq last-command this-command)
6683 (eq org-cycle-global-status 'contents))
6684 ;; We just showed the table of contents - now show everything
6685 (run-hook-with-args 'org-pre-cycle-hook 'all)
6686 (show-all)
6687 (unless ga (org-unlogged-message "SHOW ALL"))
6688 (setq org-cycle-global-status 'all)
6689 (run-hook-with-args 'org-cycle-hook 'all))
6692 ;; Default action: go to overview
6693 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6694 (org-overview)
6695 (unless ga (org-unlogged-message "OVERVIEW"))
6696 (setq org-cycle-global-status 'overview)
6697 (run-hook-with-args 'org-cycle-hook 'overview)))))
6699 (defvar org-called-with-limited-levels);Dyn-bound in ̀org-with-limited-levels'.
6701 (defun org-cycle-internal-local ()
6702 "Do the local cycling action."
6703 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6704 ;; First, determine end of headline (EOH), end of subtree or item
6705 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6706 (save-excursion
6707 (if (org-at-item-p)
6708 (progn
6709 (beginning-of-line)
6710 (setq struct (org-list-struct))
6711 (setq eoh (point-at-eol))
6712 (setq eos (org-list-get-item-end-before-blank (point) struct))
6713 (setq has-children (org-list-has-child-p (point) struct)))
6714 (org-back-to-heading)
6715 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6716 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6717 (setq has-children
6718 (or (save-excursion
6719 (let ((level (funcall outline-level)))
6720 (outline-next-heading)
6721 (and (org-at-heading-p t)
6722 (> (funcall outline-level) level))))
6723 (save-excursion
6724 (org-list-search-forward (org-item-beginning-re) eos t)))))
6725 ;; Determine end invisible part of buffer (EOL)
6726 (beginning-of-line 2)
6727 ;; XEmacs doesn't have `next-single-char-property-change'
6728 (if (featurep 'xemacs)
6729 (while (and (not (eobp)) ;; this is like `next-line'
6730 (get-char-property (1- (point)) 'invisible))
6731 (beginning-of-line 2))
6732 (while (and (not (eobp)) ;; this is like `next-line'
6733 (get-char-property (1- (point)) 'invisible))
6734 (goto-char (next-single-char-property-change (point) 'invisible))
6735 (and (eolp) (beginning-of-line 2))))
6736 (setq eol (point)))
6737 ;; Find out what to do next and set `this-command'
6738 (cond
6739 ((= eos eoh)
6740 ;; Nothing is hidden behind this heading
6741 (unless (org-before-first-heading-p)
6742 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6743 (org-unlogged-message "EMPTY ENTRY")
6744 (setq org-cycle-subtree-status nil)
6745 (save-excursion
6746 (goto-char eos)
6747 (outline-next-heading)
6748 (if (outline-invisible-p) (org-flag-heading nil))))
6749 ((and (or (>= eol eos)
6750 (not (string-match "\\S-" (buffer-substring eol eos))))
6751 (or has-children
6752 (not (setq children-skipped
6753 org-cycle-skip-children-state-if-no-children))))
6754 ;; Entire subtree is hidden in one line: children view
6755 (unless (org-before-first-heading-p)
6756 (run-hook-with-args 'org-pre-cycle-hook 'children))
6757 (if (org-at-item-p)
6758 (org-list-set-item-visibility (point-at-bol) struct 'children)
6759 (org-show-entry)
6760 (org-with-limited-levels (show-children))
6761 ;; FIXME: This slows down the func way too much.
6762 ;; How keep drawers hidden in subtree anyway?
6763 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6764 ;; (org-cycle-hide-drawers 'subtree))
6766 ;; Fold every list in subtree to top-level items.
6767 (when (eq org-cycle-include-plain-lists 'integrate)
6768 (save-excursion
6769 (org-back-to-heading)
6770 (while (org-list-search-forward (org-item-beginning-re) eos t)
6771 (beginning-of-line 1)
6772 (let* ((struct (org-list-struct))
6773 (prevs (org-list-prevs-alist struct))
6774 (end (org-list-get-bottom-point struct)))
6775 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6776 (org-list-get-all-items (point) struct prevs))
6777 (goto-char (if (< end eos) end eos)))))))
6778 (org-unlogged-message "CHILDREN")
6779 (save-excursion
6780 (goto-char eos)
6781 (outline-next-heading)
6782 (if (outline-invisible-p) (org-flag-heading nil)))
6783 (setq org-cycle-subtree-status 'children)
6784 (unless (org-before-first-heading-p)
6785 (run-hook-with-args 'org-cycle-hook 'children)))
6786 ((or children-skipped
6787 (and (eq last-command this-command)
6788 (eq org-cycle-subtree-status 'children)))
6789 ;; We just showed the children, or no children are there,
6790 ;; now show everything.
6791 (unless (org-before-first-heading-p)
6792 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6793 (outline-flag-region eoh eos nil)
6794 (org-unlogged-message
6795 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6796 (setq org-cycle-subtree-status 'subtree)
6797 (unless (org-before-first-heading-p)
6798 (run-hook-with-args 'org-cycle-hook 'subtree)))
6800 ;; Default action: hide the subtree.
6801 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6802 (outline-flag-region eoh eos t)
6803 (org-unlogged-message "FOLDED")
6804 (setq org-cycle-subtree-status 'folded)
6805 (unless (org-before-first-heading-p)
6806 (run-hook-with-args 'org-cycle-hook 'folded))))))
6808 ;;;###autoload
6809 (defun org-global-cycle (&optional arg)
6810 "Cycle the global visibility. For details see `org-cycle'.
6811 With \\[universal-argument] prefix arg, switch to startup visibility.
6812 With a numeric prefix, show all headlines up to that level."
6813 (interactive "P")
6814 (let ((org-cycle-include-plain-lists
6815 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6816 (cond
6817 ((integerp arg)
6818 (show-all)
6819 (hide-sublevels arg)
6820 (setq org-cycle-global-status 'contents))
6821 ((equal arg '(4))
6822 (org-set-startup-visibility)
6823 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6825 (org-cycle '(4))))))
6827 (defun org-set-startup-visibility ()
6828 "Set the visibility required by startup options and properties."
6829 (cond
6830 ((eq org-startup-folded t)
6831 (org-overview))
6832 ((eq org-startup-folded 'content)
6833 (org-content))
6834 ((or (eq org-startup-folded 'showeverything)
6835 (eq org-startup-folded nil))
6836 (show-all)))
6837 (unless (eq org-startup-folded 'showeverything)
6838 (if org-hide-block-startup (org-hide-block-all))
6839 (org-set-visibility-according-to-property 'no-cleanup)
6840 (org-cycle-hide-archived-subtrees 'all)
6841 (org-cycle-hide-drawers 'all)
6842 (org-cycle-show-empty-lines t)))
6844 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6845 "Switch subtree visibilities according to :VISIBILITY: property."
6846 (interactive)
6847 (let (org-show-entry-below state)
6848 (save-excursion
6849 (goto-char (point-min))
6850 (while (re-search-forward
6851 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6852 nil t)
6853 (setq state (match-string 1))
6854 (save-excursion
6855 (org-back-to-heading t)
6856 (hide-subtree)
6857 (org-reveal)
6858 (cond
6859 ((equal state '("fold" "folded"))
6860 (hide-subtree))
6861 ((equal state "children")
6862 (org-show-hidden-entry)
6863 (show-children))
6864 ((equal state "content")
6865 (save-excursion
6866 (save-restriction
6867 (org-narrow-to-subtree)
6868 (org-content))))
6869 ((member state '("all" "showall"))
6870 (show-subtree)))))
6871 (unless no-cleanup
6872 (org-cycle-hide-archived-subtrees 'all)
6873 (org-cycle-hide-drawers 'all)
6874 (org-cycle-show-empty-lines 'all)))))
6876 ;; This function uses outline-regexp instead of the more fundamental
6877 ;; org-outline-regexp so that org-cycle-global works outside of Org
6878 ;; buffers, where outline-regexp is needed.
6879 (defun org-overview ()
6880 "Switch to overview mode, showing only top-level headlines.
6881 Really, this shows all headlines with level equal or greater than the level
6882 of the first headline in the buffer. This is important, because if the
6883 first headline is not level one, then (hide-sublevels 1) gives confusing
6884 results."
6885 (interactive)
6886 (let ((pos (point))
6887 (level (save-excursion
6888 (goto-char (point-min))
6889 (if (re-search-forward (concat "^" outline-regexp) nil t)
6890 (progn
6891 (goto-char (match-beginning 0))
6892 (funcall outline-level))))))
6893 (and level (hide-sublevels level))
6894 (recenter '(4))
6895 (goto-char pos)))
6897 (defun org-content (&optional arg)
6898 "Show all headlines in the buffer, like a table of contents.
6899 With numerical argument N, show content up to level N."
6900 (interactive "P")
6901 (org-overview)
6902 (save-excursion
6903 ;; Visit all headings and show their offspring
6904 (and (integerp arg) (org-overview))
6905 (goto-char (point-max))
6906 (catch 'exit
6907 (while (and (progn (condition-case nil
6908 (outline-previous-visible-heading 1)
6909 (error (goto-char (point-min))))
6911 (looking-at org-outline-regexp))
6912 (if (integerp arg)
6913 (show-children (1- arg))
6914 (show-branches))
6915 (if (bobp) (throw 'exit nil))))))
6917 (defun org-optimize-window-after-visibility-change (state)
6918 "Adjust the window after a change in outline visibility.
6919 This function is the default value of the hook `org-cycle-hook'."
6920 (when (get-buffer-window (current-buffer))
6921 (cond
6922 ((eq state 'content) nil)
6923 ((eq state 'all) nil)
6924 ((eq state 'folded) nil)
6925 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6926 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6928 (defun org-remove-empty-overlays-at (pos)
6929 "Remove outline overlays that do not contain non-white stuff."
6930 (mapc
6931 (lambda (o)
6932 (and (eq 'outline (overlay-get o 'invisible))
6933 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6934 (overlay-end o))))
6935 (delete-overlay o)))
6936 (overlays-at pos)))
6938 (defun org-clean-visibility-after-subtree-move ()
6939 "Fix visibility issues after moving a subtree."
6940 ;; First, find a reasonable region to look at:
6941 ;; Start two siblings above, end three below
6942 (let* ((beg (save-excursion
6943 (and (org-get-last-sibling)
6944 (org-get-last-sibling))
6945 (point)))
6946 (end (save-excursion
6947 (and (org-get-next-sibling)
6948 (org-get-next-sibling)
6949 (org-get-next-sibling))
6950 (if (org-at-heading-p)
6951 (point-at-eol)
6952 (point))))
6953 (level (looking-at "\\*+"))
6954 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6955 (save-excursion
6956 (save-restriction
6957 (narrow-to-region beg end)
6958 (when re
6959 ;; Properly fold already folded siblings
6960 (goto-char (point-min))
6961 (while (re-search-forward re nil t)
6962 (if (and (not (outline-invisible-p))
6963 (save-excursion
6964 (goto-char (point-at-eol)) (outline-invisible-p)))
6965 (hide-entry))))
6966 (org-cycle-show-empty-lines 'overview)
6967 (org-cycle-hide-drawers 'overview)))))
6969 (defun org-cycle-show-empty-lines (state)
6970 "Show empty lines above all visible headlines.
6971 The region to be covered depends on STATE when called through
6972 `org-cycle-hook'. Lisp program can use t for STATE to get the
6973 entire buffer covered. Note that an empty line is only shown if there
6974 are at least `org-cycle-separator-lines' empty lines before the headline."
6975 (when (not (= org-cycle-separator-lines 0))
6976 (save-excursion
6977 (let* ((n (abs org-cycle-separator-lines))
6978 (re (cond
6979 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6980 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6981 (t (let ((ns (number-to-string (- n 2))))
6982 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6983 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6984 beg end b e)
6985 (cond
6986 ((memq state '(overview contents t))
6987 (setq beg (point-min) end (point-max)))
6988 ((memq state '(children folded))
6989 (setq beg (point) end (progn (org-end-of-subtree t t)
6990 (beginning-of-line 2)
6991 (point)))))
6992 (when beg
6993 (goto-char beg)
6994 (while (re-search-forward re end t)
6995 (unless (get-char-property (match-end 1) 'invisible)
6996 (setq e (match-end 1))
6997 (if (< org-cycle-separator-lines 0)
6998 (setq b (save-excursion
6999 (goto-char (match-beginning 0))
7000 (org-back-over-empty-lines)
7001 (if (save-excursion
7002 (goto-char (max (point-min) (1- (point))))
7003 (org-at-heading-p))
7004 (1- (point))
7005 (point))))
7006 (setq b (match-beginning 1)))
7007 (outline-flag-region b e nil)))))))
7008 ;; Never hide empty lines at the end of the file.
7009 (save-excursion
7010 (goto-char (point-max))
7011 (outline-previous-heading)
7012 (outline-end-of-heading)
7013 (if (and (looking-at "[ \t\n]+")
7014 (= (match-end 0) (point-max)))
7015 (outline-flag-region (point) (match-end 0) nil))))
7017 (defun org-show-empty-lines-in-parent ()
7018 "Move to the parent and re-show empty lines before visible headlines."
7019 (save-excursion
7020 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7021 (org-cycle-show-empty-lines context))))
7023 (defun org-files-list ()
7024 "Return `org-agenda-files' list, plus all open org-mode files.
7025 This is useful for operations that need to scan all of a user's
7026 open and agenda-wise Org files."
7027 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7028 (dolist (buf (buffer-list))
7029 (with-current-buffer buf
7030 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7031 (let ((file (expand-file-name (buffer-file-name))))
7032 (unless (member file files)
7033 (push file files))))))
7034 files))
7036 (defsubst org-entry-beginning-position ()
7037 "Return the beginning position of the current entry."
7038 (save-excursion (outline-back-to-heading t) (point)))
7040 (defsubst org-entry-end-position ()
7041 "Return the end position of the current entry."
7042 (save-excursion (outline-next-heading) (point)))
7044 (defun org-cycle-hide-drawers (state)
7045 "Re-hide all drawers after a visibility state change."
7046 (when (and (derived-mode-p 'org-mode)
7047 (not (memq state '(overview folded contents))))
7048 (save-excursion
7049 (let* ((globalp (memq state '(contents all)))
7050 (beg (if globalp (point-min) (point)))
7051 (end (if globalp (point-max)
7052 (if (eq state 'children)
7053 (save-excursion (outline-next-heading) (point))
7054 (org-end-of-subtree t)))))
7055 (goto-char beg)
7056 (while (re-search-forward org-drawer-regexp end t)
7057 (org-flag-drawer t))))))
7059 (defun org-cycle-hide-inline-tasks (state)
7060 "Re-hide inline tasks when switching to 'contents or 'children
7061 visibility state."
7062 (case state
7063 (contents
7064 (when (org-bound-and-true-p org-inlinetask-min-level)
7065 (hide-sublevels (1- org-inlinetask-min-level))))
7066 (children
7067 (when (featurep 'org-inlinetask)
7068 (save-excursion
7069 (while (and (outline-next-heading)
7070 (org-inlinetask-at-task-p))
7071 (org-inlinetask-toggle-visibility)
7072 (org-inlinetask-goto-end)))))))
7074 (defun org-flag-drawer (flag)
7075 "When FLAG is non-nil, hide the drawer we are within.
7076 Otherwise make it visible."
7077 (save-excursion
7078 (beginning-of-line 1)
7079 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
7080 (let ((b (match-end 0)))
7081 (if (re-search-forward
7082 "^[ \t]*:END:"
7083 (save-excursion (outline-next-heading) (point)) t)
7084 (outline-flag-region b (point-at-eol) flag)
7085 (user-error ":END: line missing at position %s" b))))))
7087 (defun org-subtree-end-visible-p ()
7088 "Is the end of the current subtree visible?"
7089 (pos-visible-in-window-p
7090 (save-excursion (org-end-of-subtree t) (point))))
7092 (defun org-first-headline-recenter (&optional N)
7093 "Move cursor to the first headline and recenter the headline.
7094 Optional argument N means put the headline into the Nth line of the window."
7095 (goto-char (point-min))
7096 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7097 (beginning-of-line)
7098 (recenter (prefix-numeric-value N))))
7100 ;;; Saving and restoring visibility
7102 (defun org-outline-overlay-data (&optional use-markers)
7103 "Return a list of the locations of all outline overlays.
7104 These are overlays with the `invisible' property value `outline'.
7105 The return value is a list of cons cells, with start and stop
7106 positions for each overlay.
7107 If USE-MARKERS is set, return the positions as markers."
7108 (let (beg end)
7109 (save-excursion
7110 (save-restriction
7111 (widen)
7112 (delq nil
7113 (mapcar (lambda (o)
7114 (when (eq (overlay-get o 'invisible) 'outline)
7115 (setq beg (overlay-start o)
7116 end (overlay-end o))
7117 (and beg end (> end beg)
7118 (if use-markers
7119 (cons (move-marker (make-marker) beg)
7120 (move-marker (make-marker) end))
7121 (cons beg end)))))
7122 (overlays-in (point-min) (point-max))))))))
7124 (defun org-set-outline-overlay-data (data)
7125 "Create visibility overlays for all positions in DATA.
7126 DATA should have been made by `org-outline-overlay-data'."
7127 (let (o)
7128 (save-excursion
7129 (save-restriction
7130 (widen)
7131 (show-all)
7132 (mapc (lambda (c)
7133 (outline-flag-region (car c) (cdr c) t))
7134 data)))))
7136 ;;; Folding of blocks
7138 (defvar org-hide-block-overlays nil
7139 "Overlays hiding blocks.")
7140 (make-variable-buffer-local 'org-hide-block-overlays)
7142 (defun org-block-map (function &optional start end)
7143 "Call FUNCTION at the head of all source blocks in the current buffer.
7144 Optional arguments START and END can be used to limit the range."
7145 (let ((start (or start (point-min)))
7146 (end (or end (point-max))))
7147 (save-excursion
7148 (goto-char start)
7149 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7150 (save-excursion
7151 (save-match-data
7152 (goto-char (match-beginning 0))
7153 (funcall function)))))))
7155 (defun org-hide-block-toggle-all ()
7156 "Toggle the visibility of all blocks in the current buffer."
7157 (org-block-map #'org-hide-block-toggle))
7159 (defun org-hide-block-all ()
7160 "Fold all blocks in the current buffer."
7161 (interactive)
7162 (org-show-block-all)
7163 (org-block-map #'org-hide-block-toggle-maybe))
7165 (defun org-show-block-all ()
7166 "Unfold all blocks in the current buffer."
7167 (interactive)
7168 (mapc 'delete-overlay org-hide-block-overlays)
7169 (setq org-hide-block-overlays nil))
7171 (defun org-hide-block-toggle-maybe ()
7172 "Toggle visibility of block at point."
7173 (interactive)
7174 (let ((case-fold-search t))
7175 (if (save-excursion
7176 (beginning-of-line 1)
7177 (looking-at org-block-regexp))
7178 (progn (org-hide-block-toggle)
7179 t) ;; to signal that we took action
7180 nil))) ;; to signal that we did not
7182 (defun org-hide-block-toggle (&optional force)
7183 "Toggle the visibility of the current block."
7184 (interactive)
7185 (save-excursion
7186 (beginning-of-line)
7187 (if (re-search-forward org-block-regexp nil t)
7188 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7189 (end (match-end 0)) ;; end of entire body
7191 (if (memq t (mapcar (lambda (overlay)
7192 (eq (overlay-get overlay 'invisible)
7193 'org-hide-block))
7194 (overlays-at start)))
7195 (if (or (not force) (eq force 'off))
7196 (mapc (lambda (ov)
7197 (when (member ov org-hide-block-overlays)
7198 (setq org-hide-block-overlays
7199 (delq ov org-hide-block-overlays)))
7200 (when (eq (overlay-get ov 'invisible)
7201 'org-hide-block)
7202 (delete-overlay ov)))
7203 (overlays-at start)))
7204 (setq ov (make-overlay start end))
7205 (overlay-put ov 'invisible 'org-hide-block)
7206 ;; make the block accessible to isearch
7207 (overlay-put
7208 ov 'isearch-open-invisible
7209 (lambda (ov)
7210 (when (member ov org-hide-block-overlays)
7211 (setq org-hide-block-overlays
7212 (delq ov org-hide-block-overlays)))
7213 (when (eq (overlay-get ov 'invisible)
7214 'org-hide-block)
7215 (delete-overlay ov))))
7216 (push ov org-hide-block-overlays)))
7217 (user-error "Not looking at a source block"))))
7219 ;; org-tab-after-check-for-cycling-hook
7220 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7221 ;; Remove overlays when changing major mode
7222 (add-hook 'org-mode-hook
7223 (lambda () (org-add-hook 'change-major-mode-hook
7224 'org-show-block-all 'append 'local)))
7226 ;;; Org-goto
7228 (defvar org-goto-window-configuration nil)
7229 (defvar org-goto-marker nil)
7230 (defvar org-goto-map)
7231 (defun org-goto-map ()
7232 "Set the keymap `org-goto'."
7233 (setq org-goto-map
7234 (let ((map (make-sparse-keymap)))
7235 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7236 mouse-drag-region universal-argument org-occur))
7237 cmd)
7238 (while (setq cmd (pop cmds))
7239 (substitute-key-definition cmd cmd map global-map)))
7240 (suppress-keymap map)
7241 (org-defkey map "\C-m" 'org-goto-ret)
7242 (org-defkey map [(return)] 'org-goto-ret)
7243 (org-defkey map [(left)] 'org-goto-left)
7244 (org-defkey map [(right)] 'org-goto-right)
7245 (org-defkey map [(control ?g)] 'org-goto-quit)
7246 (org-defkey map "\C-i" 'org-cycle)
7247 (org-defkey map [(tab)] 'org-cycle)
7248 (org-defkey map [(down)] 'outline-next-visible-heading)
7249 (org-defkey map [(up)] 'outline-previous-visible-heading)
7250 (if org-goto-auto-isearch
7251 (if (fboundp 'define-key-after)
7252 (define-key-after map [t] 'org-goto-local-auto-isearch)
7253 nil)
7254 (org-defkey map "q" 'org-goto-quit)
7255 (org-defkey map "n" 'outline-next-visible-heading)
7256 (org-defkey map "p" 'outline-previous-visible-heading)
7257 (org-defkey map "f" 'outline-forward-same-level)
7258 (org-defkey map "b" 'outline-backward-same-level)
7259 (org-defkey map "u" 'outline-up-heading))
7260 (org-defkey map "/" 'org-occur)
7261 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7262 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7263 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7264 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7265 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7266 map)))
7268 (defconst org-goto-help
7269 "Browse buffer copy, to find location or copy text.%s
7270 RET=jump to location C-g=quit and return to previous location
7271 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7273 (defvar org-goto-start-pos) ; dynamically scoped parameter
7275 (defun org-goto (&optional alternative-interface)
7276 "Look up a different location in the current file, keeping current visibility.
7278 When you want look-up or go to a different location in a
7279 document, the fastest way is often to fold the entire buffer and
7280 then dive into the tree. This method has the disadvantage, that
7281 the previous location will be folded, which may not be what you
7282 want.
7284 This command works around this by showing a copy of the current
7285 buffer in an indirect buffer, in overview mode. You can dive
7286 into the tree in that copy, use org-occur and incremental search
7287 to find a location. When pressing RET or `Q', the command
7288 returns to the original buffer in which the visibility is still
7289 unchanged. After RET it will also jump to the location selected
7290 in the indirect buffer and expose the headline hierarchy above.
7292 With a prefix argument, use the alternative interface: e.g. if
7293 `org-goto-interface' is 'outline use 'outline-path-completion."
7294 (interactive "P")
7295 (org-goto-map)
7296 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7297 (org-refile-use-outline-path t)
7298 (org-refile-target-verify-function nil)
7299 (interface
7300 (if (not alternative-interface)
7301 org-goto-interface
7302 (if (eq org-goto-interface 'outline)
7303 'outline-path-completion
7304 'outline)))
7305 (org-goto-start-pos (point))
7306 (selected-point
7307 (if (eq interface 'outline)
7308 (car (org-get-location (current-buffer) org-goto-help))
7309 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7310 (org-refile-check-position pa)
7311 (nth 3 pa)))))
7312 (if selected-point
7313 (progn
7314 (org-mark-ring-push org-goto-start-pos)
7315 (goto-char selected-point)
7316 (if (or (outline-invisible-p) (org-invisible-p2))
7317 (org-show-context 'org-goto)))
7318 (message "Quit"))))
7320 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7321 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7322 (defvar org-goto-local-auto-isearch-map) ; defined below
7324 (defun org-get-location (buf help)
7325 "Let the user select a location in the Org-mode buffer BUF.
7326 This function uses a recursive edit. It returns the selected position
7327 or nil."
7328 (org-no-popups
7329 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7330 (isearch-hide-immediately nil)
7331 (isearch-search-fun-function
7332 (lambda () 'org-goto-local-search-headings))
7333 (org-goto-selected-point org-goto-exit-command))
7334 (save-excursion
7335 (save-window-excursion
7336 (delete-other-windows)
7337 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7338 (org-pop-to-buffer-same-window
7339 (condition-case nil
7340 (make-indirect-buffer (current-buffer) "*org-goto*")
7341 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7342 (with-output-to-temp-buffer "*Org Help*"
7343 (princ (format help (if org-goto-auto-isearch
7344 " Just type for auto-isearch."
7345 " n/p/f/b/u to navigate, q to quit."))))
7346 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7347 (setq buffer-read-only nil)
7348 (let ((org-startup-truncated t)
7349 (org-startup-folded nil)
7350 (org-startup-align-all-tables nil))
7351 (org-mode)
7352 (org-overview))
7353 (setq buffer-read-only t)
7354 (if (and (boundp 'org-goto-start-pos)
7355 (integer-or-marker-p org-goto-start-pos))
7356 (let ((org-show-hierarchy-above t)
7357 (org-show-siblings t)
7358 (org-show-following-heading t))
7359 (goto-char org-goto-start-pos)
7360 (and (outline-invisible-p) (org-show-context)))
7361 (goto-char (point-min)))
7362 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7363 (message "Select location and press RET")
7364 (use-local-map org-goto-map)
7365 (recursive-edit)))
7366 (kill-buffer "*org-goto*")
7367 (cons org-goto-selected-point org-goto-exit-command))))
7369 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7370 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7371 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7372 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7374 (defun org-goto-local-search-headings (string bound noerror)
7375 "Search and make sure that any matches are in headlines."
7376 (catch 'return
7377 (while (if isearch-forward
7378 (search-forward string bound noerror)
7379 (search-backward string bound noerror))
7380 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7381 (and (member :headline context)
7382 (not (member :tags context))))
7383 (throw 'return (point))))))
7385 (defun org-goto-local-auto-isearch ()
7386 "Start isearch."
7387 (interactive)
7388 (goto-char (point-min))
7389 (let ((keys (this-command-keys)))
7390 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7391 (isearch-mode t)
7392 (isearch-process-search-char (string-to-char keys)))))
7394 (defun org-goto-ret (&optional arg)
7395 "Finish `org-goto' by going to the new location."
7396 (interactive "P")
7397 (setq org-goto-selected-point (point)
7398 org-goto-exit-command 'return)
7399 (throw 'exit nil))
7401 (defun org-goto-left ()
7402 "Finish `org-goto' by going to the new location."
7403 (interactive)
7404 (if (org-at-heading-p)
7405 (progn
7406 (beginning-of-line 1)
7407 (setq org-goto-selected-point (point)
7408 org-goto-exit-command 'left)
7409 (throw 'exit nil))
7410 (user-error "Not on a heading")))
7412 (defun org-goto-right ()
7413 "Finish `org-goto' by going to the new location."
7414 (interactive)
7415 (if (org-at-heading-p)
7416 (progn
7417 (setq org-goto-selected-point (point)
7418 org-goto-exit-command 'right)
7419 (throw 'exit nil))
7420 (user-error "Not on a heading")))
7422 (defun org-goto-quit ()
7423 "Finish `org-goto' without cursor motion."
7424 (interactive)
7425 (setq org-goto-selected-point nil)
7426 (setq org-goto-exit-command 'quit)
7427 (throw 'exit nil))
7429 ;;; Indirect buffer display of subtrees
7431 (defvar org-indirect-dedicated-frame nil
7432 "This is the frame being used for indirect tree display.")
7433 (defvar org-last-indirect-buffer nil)
7435 (defun org-tree-to-indirect-buffer (&optional arg)
7436 "Create indirect buffer and narrow it to current subtree.
7437 With a numerical prefix ARG, go up to this level and then take that tree.
7438 If ARG is negative, go up that many levels.
7440 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7441 indirect buffer previously made with this command, to avoid proliferation of
7442 indirect buffers. However, when you call the command with a \
7443 \\[universal-argument] prefix, or
7444 when `org-indirect-buffer-display' is `new-frame', the last buffer
7445 is kept so that you can work with several indirect buffers at the same time.
7446 If `org-indirect-buffer-display' is `dedicated-frame', the \
7447 \\[universal-argument] prefix also
7448 requests that a new frame be made for the new buffer, so that the dedicated
7449 frame is not changed."
7450 (interactive "P")
7451 (let ((cbuf (current-buffer))
7452 (cwin (selected-window))
7453 (pos (point))
7454 beg end level heading ibuf)
7455 (save-excursion
7456 (org-back-to-heading t)
7457 (when (numberp arg)
7458 (setq level (org-outline-level))
7459 (if (< arg 0) (setq arg (+ level arg)))
7460 (while (> (setq level (org-outline-level)) arg)
7461 (org-up-heading-safe)))
7462 (setq beg (point)
7463 heading (org-get-heading))
7464 (org-end-of-subtree t t)
7465 (if (org-at-heading-p) (backward-char 1))
7466 (setq end (point)))
7467 (if (and (buffer-live-p org-last-indirect-buffer)
7468 (not (eq org-indirect-buffer-display 'new-frame))
7469 (not arg))
7470 (kill-buffer org-last-indirect-buffer))
7471 (setq ibuf (org-get-indirect-buffer cbuf)
7472 org-last-indirect-buffer ibuf)
7473 (cond
7474 ((or (eq org-indirect-buffer-display 'new-frame)
7475 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7476 (select-frame (make-frame))
7477 (delete-other-windows)
7478 (org-pop-to-buffer-same-window ibuf)
7479 (org-set-frame-title heading))
7480 ((eq org-indirect-buffer-display 'dedicated-frame)
7481 (raise-frame
7482 (select-frame (or (and org-indirect-dedicated-frame
7483 (frame-live-p org-indirect-dedicated-frame)
7484 org-indirect-dedicated-frame)
7485 (setq org-indirect-dedicated-frame (make-frame)))))
7486 (delete-other-windows)
7487 (org-pop-to-buffer-same-window ibuf)
7488 (org-set-frame-title (concat "Indirect: " heading)))
7489 ((eq org-indirect-buffer-display 'current-window)
7490 (org-pop-to-buffer-same-window ibuf))
7491 ((eq org-indirect-buffer-display 'other-window)
7492 (pop-to-buffer ibuf))
7493 (t (error "Invalid value")))
7494 (if (featurep 'xemacs)
7495 (save-excursion (org-mode) (turn-on-font-lock)))
7496 (narrow-to-region beg end)
7497 (show-all)
7498 (goto-char pos)
7499 (run-hook-with-args 'org-cycle-hook 'all)
7500 (and (window-live-p cwin) (select-window cwin))))
7502 (defun org-get-indirect-buffer (&optional buffer)
7503 (setq buffer (or buffer (current-buffer)))
7504 (let ((n 1) (base (buffer-name buffer)) bname)
7505 (while (buffer-live-p
7506 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7507 (setq n (1+ n)))
7508 (condition-case nil
7509 (make-indirect-buffer buffer bname 'clone)
7510 (error (make-indirect-buffer buffer bname)))))
7512 (defun org-set-frame-title (title)
7513 "Set the title of the current frame to the string TITLE."
7514 ;; FIXME: how to name a single frame in XEmacs???
7515 (unless (featurep 'xemacs)
7516 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7518 ;;;; Structure editing
7520 ;;; Inserting headlines
7522 (defun org-previous-line-empty-p (&optional next)
7523 "Is the previous line a blank line?
7524 When NEXT is non-nil, check the next line instead."
7525 (save-excursion
7526 (and (not (bobp))
7527 (or (beginning-of-line (if next 2 0)) t)
7528 (save-match-data
7529 (looking-at "[ \t]*$")))))
7531 (defun org-insert-heading (&optional arg invisible-ok)
7532 "Insert a new heading or item with same depth at point.
7533 If point is in a plain list and ARG is nil, create a new list item.
7534 With one universal prefix argument, insert a heading even in lists.
7535 With two universal prefix arguments, insert the heading at the end
7536 of the parent subtree.
7538 If point is at the beginning of a headline, insert a sibling before
7539 the current headline. If point is not at the beginning, split the line
7540 and create a new headline with the text in the current line after point
7541 \(see `org-M-RET-may-split-line' on how to modify this behavior).
7543 If point is at the beginning of a normal line, turn this line into
7544 a heading.
7546 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7547 This is important for non-interactive uses of the command."
7548 (interactive "P")
7549 (if (org-called-interactively-p 'any) (org-reveal))
7550 (let ((itemp (org-in-item-p))
7551 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7552 (respect-content (or org-insert-heading-respect-content
7553 (equal arg '(4))))
7554 (initial-content "")
7555 (adjust-empty-lines t))
7557 (cond
7559 ((or (= (buffer-size) 0)
7560 (and (not (save-excursion
7561 (and (ignore-errors (org-back-to-heading invisible-ok))
7562 (org-at-heading-p))))
7563 (or arg (not itemp))))
7564 ;; At beginning of buffer or so high up that only a heading
7565 ;; makes sense.
7566 (insert
7567 (if (or (bobp) (org-previous-line-empty-p)) "" "\n")
7568 (if (org-in-src-block-p) ",* " "* "))
7569 (run-hooks 'org-insert-heading-hook))
7571 ((and itemp (not (equal arg '(4))))
7572 ;; Insert an item
7573 (org-insert-item))
7576 ;; Maybe move at the end of the subtree
7577 (when (equal arg '(16))
7578 (org-up-heading-safe)
7579 (org-end-of-subtree t))
7580 ;; Insert a heading
7581 (save-restriction
7582 (widen)
7583 (let* ((level nil)
7584 (on-heading (org-at-heading-p))
7585 (empty-line-p (if on-heading
7586 (org-previous-line-empty-p)
7587 ;; We will decide later
7588 nil))
7589 ;; Get a level string to fall back on
7590 (fix-level
7591 (save-excursion
7592 (org-back-to-heading t)
7593 (if (org-previous-line-empty-p) (setq empty-line-p t))
7594 (looking-at org-outline-regexp)
7595 (make-string (1- (length (match-string 0))) ?*)))
7596 (stars
7597 (save-excursion
7598 (condition-case nil
7599 (progn
7600 (org-back-to-heading invisible-ok)
7601 (when (and (not on-heading)
7602 (featurep 'org-inlinetask)
7603 (integerp org-inlinetask-min-level)
7604 (>= (length (match-string 0))
7605 org-inlinetask-min-level))
7606 ;; Find a heading level before the inline task
7607 (while (and (setq level (org-up-heading-safe))
7608 (>= level org-inlinetask-min-level)))
7609 (if (org-at-heading-p)
7610 (org-back-to-heading invisible-ok)
7611 (error "This should not happen")))
7612 (unless (and (save-excursion
7613 (save-match-data
7614 (org-backward-heading-same-level
7615 1 invisible-ok))
7616 (= (point) (match-beginning 0)))
7617 (not (org-previous-line-empty-p t)))
7618 (setq empty-line-p (or empty-line-p
7619 (org-previous-line-empty-p))))
7620 (match-string 0))
7621 (error (or fix-level "* ")))))
7622 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7623 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7624 pos hide-previous previous-pos)
7626 ;; If we insert after content, move there and clean up whitespace
7627 (when respect-content
7628 (org-end-of-subtree nil t)
7629 (skip-chars-backward " \r\n")
7630 (and (not (looking-back "^\*+"))
7631 (looking-at "[ \t]+") (replace-match ""))
7632 (unless (eobp) (forward-char 1))
7633 (when (looking-at "^\\*")
7634 (unless (bobp) (backward-char 1))
7635 (insert "\n")))
7637 ;; If we are splitting, grab the text that should be moved to the new headline
7638 (when may-split
7639 (if (org-on-heading-p)
7640 ;; This is a heading, we split intelligently (keeping tags)
7641 (let ((pos (point)))
7642 (goto-char (point-at-bol))
7643 (unless (looking-at org-complex-heading-regexp)
7644 (error "This should not happen"))
7645 (when (and (match-beginning 4)
7646 (> pos (match-beginning 4))
7647 (< pos (match-end 4)))
7648 (setq initial-content (buffer-substring pos (match-end 4)))
7649 (goto-char pos)
7650 (delete-region (point) (match-end 4))
7651 (if (looking-at "[ \t]*$")
7652 (replace-match "")
7653 (insert (make-string (length initial-content) ?\ )))
7654 (setq initial-content (org-trim initial-content)))
7655 (goto-char pos))
7656 ;; a normal line
7657 (unless (bolp)
7658 (setq initial-content (buffer-substring (point) (point-at-eol)))
7659 (delete-region (point) (point-at-eol))
7660 (setq initial-content (org-trim initial-content)))))
7662 ;; If we are at the beginning of the line, insert before it. Else after
7663 (cond
7664 ((and (bolp) (looking-at "[ \t]*$")))
7665 ((and (bolp) (not (looking-at "[ \t]*$")))
7666 (open-line 1))
7668 (goto-char (point-at-eol))
7669 (insert "\n")))
7671 ;; Insert the new heading
7672 (insert stars)
7673 (just-one-space)
7674 (insert initial-content)
7675 (when adjust-empty-lines
7676 (if (or (not blank)
7677 (and blank (not (org-previous-line-empty-p))))
7678 (org-N-empty-lines-before-current (if blank 1 0))))
7679 (run-hooks 'org-insert-heading-hook)))))))
7681 (defun org-N-empty-lines-before-current (N)
7682 "Make the number of empty lines before current exactly N.
7683 So this will delete or add empty lines."
7684 (save-excursion
7685 (goto-char (point-at-bol))
7686 (if (looking-back "\\s-+" nil 'greedy)
7687 (replace-match ""))
7688 (or (bobp) (insert "\n"))
7689 (while (> N 0)
7690 (insert "\n")
7691 (setq N (1- N)))))
7693 (defun org-get-heading (&optional no-tags no-todo)
7694 "Return the heading of the current entry, without the stars.
7695 When NO-TAGS is non-nil, don't include tags.
7696 When NO-TODO is non-nil, don't include TODO keywords."
7697 (save-excursion
7698 (org-back-to-heading t)
7699 (cond
7700 ((and no-tags no-todo)
7701 (looking-at org-complex-heading-regexp)
7702 (match-string 4))
7703 (no-tags
7704 (looking-at (concat org-outline-regexp
7705 "\\(.*?\\)"
7706 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7707 (match-string 1))
7708 (no-todo
7709 (looking-at org-todo-line-regexp)
7710 (match-string 3))
7711 (t (looking-at org-heading-regexp)
7712 (match-string 2)))))
7714 (defvar orgstruct-mode) ; defined below
7716 (defun org-heading-components ()
7717 "Return the components of the current heading.
7718 This is a list with the following elements:
7719 - the level as an integer
7720 - the reduced level, different if `org-odd-levels-only' is set.
7721 - the TODO keyword, or nil
7722 - the priority character, like ?A, or nil if no priority is given
7723 - the headline text itself, or the tags string if no headline text
7724 - the tags string, or nil."
7725 (save-excursion
7726 (org-back-to-heading t)
7727 (if (let (case-fold-search)
7728 (looking-at
7729 (if orgstruct-mode
7730 org-heading-regexp
7731 org-complex-heading-regexp)))
7732 (if orgstruct-mode
7733 (list (length (match-string 1))
7734 (org-reduced-level (length (match-string 1)))
7737 (match-string 2)
7738 nil)
7739 (list (length (match-string 1))
7740 (org-reduced-level (length (match-string 1)))
7741 (org-match-string-no-properties 2)
7742 (and (match-end 3) (aref (match-string 3) 2))
7743 (org-match-string-no-properties 4)
7744 (org-match-string-no-properties 5))))))
7746 (defun org-get-entry ()
7747 "Get the entry text, after heading, entire subtree."
7748 (save-excursion
7749 (org-back-to-heading t)
7750 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7752 (defun org-insert-heading-after-current ()
7753 "Insert a new heading with same level as current, after current subtree."
7754 (interactive)
7755 (org-back-to-heading)
7756 (org-insert-heading)
7757 (org-move-subtree-down)
7758 (end-of-line 1))
7760 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7761 "Insert heading with `org-insert-heading-respect-content' set to t."
7762 (interactive "P")
7763 (let ((org-insert-heading-respect-content t))
7764 (org-insert-heading '(4) invisible-ok)))
7766 (defun org-insert-todo-heading-respect-content (&optional force-state)
7767 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7768 (interactive "P")
7769 (let ((org-insert-heading-respect-content t))
7770 (org-insert-todo-heading force-state '(4))))
7772 (defun org-insert-todo-heading (arg &optional force-heading)
7773 "Insert a new heading with the same level and TODO state as current heading.
7774 If the heading has no TODO state, or if the state is DONE, use the first
7775 state (TODO by default). Also with one prefix arg, force first state. With
7776 two prefix args, force inserting at the end of the parent subtree."
7777 (interactive "P")
7778 (when (or force-heading (not (org-insert-item 'checkbox)))
7779 (org-insert-heading (or (and (equal arg '(16)) '(16))
7780 force-heading))
7781 (save-excursion
7782 (org-back-to-heading)
7783 (outline-previous-heading)
7784 (looking-at org-todo-line-regexp))
7785 (let*
7786 ((new-mark-x
7787 (if (or (equal arg '(4))
7788 (not (match-beginning 2))
7789 (member (match-string 2) org-done-keywords))
7790 (car org-todo-keywords-1)
7791 (match-string 2)))
7792 (new-mark
7794 (run-hook-with-args-until-success
7795 'org-todo-get-default-hook new-mark-x nil)
7796 new-mark-x)))
7797 (beginning-of-line 1)
7798 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7799 (if org-treat-insert-todo-heading-as-state-change
7800 (org-todo new-mark)
7801 (insert new-mark " "))))
7802 (when org-provide-todo-statistics
7803 (org-update-parent-todo-statistics))))
7805 (defun org-insert-subheading (arg)
7806 "Insert a new subheading and demote it.
7807 Works for outline headings and for plain lists alike."
7808 (interactive "P")
7809 (org-insert-heading arg)
7810 (cond
7811 ((org-at-heading-p) (org-do-demote))
7812 ((org-at-item-p) (org-indent-item))))
7814 (defun org-insert-todo-subheading (arg)
7815 "Insert a new subheading with TODO keyword or checkbox and demote it.
7816 Works for outline headings and for plain lists alike."
7817 (interactive "P")
7818 (org-insert-todo-heading arg)
7819 (cond
7820 ((org-at-heading-p) (org-do-demote))
7821 ((org-at-item-p) (org-indent-item))))
7823 ;;; Promotion and Demotion
7825 (defvar org-after-demote-entry-hook nil
7826 "Hook run after an entry has been demoted.
7827 The cursor will be at the beginning of the entry.
7828 When a subtree is being demoted, the hook will be called for each node.")
7830 (defvar org-after-promote-entry-hook nil
7831 "Hook run after an entry has been promoted.
7832 The cursor will be at the beginning of the entry.
7833 When a subtree is being promoted, the hook will be called for each node.")
7835 (defun org-promote-subtree ()
7836 "Promote the entire subtree.
7837 See also `org-promote'."
7838 (interactive)
7839 (save-excursion
7840 (org-with-limited-levels (org-map-tree 'org-promote)))
7841 (org-fix-position-after-promote))
7843 (defun org-demote-subtree ()
7844 "Demote the entire subtree. See `org-demote'.
7845 See also `org-promote'."
7846 (interactive)
7847 (save-excursion
7848 (org-with-limited-levels (org-map-tree 'org-demote)))
7849 (org-fix-position-after-promote))
7852 (defun org-do-promote ()
7853 "Promote the current heading higher up the tree.
7854 If the region is active in `transient-mark-mode', promote all headings
7855 in the region."
7856 (interactive)
7857 (save-excursion
7858 (if (org-region-active-p)
7859 (org-map-region 'org-promote (region-beginning) (region-end))
7860 (org-promote)))
7861 (org-fix-position-after-promote))
7863 (defun org-do-demote ()
7864 "Demote the current heading lower down the tree.
7865 If the region is active in `transient-mark-mode', demote all headings
7866 in the region."
7867 (interactive)
7868 (save-excursion
7869 (if (org-region-active-p)
7870 (org-map-region 'org-demote (region-beginning) (region-end))
7871 (org-demote)))
7872 (org-fix-position-after-promote))
7874 (defun org-fix-position-after-promote ()
7875 "Make sure that after pro/demotion cursor position is right."
7876 (let ((pos (point)))
7877 (when (save-excursion
7878 (beginning-of-line 1)
7879 (looking-at org-todo-line-regexp)
7880 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7881 (cond ((eobp) (insert " "))
7882 ((eolp) (insert " "))
7883 ((equal (char-after) ?\ ) (forward-char 1))))))
7885 (defun org-current-level ()
7886 "Return the level of the current entry, or nil if before the first headline.
7887 The level is the number of stars at the beginning of the headline."
7888 (save-excursion
7889 (org-with-limited-levels
7890 (if (ignore-errors (org-back-to-heading t))
7891 (funcall outline-level)))))
7893 (defun org-get-previous-line-level ()
7894 "Return the outline depth of the last headline before the current line.
7895 Returns 0 for the first headline in the buffer, and nil if before the
7896 first headline."
7897 (and (org-current-level)
7898 (or (and (/= (line-beginning-position) (point-min))
7899 (save-excursion (beginning-of-line 0) (org-current-level)))
7900 0)))
7902 (defun org-reduced-level (l)
7903 "Compute the effective level of a heading.
7904 This takes into account the setting of `org-odd-levels-only'."
7905 (cond
7906 ((zerop l) 0)
7907 (org-odd-levels-only (1+ (floor (/ l 2))))
7908 (t l)))
7910 (defun org-level-increment ()
7911 "Return the number of stars that will be added or removed at a
7912 time to headlines when structure editing, based on the value of
7913 `org-odd-levels-only'."
7914 (if org-odd-levels-only 2 1))
7916 (defun org-get-valid-level (level &optional change)
7917 "Rectify a level change under the influence of `org-odd-levels-only'
7918 LEVEL is a current level, CHANGE is by how much the level should be
7919 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7920 even level numbers will become the next higher odd number."
7921 (if org-odd-levels-only
7922 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7923 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7924 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7925 (max 1 (+ level (or change 0)))))
7927 (if (boundp 'define-obsolete-function-alias)
7928 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7929 (define-obsolete-function-alias 'org-get-legal-level
7930 'org-get-valid-level)
7931 (define-obsolete-function-alias 'org-get-legal-level
7932 'org-get-valid-level "23.1")))
7934 (defun org-promote ()
7935 "Promote the current heading higher up the tree.
7936 If the region is active in `transient-mark-mode', promote all headings
7937 in the region."
7938 (org-back-to-heading t)
7939 (let* ((level (save-match-data (funcall outline-level)))
7940 (after-change-functions (remove 'flyspell-after-change-function
7941 after-change-functions))
7942 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7943 (diff (abs (- level (length up-head) -1))))
7944 (cond ((and (= level 1) org-called-with-limited-levels
7945 org-allow-promoting-top-level-subtree)
7946 (replace-match "# " nil t))
7947 ((= level 1)
7948 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
7949 (t (replace-match up-head nil t)))
7950 ;; Fixup tag positioning
7951 (unless (= level 1)
7952 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
7953 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7954 (run-hooks 'org-after-promote-entry-hook)))
7956 (defun org-demote ()
7957 "Demote the current heading lower down the tree.
7958 If the region is active in `transient-mark-mode', demote all headings
7959 in the region."
7960 (org-back-to-heading t)
7961 (let* ((level (save-match-data (funcall outline-level)))
7962 (after-change-functions (remove 'flyspell-after-change-function
7963 after-change-functions))
7964 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7965 (diff (abs (- level (length down-head) -1))))
7966 (replace-match down-head nil t)
7967 ;; Fixup tag positioning
7968 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
7969 (if org-adapt-indentation (org-fixup-indentation diff))
7970 (run-hooks 'org-after-demote-entry-hook)))
7972 (defun org-cycle-level ()
7973 "Cycle the level of an empty headline through possible states.
7974 This goes first to child, then to parent, level, then up the hierarchy.
7975 After top level, it switches back to sibling level."
7976 (interactive)
7977 (let ((org-adapt-indentation nil))
7978 (when (org-point-at-end-of-empty-headline)
7979 (setq this-command 'org-cycle-level) ; Only needed for caching
7980 (let ((cur-level (org-current-level))
7981 (prev-level (org-get-previous-line-level)))
7982 (cond
7983 ;; If first headline in file, promote to top-level.
7984 ((= prev-level 0)
7985 (loop repeat (/ (- cur-level 1) (org-level-increment))
7986 do (org-do-promote)))
7987 ;; If same level as prev, demote one.
7988 ((= prev-level cur-level)
7989 (org-do-demote))
7990 ;; If parent is top-level, promote to top level if not already.
7991 ((= prev-level 1)
7992 (loop repeat (/ (- cur-level 1) (org-level-increment))
7993 do (org-do-promote)))
7994 ;; If top-level, return to prev-level.
7995 ((= cur-level 1)
7996 (loop repeat (/ (- prev-level 1) (org-level-increment))
7997 do (org-do-demote)))
7998 ;; If less than prev-level, promote one.
7999 ((< cur-level prev-level)
8000 (org-do-promote))
8001 ;; If deeper than prev-level, promote until higher than
8002 ;; prev-level.
8003 ((> cur-level prev-level)
8004 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8005 do (org-do-promote))))
8006 t))))
8008 (defun org-map-tree (fun)
8009 "Call FUN for every heading underneath the current one."
8010 (org-back-to-heading)
8011 (let ((level (funcall outline-level)))
8012 (save-excursion
8013 (funcall fun)
8014 (while (and (progn
8015 (outline-next-heading)
8016 (> (funcall outline-level) level))
8017 (not (eobp)))
8018 (funcall fun)))))
8020 (defun org-map-region (fun beg end)
8021 "Call FUN for every heading between BEG and END."
8022 (let ((org-ignore-region t))
8023 (save-excursion
8024 (setq end (copy-marker end))
8025 (goto-char beg)
8026 (if (and (re-search-forward org-outline-regexp-bol nil t)
8027 (< (point) end))
8028 (funcall fun))
8029 (while (and (progn
8030 (outline-next-heading)
8031 (< (point) end))
8032 (not (eobp)))
8033 (funcall fun)))))
8035 (defvar org-property-end-re) ; silence byte-compiler
8036 (defun org-fixup-indentation (diff)
8037 "Change the indentation in the current entry by DIFF.
8038 However, if any line in the current entry has no indentation, or if it
8039 would end up with no indentation after the change, nothing at all is done."
8040 (save-excursion
8041 (let ((end (save-excursion (outline-next-heading)
8042 (point-marker)))
8043 (prohibit (if (> diff 0)
8044 "^\\S-"
8045 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8046 col)
8047 (unless (save-excursion (end-of-line 1)
8048 (re-search-forward prohibit end t))
8049 (while (and (< (point) end)
8050 (re-search-forward "^[ \t]+" end t))
8051 (goto-char (match-end 0))
8052 (setq col (current-column))
8053 (if (< diff 0) (replace-match ""))
8054 (org-indent-to-column (+ diff col))))
8055 (move-marker end nil))))
8057 (defun org-convert-to-odd-levels ()
8058 "Convert an org-mode file with all levels allowed to one with odd levels.
8059 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8060 level 5 etc."
8061 (interactive)
8062 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8063 (let ((outline-level 'org-outline-level)
8064 (org-odd-levels-only nil) n)
8065 (save-excursion
8066 (goto-char (point-min))
8067 (while (re-search-forward "^\\*\\*+ " nil t)
8068 (setq n (- (length (match-string 0)) 2))
8069 (while (>= (setq n (1- n)) 0)
8070 (org-demote))
8071 (end-of-line 1))))))
8073 (defun org-convert-to-oddeven-levels ()
8074 "Convert an org-mode file with only odd levels to one with odd/even levels.
8075 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8076 file contains a section with an even level, conversion would
8077 destroy the structure of the file. An error is signaled in this
8078 case."
8079 (interactive)
8080 (goto-char (point-min))
8081 ;; First check if there are no even levels
8082 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8083 (org-show-context t)
8084 (error "Not all levels are odd in this file. Conversion not possible"))
8085 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8086 (let ((outline-regexp org-outline-regexp)
8087 (outline-level 'org-outline-level)
8088 (org-odd-levels-only nil) n)
8089 (save-excursion
8090 (goto-char (point-min))
8091 (while (re-search-forward "^\\*\\*+ " nil t)
8092 (setq n (/ (1- (length (match-string 0))) 2))
8093 (while (>= (setq n (1- n)) 0)
8094 (org-promote))
8095 (end-of-line 1))))))
8097 (defun org-tr-level (n)
8098 "Make N odd if required."
8099 (if org-odd-levels-only (1+ (/ n 2)) n))
8101 ;;; Vertical tree motion, cutting and pasting of subtrees
8103 (defun org-move-subtree-up (&optional arg)
8104 "Move the current subtree up past ARG headlines of the same level."
8105 (interactive "p")
8106 (org-move-subtree-down (- (prefix-numeric-value arg))))
8108 (defun org-move-subtree-down (&optional arg)
8109 "Move the current subtree down past ARG headlines of the same level."
8110 (interactive "p")
8111 (setq arg (prefix-numeric-value arg))
8112 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8113 'org-get-last-sibling))
8114 (ins-point (make-marker))
8115 (cnt (abs arg))
8116 (col (current-column))
8117 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8118 ;; Select the tree
8119 (org-back-to-heading)
8120 (setq beg0 (point))
8121 (save-excursion
8122 (setq ne-beg (org-back-over-empty-lines))
8123 (setq beg (point)))
8124 (save-match-data
8125 (save-excursion (outline-end-of-heading)
8126 (setq folded (outline-invisible-p)))
8127 (outline-end-of-subtree))
8128 (outline-next-heading)
8129 (setq ne-end (org-back-over-empty-lines))
8130 (setq end (point))
8131 (goto-char beg0)
8132 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8133 ;; include less whitespace
8134 (save-excursion
8135 (goto-char beg)
8136 (forward-line (- ne-beg ne-end))
8137 (setq beg (point))))
8138 ;; Find insertion point, with error handling
8139 (while (> cnt 0)
8140 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8141 (progn (goto-char beg0)
8142 (user-error "Cannot move past superior level or buffer limit")))
8143 (setq cnt (1- cnt)))
8144 (if (> arg 0)
8145 ;; Moving forward - still need to move over subtree
8146 (progn (org-end-of-subtree t t)
8147 (save-excursion
8148 (org-back-over-empty-lines)
8149 (or (bolp) (newline)))))
8150 (setq ne-ins (org-back-over-empty-lines))
8151 (move-marker ins-point (point))
8152 (setq txt (buffer-substring beg end))
8153 (org-save-markers-in-region beg end)
8154 (delete-region beg end)
8155 (org-remove-empty-overlays-at beg)
8156 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8157 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8158 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8159 (let ((bbb (point)))
8160 (insert-before-markers txt)
8161 (org-reinstall-markers-in-region bbb)
8162 (move-marker ins-point bbb))
8163 (or (bolp) (insert "\n"))
8164 (setq ins-end (point))
8165 (goto-char ins-point)
8166 (org-skip-whitespace)
8167 (when (and (< arg 0)
8168 (org-first-sibling-p)
8169 (> ne-ins ne-beg))
8170 ;; Move whitespace back to beginning
8171 (save-excursion
8172 (goto-char ins-end)
8173 (let ((kill-whole-line t))
8174 (kill-line (- ne-ins ne-beg)) (point)))
8175 (insert (make-string (- ne-ins ne-beg) ?\n)))
8176 (move-marker ins-point nil)
8177 (if folded
8178 (hide-subtree)
8179 (org-show-entry)
8180 (show-children)
8181 (org-cycle-hide-drawers 'children))
8182 (org-clean-visibility-after-subtree-move)
8183 ;; move back to the initial column we were at
8184 (move-to-column col)))
8186 (defvar org-subtree-clip ""
8187 "Clipboard for cut and paste of subtrees.
8188 This is actually only a copy of the kill, because we use the normal kill
8189 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8191 (defvar org-subtree-clip-folded nil
8192 "Was the last copied subtree folded?
8193 This is used to fold the tree back after pasting.")
8195 (defun org-cut-subtree (&optional n)
8196 "Cut the current subtree into the clipboard.
8197 With prefix arg N, cut this many sequential subtrees.
8198 This is a short-hand for marking the subtree and then cutting it."
8199 (interactive "p")
8200 (org-copy-subtree n 'cut))
8202 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8203 "Copy the current subtree it in the clipboard.
8204 With prefix arg N, copy this many sequential subtrees.
8205 This is a short-hand for marking the subtree and then copying it.
8206 If CUT is non-nil, actually cut the subtree.
8207 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8208 of some markers in the region, even if CUT is non-nil. This is
8209 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8210 (interactive "p")
8211 (let (beg end folded (beg0 (point)))
8212 (if (org-called-interactively-p 'any)
8213 (org-back-to-heading nil) ; take what looks like a subtree
8214 (org-back-to-heading t)) ; take what is really there
8215 (setq beg (point))
8216 (skip-chars-forward " \t\r\n")
8217 (save-match-data
8218 (if nosubtrees
8219 (outline-next-heading)
8220 (save-excursion (outline-end-of-heading)
8221 (setq folded (outline-invisible-p)))
8222 (condition-case nil
8223 (org-forward-heading-same-level (1- n) t)
8224 (error nil))
8225 (org-end-of-subtree t t)))
8226 (setq end (point))
8227 (goto-char beg0)
8228 (when (> end beg)
8229 (setq org-subtree-clip-folded folded)
8230 (when (or cut force-store-markers)
8231 (org-save-markers-in-region beg end))
8232 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8233 (setq org-subtree-clip (current-kill 0))
8234 (message "%s: Subtree(s) with %d characters"
8235 (if cut "Cut" "Copied")
8236 (length org-subtree-clip)))))
8238 (defun org-paste-subtree (&optional level tree for-yank)
8239 "Paste the clipboard as a subtree, with modification of headline level.
8240 The entire subtree is promoted or demoted in order to match a new headline
8241 level.
8243 If the cursor is at the beginning of a headline, the same level as
8244 that headline is used to paste the tree.
8246 If not, the new level is derived from the *visible* headings
8247 before and after the insertion point, and taken to be the inferior headline
8248 level of the two. So if the previous visible heading is level 3 and the
8249 next is level 4 (or vice versa), level 4 will be used for insertion.
8250 This makes sure that the subtree remains an independent subtree and does
8251 not swallow low level entries.
8253 You can also force a different level, either by using a numeric prefix
8254 argument, or by inserting the heading marker by hand. For example, if the
8255 cursor is after \"*****\", then the tree will be shifted to level 5.
8257 If optional TREE is given, use this text instead of the kill ring.
8259 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8260 move back over whitespace before inserting, and move point to the end of
8261 the inserted text when done."
8262 (interactive "P")
8263 (setq tree (or tree (and kill-ring (current-kill 0))))
8264 (unless (org-kill-is-subtree-p tree)
8265 (user-error "%s"
8266 (substitute-command-keys
8267 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8268 (org-with-limited-levels
8269 (let* ((visp (not (outline-invisible-p)))
8270 (txt tree)
8271 (^re_ "\\(\\*+\\)[ \t]*")
8272 (old-level (if (string-match org-outline-regexp-bol txt)
8273 (- (match-end 0) (match-beginning 0) 1)
8274 -1))
8275 (force-level (cond (level (prefix-numeric-value level))
8276 ((and (looking-at "[ \t]*$")
8277 (string-match
8278 "^\\*+$" (buffer-substring
8279 (point-at-bol) (point))))
8280 (- (match-end 1) (match-beginning 1)))
8281 ((and (bolp)
8282 (looking-at org-outline-regexp))
8283 (- (match-end 0) (point) 1))))
8284 (previous-level (save-excursion
8285 (condition-case nil
8286 (progn
8287 (outline-previous-visible-heading 1)
8288 (if (looking-at ^re_)
8289 (- (match-end 0) (match-beginning 0) 1)
8291 (error 1))))
8292 (next-level (save-excursion
8293 (condition-case nil
8294 (progn
8295 (or (looking-at org-outline-regexp)
8296 (outline-next-visible-heading 1))
8297 (if (looking-at ^re_)
8298 (- (match-end 0) (match-beginning 0) 1)
8300 (error 1))))
8301 (new-level (or force-level (max previous-level next-level)))
8302 (shift (if (or (= old-level -1)
8303 (= new-level -1)
8304 (= old-level new-level))
8306 (- new-level old-level)))
8307 (delta (if (> shift 0) -1 1))
8308 (func (if (> shift 0) 'org-demote 'org-promote))
8309 (org-odd-levels-only nil)
8310 beg end newend)
8311 ;; Remove the forced level indicator
8312 (if force-level
8313 (delete-region (point-at-bol) (point)))
8314 ;; Paste
8315 (beginning-of-line (if (bolp) 1 2))
8316 (setq beg (point))
8317 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8318 (insert-before-markers txt)
8319 (unless (string-match "\n\\'" txt) (insert "\n"))
8320 (setq newend (point))
8321 (org-reinstall-markers-in-region beg)
8322 (setq end (point))
8323 (goto-char beg)
8324 (skip-chars-forward " \t\n\r")
8325 (setq beg (point))
8326 (if (and (outline-invisible-p) visp)
8327 (save-excursion (outline-show-heading)))
8328 ;; Shift if necessary
8329 (unless (= shift 0)
8330 (save-restriction
8331 (narrow-to-region beg end)
8332 (while (not (= shift 0))
8333 (org-map-region func (point-min) (point-max))
8334 (setq shift (+ delta shift)))
8335 (goto-char (point-min))
8336 (setq newend (point-max))))
8337 (when (or (org-called-interactively-p 'interactive) for-yank)
8338 (message "Clipboard pasted as level %d subtree" new-level))
8339 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8340 kill-ring
8341 (eq org-subtree-clip (current-kill 0))
8342 org-subtree-clip-folded)
8343 ;; The tree was folded before it was killed/copied
8344 (hide-subtree))
8345 (and for-yank (goto-char newend)))))
8347 (defun org-kill-is-subtree-p (&optional txt)
8348 "Check if the current kill is an outline subtree, or a set of trees.
8349 Returns nil if kill does not start with a headline, or if the first
8350 headline level is not the largest headline level in the tree.
8351 So this will actually accept several entries of equal levels as well,
8352 which is OK for `org-paste-subtree'.
8353 If optional TXT is given, check this string instead of the current kill."
8354 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8355 (re (org-get-limited-outline-regexp))
8356 (^re (concat "^" re))
8357 (start-level (and kill
8358 (string-match
8359 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8360 kill)
8361 (- (match-end 2) (match-beginning 2) 1)))
8362 (start (1+ (or (match-beginning 2) -1))))
8363 (if (not start-level)
8364 (progn
8365 nil) ;; does not even start with a heading
8366 (catch 'exit
8367 (while (setq start (string-match ^re kill (1+ start)))
8368 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8369 (throw 'exit nil)))
8370 t))))
8372 (defvar org-markers-to-move nil
8373 "Markers that should be moved with a cut-and-paste operation.
8374 Those markers are stored together with their positions relative to
8375 the start of the region.")
8377 (defun org-save-markers-in-region (beg end)
8378 "Check markers in region.
8379 If these markers are between BEG and END, record their position relative
8380 to BEG, so that after moving the block of text, we can put the markers back
8381 into place.
8382 This function gets called just before an entry or tree gets cut from the
8383 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8384 called immediately, to move the markers with the entries."
8385 (setq org-markers-to-move nil)
8386 (when (featurep 'org-clock)
8387 (org-clock-save-markers-for-cut-and-paste beg end))
8388 (when (featurep 'org-agenda)
8389 (org-agenda-save-markers-for-cut-and-paste beg end)))
8391 (defun org-check-and-save-marker (marker beg end)
8392 "Check if MARKER is between BEG and END.
8393 If yes, remember the marker and the distance to BEG."
8394 (when (and (marker-buffer marker)
8395 (equal (marker-buffer marker) (current-buffer)))
8396 (if (and (>= marker beg) (< marker end))
8397 (push (cons marker (- marker beg)) org-markers-to-move))))
8399 (defun org-reinstall-markers-in-region (beg)
8400 "Move all remembered markers to their position relative to BEG."
8401 (mapc (lambda (x)
8402 (move-marker (car x) (+ beg (cdr x))))
8403 org-markers-to-move)
8404 (setq org-markers-to-move nil))
8406 (defun org-narrow-to-subtree ()
8407 "Narrow buffer to the current subtree."
8408 (interactive)
8409 (save-excursion
8410 (save-match-data
8411 (org-with-limited-levels
8412 (narrow-to-region
8413 (progn (org-back-to-heading t) (point))
8414 (progn (org-end-of-subtree t t)
8415 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8416 (point)))))))
8418 (defun org-narrow-to-block ()
8419 "Narrow buffer to the current block."
8420 (interactive)
8421 (let* ((case-fold-search t)
8422 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8423 "^[ \t]*#\\+end_.*")))
8424 (if blockp
8425 (narrow-to-region (car blockp) (cdr blockp))
8426 (user-error "Not in a block"))))
8428 (eval-when-compile
8429 (defvar org-property-drawer-re))
8431 (defvar org-property-start-re) ;; defined below
8432 (defun org-clone-subtree-with-time-shift (n &optional shift)
8433 "Clone the task (subtree) at point N times.
8434 The clones will be inserted as siblings.
8436 In interactive use, the user will be prompted for the number of
8437 clones to be produced. If the entry has a timestamp, the user
8438 will also be prompted for a time shift, which may be a repeater
8439 as used in time stamps, for example `+3d'. To disable this,
8440 you can call the function with a universal prefix argument.
8442 When a valid repeater is given and the entry contains any time
8443 stamps, the clones will become a sequence in time, with time
8444 stamps in the subtree shifted for each clone produced. If SHIFT
8445 is nil or the empty string, time stamps will be left alone. The
8446 ID property of the original subtree is removed.
8448 If the original subtree did contain time stamps with a repeater,
8449 the following will happen:
8450 - the repeater will be removed in each clone
8451 - an additional clone will be produced, with the current, unshifted
8452 date(s) in the entry.
8453 - the original entry will be placed *after* all the clones, with
8454 repeater intact.
8455 - the start days in the repeater in the original entry will be shifted
8456 to past the last clone.
8457 In this way you can spell out a number of instances of a repeating task,
8458 and still retain the repeater to cover future instances of the task."
8459 (interactive "nNumber of clones to produce: ")
8460 (let ((shift
8461 (or shift
8462 (if (and (not (equal current-prefix-arg '(4)))
8463 (save-excursion
8464 (re-search-forward org-ts-regexp-both
8465 (save-excursion
8466 (org-end-of-subtree t)
8467 (point)) t)))
8468 (read-from-minibuffer
8469 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8470 ""))) ;; No time shift
8471 (n-no-remove -1)
8472 (drawer-re org-drawer-regexp)
8473 beg end template task idprop
8474 shift-n shift-what doshift nmin nmax)
8475 (if (not (and (integerp n) (> n 0)))
8476 (error "Invalid number of replications %s" n))
8477 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8478 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8479 shift)))
8480 (error "Invalid shift specification %s" shift))
8481 (when doshift
8482 (setq shift-n (string-to-number (match-string 1 shift))
8483 shift-what (cdr (assoc (match-string 2 shift)
8484 '(("d" . day) ("w" . week)
8485 ("m" . month) ("y" . year))))))
8486 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8487 (setq nmin 1 nmax n)
8488 (org-back-to-heading t)
8489 (setq beg (point))
8490 (setq idprop (org-entry-get nil "ID"))
8491 (org-end-of-subtree t t)
8492 (or (bolp) (insert "\n"))
8493 (setq end (point))
8494 (setq template (buffer-substring beg end))
8495 (when (and doshift
8496 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8497 (delete-region beg end)
8498 (setq end beg)
8499 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8500 (goto-char end)
8501 (loop for n from nmin to nmax do
8502 ;; prepare clone
8503 (with-temp-buffer
8504 (insert template)
8505 (org-mode)
8506 (goto-char (point-min))
8507 (org-show-subtree)
8508 (and idprop (if org-clone-delete-id
8509 (org-entry-delete nil "ID")
8510 (org-id-get-create t)))
8511 (unless (= n 0)
8512 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8513 (kill-whole-line))
8514 (goto-char (point-min))
8515 (while (re-search-forward drawer-re nil t)
8516 (mapc (lambda (d)
8517 (org-remove-empty-drawer-at d (point))) org-drawers)))
8518 (goto-char (point-min))
8519 (when doshift
8520 (while (re-search-forward org-ts-regexp-both nil t)
8521 (org-timestamp-change (* n shift-n) shift-what))
8522 (unless (= n n-no-remove)
8523 (goto-char (point-min))
8524 (while (re-search-forward org-ts-regexp nil t)
8525 (save-excursion
8526 (goto-char (match-beginning 0))
8527 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8528 (delete-region (match-beginning 1) (match-end 1)))))))
8529 (setq task (buffer-string)))
8530 (insert task))
8531 (goto-char beg)))
8533 ;;; Outline Sorting
8535 (defun org-sort (with-case)
8536 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8537 Optional argument WITH-CASE means sort case-sensitively."
8538 (interactive "P")
8539 (cond
8540 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8541 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8543 (org-call-with-arg 'org-sort-entries with-case))))
8545 (defun org-sort-remove-invisible (s)
8546 "Remove invisible links from string S."
8547 (remove-text-properties 0 (length s) org-rm-props s)
8548 (while (string-match org-bracket-link-regexp s)
8549 (setq s (replace-match (if (match-end 2)
8550 (match-string 3 s)
8551 (match-string 1 s)) t t s)))
8552 (let ((st (format " %s " s)))
8553 (while (string-match org-emph-re st)
8554 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8555 (setq s (substring st 1 -1)))
8558 (defvar org-priority-regexp) ; defined later in the file
8560 (defvar org-after-sorting-entries-or-items-hook nil
8561 "Hook that is run after a bunch of entries or items have been sorted.
8562 When children are sorted, the cursor is in the parent line when this
8563 hook gets called. When a region or a plain list is sorted, the cursor
8564 will be in the first entry of the sorted region/list.")
8566 (defun org-sort-entries
8567 (&optional with-case sorting-type getkey-func compare-func property)
8568 "Sort entries on a certain level of an outline tree.
8569 If there is an active region, the entries in the region are sorted.
8570 Else, if the cursor is before the first entry, sort the top-level items.
8571 Else, the children of the entry at point are sorted.
8573 Sorting can be alphabetically, numerically, by date/time as given by
8574 a time stamp, by a property, by priority order, or by a custom function.
8576 The command prompts for the sorting type unless it has been given to the
8577 function through the SORTING-TYPE argument, which needs to be a character,
8578 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8579 precise meaning of each character:
8581 n Numerically, by converting the beginning of the entry/item to a number.
8582 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8583 o By order of TODO keywords.
8584 t By date/time, either the first active time stamp in the entry, or, if
8585 none exist, by the first inactive one.
8586 s By the scheduled date/time.
8587 d By deadline date/time.
8588 c By creation time, which is assumed to be the first inactive time stamp
8589 at the beginning of a line.
8590 p By priority according to the cookie.
8591 r By the value of a property.
8593 Capital letters will reverse the sort order.
8595 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8596 called with point at the beginning of the record. It must return either
8597 a string or a number that should serve as the sorting key for that record.
8599 Comparing entries ignores case by default. However, with an optional argument
8600 WITH-CASE, the sorting considers case as well.
8602 Sorting is done against the visible part of the headlines, it ignores hidden
8603 links."
8604 (interactive "P")
8605 (let ((case-func (if with-case 'identity 'downcase))
8606 (cmstr
8607 ;; The clock marker is lost when using `sort-subr', let's
8608 ;; store the clocking string.
8609 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8610 (save-excursion
8611 (goto-char org-clock-marker)
8612 (looking-back "^.*") (match-string-no-properties 0))))
8613 start beg end stars re re2
8614 txt what tmp)
8615 ;; Find beginning and end of region to sort
8616 (cond
8617 ((org-region-active-p)
8618 ;; we will sort the region
8619 (setq end (region-end)
8620 what "region")
8621 (goto-char (region-beginning))
8622 (if (not (org-at-heading-p)) (outline-next-heading))
8623 (setq start (point)))
8624 ((or (org-at-heading-p)
8625 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8626 ;; we will sort the children of the current headline
8627 (org-back-to-heading)
8628 (setq start (point)
8629 end (progn (org-end-of-subtree t t)
8630 (or (bolp) (insert "\n"))
8631 (org-back-over-empty-lines)
8632 (point))
8633 what "children")
8634 (goto-char start)
8635 (show-subtree)
8636 (outline-next-heading))
8638 ;; we will sort the top-level entries in this file
8639 (goto-char (point-min))
8640 (or (org-at-heading-p) (outline-next-heading))
8641 (setq start (point))
8642 (goto-char (point-max))
8643 (beginning-of-line 1)
8644 (when (looking-at ".*?\\S-")
8645 ;; File ends in a non-white line
8646 (end-of-line 1)
8647 (insert "\n"))
8648 (setq end (point-max))
8649 (setq what "top-level")
8650 (goto-char start)
8651 (show-all)))
8653 (setq beg (point))
8654 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8656 (looking-at "\\(\\*+\\)")
8657 (setq stars (match-string 1)
8658 re (concat "^" (regexp-quote stars) " +")
8659 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8660 txt (buffer-substring beg end))
8661 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8662 (if (and (not (equal stars "*")) (string-match re2 txt))
8663 (user-error "Region to sort contains a level above the first entry"))
8665 (unless sorting-type
8666 (message
8667 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8668 [t]ime [s]cheduled [d]eadline [c]reated
8669 A/N/P/R/O/F/T/S/D/C means reversed:"
8670 what)
8671 (setq sorting-type (read-char-exclusive))
8673 (unless getkey-func
8674 (and (= (downcase sorting-type) ?f)
8675 (setq getkey-func
8676 (org-icompleting-read "Sort using function: "
8677 obarray 'fboundp t nil nil))
8678 (setq getkey-func (intern getkey-func))))
8680 (and (= (downcase sorting-type) ?r)
8681 (not property)
8682 (setq property
8683 (org-icompleting-read "Property: "
8684 (mapcar 'list (org-buffer-property-keys t))
8685 nil t))))
8687 (message "Sorting entries...")
8689 (save-restriction
8690 (narrow-to-region start end)
8691 (let ((dcst (downcase sorting-type))
8692 (case-fold-search nil)
8693 (now (current-time)))
8694 (sort-subr
8695 (/= dcst sorting-type)
8696 ;; This function moves to the beginning character of the "record" to
8697 ;; be sorted.
8698 (lambda nil
8699 (if (re-search-forward re nil t)
8700 (goto-char (match-beginning 0))
8701 (goto-char (point-max))))
8702 ;; This function moves to the last character of the "record" being
8703 ;; sorted.
8704 (lambda nil
8705 (save-match-data
8706 (condition-case nil
8707 (outline-forward-same-level 1)
8708 (error
8709 (goto-char (point-max))))))
8710 ;; This function returns the value that gets sorted against.
8711 (lambda nil
8712 (cond
8713 ((= dcst ?n)
8714 (if (looking-at org-complex-heading-regexp)
8715 (string-to-number (org-sort-remove-invisible (match-string 4)))
8716 nil))
8717 ((= dcst ?a)
8718 (if (looking-at org-complex-heading-regexp)
8719 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8720 nil))
8721 ((= dcst ?t)
8722 (let ((end (save-excursion (outline-next-heading) (point))))
8723 (if (or (re-search-forward org-ts-regexp end t)
8724 (re-search-forward org-ts-regexp-both end t))
8725 (org-time-string-to-seconds (match-string 0))
8726 (org-float-time now))))
8727 ((= dcst ?c)
8728 (let ((end (save-excursion (outline-next-heading) (point))))
8729 (if (re-search-forward
8730 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8731 end t)
8732 (org-time-string-to-seconds (match-string 0))
8733 (org-float-time now))))
8734 ((= dcst ?s)
8735 (let ((end (save-excursion (outline-next-heading) (point))))
8736 (if (re-search-forward org-scheduled-time-regexp end t)
8737 (org-time-string-to-seconds (match-string 1))
8738 (org-float-time now))))
8739 ((= dcst ?d)
8740 (let ((end (save-excursion (outline-next-heading) (point))))
8741 (if (re-search-forward org-deadline-time-regexp end t)
8742 (org-time-string-to-seconds (match-string 1))
8743 (org-float-time now))))
8744 ((= dcst ?p)
8745 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8746 (string-to-char (match-string 2))
8747 org-default-priority))
8748 ((= dcst ?r)
8749 (or (org-entry-get nil property) ""))
8750 ((= dcst ?o)
8751 (if (looking-at org-complex-heading-regexp)
8752 (- 9999 (length (member (match-string 2)
8753 org-todo-keywords-1)))))
8754 ((= dcst ?f)
8755 (if getkey-func
8756 (progn
8757 (setq tmp (funcall getkey-func))
8758 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8759 tmp)
8760 (error "Invalid key function `%s'" getkey-func)))
8761 (t (error "Invalid sorting type `%c'" sorting-type))))
8763 (cond
8764 ((= dcst ?a) 'string<)
8765 ((= dcst ?f) compare-func)
8766 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8767 (run-hooks 'org-after-sorting-entries-or-items-hook)
8768 ;; Reset the clock marker if needed
8769 (when cmstr
8770 (save-excursion
8771 (goto-char start)
8772 (search-forward cmstr nil t)
8773 (move-marker org-clock-marker (point))))
8774 (message "Sorting entries...done")))
8776 (defun org-do-sort (table what &optional with-case sorting-type)
8777 "Sort TABLE of WHAT according to SORTING-TYPE.
8778 The user will be prompted for the SORTING-TYPE if the call to this
8779 function does not specify it. WHAT is only for the prompt, to indicate
8780 what is being sorted. The sorting key will be extracted from
8781 the car of the elements of the table.
8782 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8783 (unless sorting-type
8784 (message
8785 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8786 what)
8787 (setq sorting-type (read-char-exclusive)))
8788 (let ((dcst (downcase sorting-type))
8789 extractfun comparefun)
8790 ;; Define the appropriate functions
8791 (cond
8792 ((= dcst ?n)
8793 (setq extractfun 'string-to-number
8794 comparefun (if (= dcst sorting-type) '< '>)))
8795 ((= dcst ?a)
8796 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8797 (lambda(x) (downcase (org-sort-remove-invisible x))))
8798 comparefun (if (= dcst sorting-type)
8799 'string<
8800 (lambda (a b) (and (not (string< a b))
8801 (not (string= a b)))))))
8802 ((= dcst ?t)
8803 (setq extractfun
8804 (lambda (x)
8805 (if (or (string-match org-ts-regexp x)
8806 (string-match org-ts-regexp-both x))
8807 (org-float-time
8808 (org-time-string-to-time (match-string 0 x)))
8810 comparefun (if (= dcst sorting-type) '< '>)))
8811 (t (error "Invalid sorting type `%c'" sorting-type)))
8813 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8814 table)
8815 (lambda (a b) (funcall comparefun (car a) (car b))))))
8818 ;;; The orgstruct minor mode
8820 ;; Define a minor mode which can be used in other modes in order to
8821 ;; integrate the org-mode structure editing commands.
8823 ;; This is really a hack, because the org-mode structure commands use
8824 ;; keys which normally belong to the major mode. Here is how it
8825 ;; works: The minor mode defines all the keys necessary to operate the
8826 ;; structure commands, but wraps the commands into a function which
8827 ;; tests if the cursor is currently at a headline or a plain list
8828 ;; item. If that is the case, the structure command is used,
8829 ;; temporarily setting many Org-mode variables like regular
8830 ;; expressions for filling etc. However, when any of those keys is
8831 ;; used at a different location, function uses `key-binding' to look
8832 ;; up if the key has an associated command in another currently active
8833 ;; keymap (minor modes, major mode, global), and executes that
8834 ;; command. There might be problems if any of the keys is otherwise
8835 ;; used as a prefix key.
8837 (defcustom orgstruct-heading-prefix-regexp ""
8838 "Regexp that matches the custom prefix of Org headlines in
8839 orgstruct(++)-mode."
8840 :group 'org
8841 :version "24.4"
8842 :package-version '(Org . "8.3")
8843 :type 'regexp)
8844 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8846 (defcustom orgstruct-setup-hook nil
8847 "Hook run after orgstruct-mode-map is filled."
8848 :group 'org
8849 :version "24.4"
8850 :package-version '(Org . "8.0")
8851 :type 'hook)
8853 (defvar orgstruct-initialized nil)
8855 (defvar org-local-vars nil
8856 "List of local variables, for use by `orgstruct-mode'.")
8858 ;;;###autoload
8859 (define-minor-mode orgstruct-mode
8860 "Toggle the minor mode `orgstruct-mode'.
8861 This mode is for using Org-mode structure commands in other
8862 modes. The following keys behave as if Org-mode were active, if
8863 the cursor is on a headline, or on a plain list item (both as
8864 defined by Org-mode)."
8865 nil " OrgStruct" (make-sparse-keymap)
8866 (funcall (if orgstruct-mode
8867 'add-to-invisibility-spec
8868 'remove-from-invisibility-spec)
8869 '(outline . t))
8870 (when orgstruct-mode
8871 (org-load-modules-maybe)
8872 (unless orgstruct-initialized
8873 (orgstruct-setup)
8874 (setq orgstruct-initialized t))))
8876 ;;;###autoload
8877 (defun turn-on-orgstruct ()
8878 "Unconditionally turn on `orgstruct-mode'."
8879 (orgstruct-mode 1))
8881 (defvar org-fb-vars nil)
8882 (make-variable-buffer-local 'org-fb-vars)
8883 (defun orgstruct++-mode (&optional arg)
8884 "Toggle `orgstruct-mode', the enhanced version of it.
8885 In addition to setting orgstruct-mode, this also exports all
8886 indentation and autofilling variables from org-mode into the
8887 buffer. It will also recognize item context in multiline items."
8888 (interactive "P")
8889 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8890 (if (< arg 1)
8891 (progn (orgstruct-mode -1)
8892 (mapc (lambda(v)
8893 (org-set-local (car v)
8894 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8895 org-fb-vars))
8896 (orgstruct-mode 1)
8897 (setq org-fb-vars nil)
8898 (unless org-local-vars
8899 (setq org-local-vars (org-get-local-variables)))
8900 (let (var val)
8901 (mapc
8902 (lambda (x)
8903 (when (string-match
8904 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8905 (symbol-name (car x)))
8906 (setq var (car x) val (nth 1 x))
8907 (push (list var `(quote ,(eval var))) org-fb-vars)
8908 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8909 org-local-vars)
8910 (org-set-local 'orgstruct-is-++ t))))
8912 (defvar orgstruct-is-++ nil
8913 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8914 (make-variable-buffer-local 'orgstruct-is-++)
8916 ;;;###autoload
8917 (defun turn-on-orgstruct++ ()
8918 "Unconditionally turn on `orgstruct++-mode'."
8919 (orgstruct++-mode 1))
8921 (defun orgstruct-error ()
8922 "Error when there is no default binding for a structure key."
8923 (interactive)
8924 (funcall (if (fboundp 'user-error)
8925 'user-error
8926 'error)
8927 "This key has no function outside structure elements"))
8929 (defun orgstruct-setup ()
8930 "Setup orgstruct keymap."
8931 (dolist (cell '((org-demote . t)
8932 (org-metaleft . t)
8933 (org-metaright . t)
8934 (org-promote . t)
8935 (org-shiftmetaleft . t)
8936 (org-shiftmetaright . t)
8937 org-backward-element
8938 org-backward-heading-same-level
8939 org-ctrl-c-ret
8940 org-ctrl-c-minus
8941 org-ctrl-c-star
8942 org-cycle
8943 org-forward-heading-same-level
8944 org-insert-heading
8945 org-insert-heading-respect-content
8946 org-kill-note-or-show-branches
8947 org-mark-subtree
8948 org-meta-return
8949 org-metadown
8950 org-metaup
8951 org-narrow-to-subtree
8952 org-promote-subtree
8953 org-reveal
8954 org-shiftdown
8955 org-shiftleft
8956 org-shiftmetadown
8957 org-shiftmetaup
8958 org-shiftright
8959 org-shifttab
8960 org-shifttab
8961 org-shiftup
8962 org-show-subtree
8963 org-sort
8964 org-up-element
8965 outline-demote
8966 outline-next-visible-heading
8967 outline-previous-visible-heading
8968 outline-promote
8969 outline-up-heading
8970 show-children))
8971 (let ((f (or (car-safe cell) cell))
8972 (disable-when-heading-prefix (cdr-safe cell)))
8973 (when (fboundp f)
8974 (let ((new-bindings))
8975 (dolist (binding (nconc (where-is-internal f org-mode-map)
8976 (where-is-internal f outline-mode-map)))
8977 (push binding new-bindings)
8978 ;; TODO use local-function-key-map
8979 (dolist (rep '(("<tab>" . "TAB")
8980 ("<return>" . "RET")
8981 ("<escape>" . "ESC")
8982 ("<delete>" . "DEL")))
8983 (setq binding (read-kbd-macro
8984 (let ((case-fold-search))
8985 (replace-regexp-in-string
8986 (regexp-quote (cdr rep))
8987 (car rep)
8988 (key-description binding)))))
8989 (pushnew binding new-bindings :test 'equal)))
8990 (dolist (binding new-bindings)
8991 (let ((key (lookup-key orgstruct-mode-map binding)))
8992 (when (or (not key) (numberp key))
8993 (condition-case nil
8994 (org-defkey orgstruct-mode-map
8995 binding
8996 (orgstruct-make-binding f binding disable-when-heading-prefix))
8997 (error nil)))))))))
8998 (run-hooks 'orgstruct-setup-hook))
9000 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9001 "Create a function for binding in the structure minor mode.
9002 FUN is the command to call inside a table. KEY is the key that
9003 should be checked in for a command to execute outside of tables.
9004 Non-nil `disable-when-heading-prefix' means to disable the command
9005 if `orgstruct-heading-prefix-regexp' is not empty."
9006 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9007 (let ((nname name)
9008 (i 0))
9009 (while (fboundp (intern nname))
9010 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9011 (setq name (intern nname)))
9012 (eval
9013 (let ((bindings '((org-heading-regexp
9014 (concat "^"
9015 orgstruct-heading-prefix-regexp
9016 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9017 (org-outline-regexp
9018 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9019 (org-outline-regexp-bol
9020 (concat "^" org-outline-regexp))
9021 (outline-regexp org-outline-regexp)
9022 (outline-heading-end-regexp "\n")
9023 (outline-level 'org-outline-level)
9024 (outline-heading-alist))))
9025 `(defun ,name (arg)
9026 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9027 "Outside of structure, run the binding of `"
9028 (key-description key) "'."
9029 (when disable-when-heading-prefix
9030 (concat
9031 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9032 "back to the default binding due to limitations of Org's implementation of\n"
9033 "`" (symbol-name fun) "'.")))
9034 (interactive "p")
9035 (let* ((disable
9036 ,(and disable-when-heading-prefix
9037 '(not (string= orgstruct-heading-prefix-regexp ""))))
9038 (fallback
9039 (or disable
9040 (not
9041 (let* ,bindings
9042 (org-context-p 'headline 'item
9043 ,(when (memq fun
9044 '(org-insert-heading
9045 org-insert-heading-respect-content
9046 org-meta-return))
9047 '(when orgstruct-is-++
9048 'item-body))))))))
9049 (if fallback
9050 (let* ((orgstruct-mode)
9051 (binding
9052 (loop with key = ,key
9053 for rep in
9054 '(nil
9055 ("<\\([^>]*\\)tab>" . "\\1TAB")
9056 ("<\\([^>]*\\)return>" . "\\1RET")
9057 ("<\\([^>]*\\)escape>" . "\\1ESC")
9058 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9060 (when rep
9061 (setq key (read-kbd-macro
9062 (let ((case-fold-search))
9063 (replace-regexp-in-string
9064 (car rep)
9065 (cdr rep)
9066 (key-description key))))))
9067 thereis (key-binding key))))
9068 (if (keymapp binding)
9069 (org-set-transient-map binding)
9070 (let ((func (or binding
9071 (unless disable
9072 'orgstruct-error))))
9073 (when func
9074 (call-interactively func)))))
9075 (org-run-like-in-org-mode
9076 (lambda ()
9077 (interactive)
9078 (let* ,bindings
9079 (call-interactively ',fun)))))))))
9080 name))
9082 (defun org-contextualize-keys (alist contexts)
9083 "Return valid elements in ALIST depending on CONTEXTS.
9085 `org-agenda-custom-commands' or `org-capture-templates' are the
9086 values used for ALIST, and `org-agenda-custom-commands-contexts'
9087 or `org-capture-templates-contexts' are the associated contexts
9088 definitions."
9089 (let ((contexts
9090 ;; normalize contexts
9091 (mapcar
9092 (lambda(c) (cond ((listp (cadr c))
9093 (list (car c) (car c) (cadr c)))
9094 ((string= "" (cadr c))
9095 (list (car c) (car c) (caddr c)))
9096 (t c))) contexts))
9097 (a alist) c r s)
9098 ;; loop over all commands or templates
9099 (while (setq c (pop a))
9100 (let (vrules repl)
9101 (cond
9102 ((not (assoc (car c) contexts))
9103 (push c r))
9104 ((and (assoc (car c) contexts)
9105 (setq vrules (org-contextualize-validate-key
9106 (car c) contexts)))
9107 (mapc (lambda (vr)
9108 (when (not (equal (car vr) (cadr vr)))
9109 (setq repl vr))) vrules)
9110 (if (not repl) (push c r)
9111 (push (cadr repl) s)
9112 (push
9113 (cons (car c)
9114 (cdr (or (assoc (cadr repl) alist)
9115 (error "Undefined key `%s' as contextual replacement for `%s'"
9116 (cadr repl) (car c)))))
9117 r))))))
9118 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9119 (delq
9121 (delete-dups
9122 (mapcar (lambda (x)
9123 (let ((tpl (car x)))
9124 (when (not (delq
9126 (mapcar (lambda(y)
9127 (equal y tpl)) s))) x)))
9128 (reverse r))))))
9130 (defun org-contextualize-validate-key (key contexts)
9131 "Check CONTEXTS for agenda or capture KEY."
9132 (let (r rr res)
9133 (while (setq r (pop contexts))
9134 (mapc
9135 (lambda (rr)
9136 (when
9137 (and (equal key (car r))
9138 (if (functionp rr) (funcall rr)
9139 (or (and (eq (car rr) 'in-file)
9140 (buffer-file-name)
9141 (string-match (cdr rr) (buffer-file-name)))
9142 (and (eq (car rr) 'in-mode)
9143 (string-match (cdr rr) (symbol-name major-mode)))
9144 (and (eq (car rr) 'in-buffer)
9145 (string-match (cdr rr) (buffer-name)))
9146 (if (and (eq (car rr) 'not-in-file)
9147 (buffer-file-name))
9148 (not (string-match (cdr rr) (buffer-file-name)))
9150 (when (eq (car rr) 'not-in-mode)
9151 (not (string-match (cdr rr) (symbol-name major-mode))))
9152 (when (eq (car rr) 'not-in-buffer)
9153 (not (string-match (cdr rr) (buffer-name)))))))
9154 (push r res)))
9155 (car (last r))))
9156 (delete-dups (delq nil res))))
9158 (defun org-context-p (&rest contexts)
9159 "Check if local context is any of CONTEXTS.
9160 Possible values in the list of contexts are `table', `headline', and `item'."
9161 (let ((pos (point)))
9162 (goto-char (point-at-bol))
9163 (prog1 (or (and (memq 'table contexts)
9164 (looking-at "[ \t]*|"))
9165 (and (memq 'headline contexts)
9166 (looking-at org-outline-regexp))
9167 (and (memq 'item contexts)
9168 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9169 (and (memq 'item-body contexts)
9170 (org-in-item-p)))
9171 (goto-char pos))))
9173 (defun org-get-local-variables ()
9174 "Return a list of all local variables in an Org mode buffer."
9175 (let (varlist)
9176 (with-current-buffer (get-buffer-create "*Org tmp*")
9177 (erase-buffer)
9178 (org-mode)
9179 (setq varlist (buffer-local-variables)))
9180 (kill-buffer "*Org tmp*")
9181 (delq nil
9182 (mapcar
9183 (lambda (x)
9184 (setq x
9185 (if (symbolp x)
9186 (list x)
9187 (list (car x) (cdr x))))
9188 (if (and (not (get (car x) 'org-state))
9189 (string-match
9190 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9191 (symbol-name (car x))))
9192 x nil))
9193 varlist))))
9195 (defun org-clone-local-variables (from-buffer &optional regexp)
9196 "Clone local variables from FROM-BUFFER.
9197 Optional argument REGEXP selects variables to clone."
9198 (mapc
9199 (lambda (pair)
9200 (and (symbolp (car pair))
9201 (or (null regexp)
9202 (string-match regexp (symbol-name (car pair))))
9203 (set (make-local-variable (car pair))
9204 (cdr pair))))
9205 (buffer-local-variables from-buffer)))
9207 ;;;###autoload
9208 (defun org-run-like-in-org-mode (cmd)
9209 "Run a command, pretending that the current buffer is in Org-mode.
9210 This will temporarily bind local variables that are typically bound in
9211 Org-mode to the values they have in Org-mode, and then interactively
9212 call CMD."
9213 (org-load-modules-maybe)
9214 (unless org-local-vars
9215 (setq org-local-vars (org-get-local-variables)))
9216 (let (binds)
9217 (dolist (var org-local-vars)
9218 (when (or (not (boundp (car var)))
9219 (eq (symbol-value (car var))
9220 (default-value (car var))))
9221 (push (list (car var) `(quote ,(cadr var))) binds)))
9222 (eval `(let ,binds
9223 (call-interactively (quote ,cmd))))))
9225 ;;;; Archiving
9227 (defun org-get-category (&optional pos force-refresh)
9228 "Get the category applying to position POS."
9229 (save-match-data
9230 (if force-refresh (org-refresh-category-properties))
9231 (let ((pos (or pos (point))))
9232 (or (get-text-property pos 'org-category)
9233 (progn (org-refresh-category-properties)
9234 (get-text-property pos 'org-category))))))
9236 (defun org-refresh-category-properties ()
9237 "Refresh category text properties in the buffer."
9238 (let ((case-fold-search t)
9239 (inhibit-read-only t)
9240 (def-cat (cond
9241 ((null org-category)
9242 (if buffer-file-name
9243 (file-name-sans-extension
9244 (file-name-nondirectory buffer-file-name))
9245 "???"))
9246 ((symbolp org-category) (symbol-name org-category))
9247 (t org-category)))
9248 beg end cat pos optionp)
9249 (org-with-silent-modifications
9250 (save-excursion
9251 (save-restriction
9252 (widen)
9253 (goto-char (point-min))
9254 (put-text-property (point) (point-max) 'org-category def-cat)
9255 (while (re-search-forward
9256 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9257 (setq pos (match-end 0)
9258 optionp (equal (char-after (match-beginning 0)) ?#)
9259 cat (org-trim (match-string 2)))
9260 (if optionp
9261 (setq beg (point-at-bol) end (point-max))
9262 (org-back-to-heading t)
9263 (setq beg (point) end (org-end-of-subtree t t)))
9264 (put-text-property beg end 'org-category cat)
9265 (put-text-property beg end 'org-category-position beg)
9266 (goto-char pos)))))))
9268 (defun org-refresh-properties (dprop tprop)
9269 "Refresh buffer text properties.
9270 DPROP is the drawer property and TPROP is the corresponding text
9271 property to set."
9272 (let ((case-fold-search t)
9273 (inhibit-read-only t) p)
9274 (org-with-silent-modifications
9275 (save-excursion
9276 (save-restriction
9277 (widen)
9278 (goto-char (point-min))
9279 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9280 (setq p (org-match-string-no-properties 1))
9281 (save-excursion
9282 (org-back-to-heading t)
9283 (put-text-property
9284 (point-at-bol) (outline-next-heading) tprop p))))))))
9287 ;;;; Link Stuff
9289 ;;; Link abbreviations
9291 (defun org-link-expand-abbrev (link)
9292 "Apply replacements as defined in `org-link-abbrev-alist'."
9293 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9294 (let* ((key (match-string 1 link))
9295 (as (or (assoc key org-link-abbrev-alist-local)
9296 (assoc key org-link-abbrev-alist)))
9297 (tag (and (match-end 2) (match-string 3 link)))
9298 rpl)
9299 (if (not as)
9300 link
9301 (setq rpl (cdr as))
9302 (cond
9303 ((symbolp rpl) (funcall rpl tag))
9304 ((string-match "%(\\([^)]+\\))" rpl)
9305 (replace-match
9306 (save-match-data
9307 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9308 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9309 ((string-match "%h" rpl)
9310 (replace-match (url-hexify-string (or tag "")) t t rpl))
9311 (t (concat rpl tag)))))
9312 link))
9314 ;;; Storing and inserting links
9316 (defvar org-insert-link-history nil
9317 "Minibuffer history for links inserted with `org-insert-link'.")
9319 (defvar org-stored-links nil
9320 "Contains the links stored with `org-store-link'.")
9322 (defvar org-store-link-plist nil
9323 "Plist with info about the most recently link created with `org-store-link'.")
9325 (defvar org-link-protocols nil
9326 "Link protocols added to Org-mode using `org-add-link-type'.")
9328 (defvar org-store-link-functions nil
9329 "List of functions that are called to create and store a link.
9330 Each function will be called in turn until one returns a non-nil
9331 value. Each function should check if it is responsible for creating
9332 this link (for example by looking at the major mode).
9333 If not, it must exit and return nil.
9334 If yes, it should return a non-nil value after a calling
9335 `org-store-link-props' with a list of properties and values.
9336 Special properties are:
9338 :type The link prefix, like \"http\". This must be given.
9339 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9340 This is obligatory as well.
9341 :description Optional default description for the second pair
9342 of brackets in an Org-mode link. The user can still change
9343 this when inserting this link into an Org-mode buffer.
9345 In addition to these, any additional properties can be specified
9346 and then used in capture templates.")
9348 (defun org-add-link-type (type &optional follow export)
9349 "Add TYPE to the list of `org-link-types'.
9350 Re-compute all regular expressions depending on `org-link-types'
9352 FOLLOW and EXPORT are two functions.
9354 FOLLOW should take the link path as the single argument and do whatever
9355 is necessary to follow the link, for example find a file or display
9356 a mail message.
9358 EXPORT should format the link path for export to one of the export formats.
9359 It should be a function accepting three arguments:
9361 path the path of the link, the text after the prefix (like \"http:\")
9362 desc the description of the link, if any, or a description added by
9363 org-export-normalize-links if there is none
9364 format the export format, a symbol like `html' or `latex' or `ascii'..
9366 The function may use the FORMAT information to return different values
9367 depending on the format. The return value will be put literally into
9368 the exported file. If the return value is nil, this means Org should
9369 do what it normally does with links which do not have EXPORT defined.
9371 Org-mode has a built-in default for exporting links. If you are happy with
9372 this default, there is no need to define an export function for the link
9373 type. For a simple example of an export function, see `org-bbdb.el'."
9374 (add-to-list 'org-link-types type t)
9375 (org-make-link-regexps)
9376 (if (assoc type org-link-protocols)
9377 (setcdr (assoc type org-link-protocols) (list follow export))
9378 (push (list type follow export) org-link-protocols)))
9380 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9381 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9383 ;;;###autoload
9384 (defun org-store-link (arg)
9385 "\\<org-mode-map>Store an org-link to the current location.
9386 This link is added to `org-stored-links' and can later be inserted
9387 into an org-buffer with \\[org-insert-link].
9389 For some link types, a prefix arg is interpreted.
9390 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9391 For file links, arg negates `org-context-in-file-links'.
9393 A double prefix arg force skipping storing functions that are not
9394 part of Org's core.
9396 A triple prefix arg force storing a link for each line in the
9397 active region."
9398 (interactive "P")
9399 (org-load-modules-maybe)
9400 (if (and (equal arg '(64)) (org-region-active-p))
9401 (save-excursion
9402 (let ((end (region-end)))
9403 (goto-char (region-beginning))
9404 (set-mark (point))
9405 (while (< (point-at-eol) end)
9406 (move-end-of-line 1) (activate-mark)
9407 (let (current-prefix-arg)
9408 (call-interactively 'org-store-link))
9409 (move-beginning-of-line 2)
9410 (set-mark (point)))))
9411 (org-with-limited-levels
9412 (setq org-store-link-plist nil)
9413 (let (link cpltxt desc description search
9414 txt custom-id agenda-link sfuns sfunsn)
9415 (cond
9417 ;; Store a link using an external link type
9418 ((and (not (equal arg '(16)))
9419 (setq sfuns
9420 (delq
9421 nil (mapcar (lambda (f)
9422 (let (fs) (if (funcall f) (push f fs))))
9423 org-store-link-functions))
9424 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9425 (or (and (cdr sfuns)
9426 (funcall (intern
9427 (completing-read
9428 "Which function for creating the link? "
9429 sfunsn nil t (car sfunsn)))))
9430 (funcall (caar sfuns)))
9431 (setq link (plist-get org-store-link-plist :link)
9432 desc (or (plist-get org-store-link-plist
9433 :description) link))))
9435 ;; Store a link from a source code buffer
9436 ((org-src-edit-buffer-p)
9437 (let (label gc)
9438 (while (or (not label)
9439 (save-excursion
9440 (save-restriction
9441 (widen)
9442 (goto-char (point-min))
9443 (re-search-forward
9444 (regexp-quote (format org-coderef-label-format label))
9445 nil t))))
9446 (when label (message "Label exists already") (sit-for 2))
9447 (setq label (read-string "Code line label: " label)))
9448 (end-of-line 1)
9449 (setq link (format org-coderef-label-format label))
9450 (setq gc (- 79 (length link)))
9451 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9452 (insert link)
9453 (setq link (concat "(" label ")") desc nil)))
9455 ;; We are in the agenda, link to referenced location
9456 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9457 (let ((m (or (get-text-property (point) 'org-hd-marker)
9458 (get-text-property (point) 'org-marker))))
9459 (when m
9460 (org-with-point-at m
9461 (setq agenda-link
9462 (if (org-called-interactively-p 'any)
9463 (call-interactively 'org-store-link)
9464 (org-store-link nil)))))))
9466 ((eq major-mode 'calendar-mode)
9467 (let ((cd (calendar-cursor-to-date)))
9468 (setq link
9469 (format-time-string
9470 (car org-time-stamp-formats)
9471 (apply 'encode-time
9472 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9473 nil nil nil))))
9474 (org-store-link-props :type "calendar" :date cd)))
9476 ((eq major-mode 'help-mode)
9477 (setq link (concat "help:" (save-excursion
9478 (goto-char (point-min))
9479 (looking-at "^[^ ]+")
9480 (match-string 0))))
9481 (org-store-link-props :type "help"))
9483 ((eq major-mode 'w3-mode)
9484 (setq cpltxt (if (and (buffer-name)
9485 (not (string-match "Untitled" (buffer-name))))
9486 (buffer-name)
9487 (url-view-url t))
9488 link (url-view-url t))
9489 (org-store-link-props :type "w3" :url (url-view-url t)))
9491 ((eq major-mode 'image-mode)
9492 (setq cpltxt (concat "file:"
9493 (abbreviate-file-name buffer-file-name))
9494 link cpltxt)
9495 (org-store-link-props :type "image" :file buffer-file-name))
9497 ;; In dired, store a link to the file of the current line
9498 ((eq major-mode 'dired-mode)
9499 (let ((file (dired-get-filename nil t)))
9500 (setq file (if file
9501 (abbreviate-file-name
9502 (expand-file-name (dired-get-filename nil t)))
9503 ;; otherwise, no file so use current directory.
9504 default-directory))
9505 (setq cpltxt (concat "file:" file)
9506 link cpltxt)))
9508 ((setq search (run-hook-with-args-until-success
9509 'org-create-file-search-functions))
9510 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9511 "::" search))
9512 (setq cpltxt (or description link)))
9514 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9515 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9516 (cond
9517 ;; Store a link using the target at point
9518 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9519 (setq cpltxt
9520 (concat "file:"
9521 (abbreviate-file-name
9522 (buffer-file-name (buffer-base-buffer)))
9523 "::" (match-string 1))
9524 link cpltxt))
9525 ((and (featurep 'org-id)
9526 (or (eq org-id-link-to-org-use-id t)
9527 (and (org-called-interactively-p 'any)
9528 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9529 (and (eq org-id-link-to-org-use-id
9530 'create-if-interactive-and-no-custom-id)
9531 (not custom-id))))
9532 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9533 ;; Store a link using the ID at point
9534 (setq link (condition-case nil
9535 (prog1 (org-id-store-link)
9536 (setq desc (or (plist-get org-store-link-plist
9537 :description)
9538 "")))
9539 (error
9540 ;; Probably before first headline, link only to file
9541 (concat "file:"
9542 (abbreviate-file-name
9543 (buffer-file-name (buffer-base-buffer))))))))
9545 ;; Just link to current headline
9546 (setq cpltxt (concat "file:"
9547 (abbreviate-file-name
9548 (buffer-file-name (buffer-base-buffer)))))
9549 ;; Add a context search string
9550 (when (org-xor org-context-in-file-links arg)
9551 (let* ((ee (org-element-at-point))
9552 (et (org-element-type ee))
9553 (ev (plist-get (cadr ee) :value))
9554 (ek (plist-get (cadr ee) :key))
9555 (eok (and (stringp ek) (string-match "name" ek))))
9556 (setq txt (cond
9557 ((org-at-heading-p) nil)
9558 ((and (eq et 'keyword) eok) ev)
9559 ((org-region-active-p)
9560 (buffer-substring (region-beginning) (region-end)))))
9561 (when (or (null txt) (string-match "\\S-" txt))
9562 (setq cpltxt
9563 (concat cpltxt "::"
9564 (condition-case nil
9565 (org-make-org-heading-search-string txt)
9566 (error "")))
9567 desc (or (and (eq et 'keyword) eok ev)
9568 (nth 4 (ignore-errors (org-heading-components)))
9569 "NONE")))))
9570 (if (string-match "::\\'" cpltxt)
9571 (setq cpltxt (substring cpltxt 0 -2)))
9572 (setq link cpltxt))))
9574 ((buffer-file-name (buffer-base-buffer))
9575 ;; Just link to this file here.
9576 (setq cpltxt (concat "file:"
9577 (abbreviate-file-name
9578 (buffer-file-name (buffer-base-buffer)))))
9579 ;; Add a context string.
9580 (when (org-xor org-context-in-file-links arg)
9581 (setq txt (if (org-region-active-p)
9582 (buffer-substring (region-beginning) (region-end))
9583 (buffer-substring (point-at-bol) (point-at-eol))))
9584 ;; Only use search option if there is some text.
9585 (when (string-match "\\S-" txt)
9586 (setq cpltxt
9587 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9588 desc "NONE")))
9589 (setq link cpltxt))
9591 ((org-called-interactively-p 'interactive)
9592 (user-error "No method for storing a link from this buffer"))
9594 (t (setq link nil)))
9596 ;; We're done setting link and desc, clean up
9597 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9598 (setq link (or link cpltxt)
9599 desc (or desc cpltxt))
9600 (cond ((equal desc "NONE") (setq desc nil))
9601 ((and desc (string-match org-bracket-link-analytic-regexp desc))
9602 (let ((d0 (match-string 3 desc))
9603 (p0 (match-string 5 desc)))
9604 (setq desc
9605 (replace-regexp-in-string
9606 org-bracket-link-regexp
9607 (concat (or p0 d0)
9608 (if (equal (length (match-string 0 desc))
9609 (length desc)) "*" "")) desc)))))
9611 ;; Return the link
9612 (if (not (and (or (org-called-interactively-p 'any)
9613 executing-kbd-macro) link))
9614 (or agenda-link (and link (org-make-link-string link desc)))
9615 (push (list link desc) org-stored-links)
9616 (message "Stored: %s" (or desc link))
9617 (when custom-id
9618 (setq link (concat "file:" (abbreviate-file-name
9619 (buffer-file-name)) "::#" custom-id))
9620 (push (list link desc) org-stored-links))
9621 (car org-stored-links))))))
9623 (defun org-store-link-props (&rest plist)
9624 "Store link properties, extract names and addresses."
9625 (let (x adr)
9626 (when (setq x (plist-get plist :from))
9627 (setq adr (mail-extract-address-components x))
9628 (setq plist (plist-put plist :fromname (car adr)))
9629 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9630 (when (setq x (plist-get plist :to))
9631 (setq adr (mail-extract-address-components x))
9632 (setq plist (plist-put plist :toname (car adr)))
9633 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9634 (let ((from (plist-get plist :from))
9635 (to (plist-get plist :to)))
9636 (when (and from to org-from-is-user-regexp)
9637 (setq plist
9638 (plist-put plist :fromto
9639 (if (string-match org-from-is-user-regexp from)
9640 (concat "to %t")
9641 (concat "from %f"))))))
9642 (setq org-store-link-plist plist))
9644 (defun org-add-link-props (&rest plist)
9645 "Add these properties to the link property list."
9646 (let (key value)
9647 (while plist
9648 (setq key (pop plist) value (pop plist))
9649 (setq org-store-link-plist
9650 (plist-put org-store-link-plist key value)))))
9652 (defun org-email-link-description (&optional fmt)
9653 "Return the description part of an email link.
9654 This takes information from `org-store-link-plist' and formats it
9655 according to FMT (default from `org-email-link-description-format')."
9656 (setq fmt (or fmt org-email-link-description-format))
9657 (let* ((p org-store-link-plist)
9658 (to (plist-get p :toaddress))
9659 (from (plist-get p :fromaddress))
9660 (table
9661 (list
9662 (cons "%c" (plist-get p :fromto))
9663 (cons "%F" (plist-get p :from))
9664 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9665 (cons "%T" (plist-get p :to))
9666 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9667 (cons "%s" (plist-get p :subject))
9668 (cons "%d" (plist-get p :date))
9669 (cons "%m" (plist-get p :message-id)))))
9670 (when (string-match "%c" fmt)
9671 ;; Check if the user wrote this message
9672 (if (and org-from-is-user-regexp from to
9673 (save-match-data (string-match org-from-is-user-regexp from)))
9674 (setq fmt (replace-match "to %t" t t fmt))
9675 (setq fmt (replace-match "from %f" t t fmt))))
9676 (org-replace-escapes fmt table)))
9678 (defun org-make-org-heading-search-string (&optional string)
9679 "Make search string for the current headline or STRING."
9680 (let ((s (or string
9681 (and (derived-mode-p 'org-mode)
9682 (save-excursion
9683 (org-back-to-heading t)
9684 (org-element-property :raw-value (org-element-at-point))))))
9685 (lines org-context-in-file-links))
9686 (or string (setq s (concat "*" s))) ; Add * for headlines
9687 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9688 (when (and string (integerp lines) (> lines 0))
9689 (let ((slines (org-split-string s "\n")))
9690 (when (< lines (length slines))
9691 (setq s (mapconcat
9692 'identity
9693 (reverse (nthcdr (- (length slines) lines)
9694 (reverse slines))) "\n")))))
9695 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9697 (defun org-make-link-string (link &optional description)
9698 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9699 (unless (string-match "\\S-" link)
9700 (error "Empty link"))
9701 (when (and description
9702 (stringp description)
9703 (not (string-match "\\S-" description)))
9704 (setq description nil))
9705 (when (stringp description)
9706 ;; Remove brackets from the description, they are fatal.
9707 (while (string-match "\\[" description)
9708 (setq description (replace-match "{" t t description)))
9709 (while (string-match "\\]" description)
9710 (setq description (replace-match "}" t t description))))
9711 (when (equal link description)
9712 ;; No description needed, it is identical
9713 (setq description nil))
9714 (when (and (not description)
9715 (not (string-match (org-image-file-name-regexp) link))
9716 (not (equal link (org-link-escape link))))
9717 (setq description (org-extract-attributes link)))
9718 (setq link
9719 (cond ((string-match (org-image-file-name-regexp) link) link)
9720 ((string-match org-link-types-re link)
9721 (concat (match-string 1 link)
9722 (org-link-escape (substring link (match-end 1)))))
9723 (t (org-link-escape link))))
9724 (concat "[[" link "]"
9725 (if description (concat "[" description "]") "")
9726 "]"))
9728 (defconst org-link-escape-chars
9729 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9730 "List of characters that should be escaped in link.
9731 This is the list that is used for internal purposes.")
9733 (defconst org-link-escape-chars-browser
9734 '(?\ ?\")
9735 "List of escapes for characters that are problematic in links.
9736 This is the list that is used before handing over to the browser.")
9738 (defun org-link-escape (text &optional table merge)
9739 "Return percent escaped representation of TEXT.
9740 TEXT is a string with the text to escape.
9741 Optional argument TABLE is a list with characters that should be
9742 escaped. When nil, `org-link-escape-chars' is used.
9743 If optional argument MERGE is set, merge TABLE into
9744 `org-link-escape-chars'."
9745 (cond
9746 ((and table merge)
9747 (mapc (lambda (defchr)
9748 (unless (member defchr table)
9749 (setq table (cons defchr table)))) org-link-escape-chars))
9750 ((null table)
9751 (setq table org-link-escape-chars)))
9752 (mapconcat
9753 (lambda (char)
9754 (if (or (member char table)
9755 (and (or (< char 32) (= char 37) (> char 126))
9756 org-url-hexify-p))
9757 (mapconcat (lambda (sequence-element)
9758 (format "%%%.2X" sequence-element))
9759 (or (encode-coding-char char 'utf-8)
9760 (error "Unable to percent escape character: %s"
9761 (char-to-string char))) "")
9762 (char-to-string char))) text ""))
9764 (defun org-link-unescape (str)
9765 "Unhex hexified Unicode strings as returned from the JavaScript function
9766 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9767 (unless (and (null str) (string= "" str))
9768 (let ((pos 0) (case-fold-search t) unhexed)
9769 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9770 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9771 (setq str (replace-match unhexed t t str))
9772 (setq pos (+ pos (length unhexed))))))
9773 str)
9775 (defun org-link-unescape-compound (hex)
9776 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9777 Note: this function also decodes single byte encodings like
9778 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9779 (save-match-data
9780 (let* ((bytes (cdr (split-string hex "%")))
9781 (ret "")
9782 (eat 0)
9783 (sum 0))
9784 (while bytes
9785 (let* ((val (string-to-number (pop bytes) 16))
9786 (shift-xor
9787 (if (= 0 eat)
9788 (cond
9789 ((>= val 252) (cons 6 252))
9790 ((>= val 248) (cons 5 248))
9791 ((>= val 240) (cons 4 240))
9792 ((>= val 224) (cons 3 224))
9793 ((>= val 192) (cons 2 192))
9794 (t (cons 0 0)))
9795 (cons 6 128))))
9796 (if (>= val 192) (setq eat (car shift-xor)))
9797 (setq val (logxor val (cdr shift-xor)))
9798 (setq sum (+ (lsh sum (car shift-xor)) val))
9799 (if (> eat 0) (setq eat (- eat 1)))
9800 (cond
9801 ((= 0 eat) ;multi byte
9802 (setq ret (concat ret (org-char-to-string sum)))
9803 (setq sum 0))
9804 ((not bytes) ; single byte(s)
9805 (setq ret (org-link-unescape-single-byte-sequence hex))))
9806 )) ;; end (while bytes
9807 ret )))
9809 (defun org-link-unescape-single-byte-sequence (hex)
9810 "Unhexify hex-encoded single byte character sequences."
9811 (mapconcat (lambda (byte)
9812 (char-to-string (string-to-number byte 16)))
9813 (cdr (split-string hex "%")) ""))
9815 (defun org-xor (a b)
9816 "Exclusive or."
9817 (if a (not b) b))
9819 (defun org-fixup-message-id-for-http (s)
9820 "Replace special characters in a message id, so it can be used in an http query."
9821 (when (string-match "%" s)
9822 (setq s (mapconcat (lambda (c)
9823 (if (eq c ?%)
9824 "%25"
9825 (char-to-string c)))
9826 s "")))
9827 (while (string-match "<" s)
9828 (setq s (replace-match "%3C" t t s)))
9829 (while (string-match ">" s)
9830 (setq s (replace-match "%3E" t t s)))
9831 (while (string-match "@" s)
9832 (setq s (replace-match "%40" t t s)))
9835 (defun org-link-prettify (link)
9836 "Return a human-readable representation of LINK.
9837 The car of LINK must be a raw link the cdr of LINK must be either
9838 a link description or nil."
9839 (let ((desc (or (cadr link) "<no description>")))
9840 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9841 "<" (car link) ">")))
9843 ;;;###autoload
9844 (defun org-insert-link-global ()
9845 "Insert a link like Org-mode does.
9846 This command can be called in any mode to insert a link in Org-mode syntax."
9847 (interactive)
9848 (org-load-modules-maybe)
9849 (org-run-like-in-org-mode 'org-insert-link))
9851 (defun org-insert-all-links (&optional keep)
9852 "Insert all links in `org-stored-links'."
9853 (interactive "P")
9854 (let ((links (copy-sequence org-stored-links)) l)
9855 (while (setq l (if keep (pop links) (pop org-stored-links)))
9856 (insert "- ")
9857 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9858 (insert "\n"))))
9860 (defun org-link-fontify-links-to-this-file ()
9861 "Fontify links to the current file in `org-stored-links'."
9862 (let ((f (buffer-file-name)) a b)
9863 (setq a (mapcar (lambda(l)
9864 (let ((ll (car l)))
9865 (when (and (string-match "^file:\\(.+\\)::" ll)
9866 (equal f (expand-file-name (match-string 1 ll))))
9867 ll)))
9868 org-stored-links))
9869 (when (featurep 'org-id)
9870 (setq b (mapcar (lambda(l)
9871 (let ((ll (car l)))
9872 (when (and (string-match "^id:\\(.+\\)$" ll)
9873 (equal f (expand-file-name
9874 (or (org-id-find-id-file
9875 (match-string 1 ll)) ""))))
9876 ll)))
9877 org-stored-links)))
9878 (mapcar (lambda(l)
9879 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9880 (delq nil (append a b)))))
9882 (defvar org-link-links-in-this-file nil)
9883 (defun org-insert-link (&optional complete-file link-location default-description)
9884 "Insert a link. At the prompt, enter the link.
9886 Completion can be used to insert any of the link protocol prefixes like
9887 http or ftp in use.
9889 The history can be used to select a link previously stored with
9890 `org-store-link'. When the empty string is entered (i.e. if you just
9891 press RET at the prompt), the link defaults to the most recently
9892 stored link. As SPC triggers completion in the minibuffer, you need to
9893 use M-SPC or C-q SPC to force the insertion of a space character.
9895 You will also be prompted for a description, and if one is given, it will
9896 be displayed in the buffer instead of the link.
9898 If there is already a link at point, this command will allow you to edit link
9899 and description parts.
9901 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9902 be selected using completion. The path to the file will be relative to the
9903 current directory if the file is in the current directory or a subdirectory.
9904 Otherwise, the link will be the absolute path as completed in the minibuffer
9905 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9906 option `org-link-file-path-type'.
9908 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9909 the current directory or below.
9911 With three \\[universal-argument] prefixes, negate the meaning of
9912 `org-keep-stored-link-after-insertion'.
9914 If `org-make-link-description-function' is non-nil, this function will be
9915 called with the link target, and the result will be the default
9916 link description.
9918 If the LINK-LOCATION parameter is non-nil, this value will be
9919 used as the link location instead of reading one interactively.
9921 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9922 be used as the default description."
9923 (interactive "P")
9924 (let* ((wcf (current-window-configuration))
9925 (origbuf (current-buffer))
9926 (region (if (org-region-active-p)
9927 (buffer-substring (region-beginning) (region-end))))
9928 (remove (and region (list (region-beginning) (region-end))))
9929 (desc region)
9930 tmphist ; byte-compile incorrectly complains about this
9931 (link link-location)
9932 (abbrevs org-link-abbrev-alist-local)
9933 entry file all-prefixes auto-desc)
9934 (cond
9935 (link-location) ; specified by arg, just use it.
9936 ((org-in-regexp org-bracket-link-regexp 1)
9937 ;; We do have a link at point, and we are going to edit it.
9938 (setq remove (list (match-beginning 0) (match-end 0)))
9939 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9940 (setq link (read-string "Link: "
9941 (org-link-unescape
9942 (org-match-string-no-properties 1)))))
9943 ((or (org-in-regexp org-angle-link-re)
9944 (org-in-regexp org-plain-link-re))
9945 ;; Convert to bracket link
9946 (setq remove (list (match-beginning 0) (match-end 0))
9947 link (read-string "Link: "
9948 (org-remove-angle-brackets (match-string 0)))))
9949 ((member complete-file '((4) (16)))
9950 ;; Completing read for file names.
9951 (setq link (org-file-complete-link complete-file)))
9953 ;; Read link, with completion for stored links.
9954 (org-link-fontify-links-to-this-file)
9955 (org-switch-to-buffer-other-window "*Org Links*")
9956 (with-current-buffer "*Org Links*"
9957 (erase-buffer)
9958 (insert "Insert a link.
9959 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9960 (when org-stored-links
9961 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9962 (insert (mapconcat 'org-link-prettify
9963 (reverse org-stored-links) "\n")))
9964 (goto-char (point-min)))
9965 (let ((cw (selected-window)))
9966 (select-window (get-buffer-window "*Org Links*" 'visible))
9967 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9968 (unless (pos-visible-in-window-p (point-max))
9969 (org-fit-window-to-buffer))
9970 (and (window-live-p cw) (select-window cw)))
9971 ;; Fake a link history, containing the stored links.
9972 (setq tmphist (append (mapcar 'car org-stored-links)
9973 org-insert-link-history))
9974 (setq all-prefixes (append (mapcar 'car abbrevs)
9975 (mapcar 'car org-link-abbrev-alist)
9976 org-link-types))
9977 (unwind-protect
9978 (progn
9979 (setq link
9980 (org-completing-read
9981 "Link: "
9982 (append
9983 (mapcar (lambda (x) (concat x ":"))
9984 all-prefixes)
9985 (mapcar 'car org-stored-links))
9986 nil nil nil
9987 'tmphist
9988 (caar org-stored-links)))
9989 (if (not (string-match "\\S-" link))
9990 (user-error "No link selected"))
9991 (mapc (lambda(l)
9992 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9993 org-stored-links)
9994 (if (or (member link all-prefixes)
9995 (and (equal ":" (substring link -1))
9996 (member (substring link 0 -1) all-prefixes)
9997 (setq link (substring link 0 -1))))
9998 (setq link (with-current-buffer origbuf
9999 (org-link-try-special-completion link)))))
10000 (set-window-configuration wcf)
10001 (kill-buffer "*Org Links*"))
10002 (setq entry (assoc link org-stored-links))
10003 (or entry (push link org-insert-link-history))
10004 (setq desc (or desc (nth 1 entry)))))
10006 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10007 (not org-keep-stored-link-after-insertion))
10008 (setq org-stored-links (delq (assoc link org-stored-links)
10009 org-stored-links)))
10011 (if (and (string-match org-plain-link-re link)
10012 (not (string-match org-ts-regexp link)))
10013 ;; URL-like link, normalize the use of angular brackets.
10014 (setq link (org-remove-angle-brackets link)))
10016 ;; Check if we are linking to the current file with a search
10017 ;; option If yes, simplify the link by using only the search
10018 ;; option.
10019 (when (and buffer-file-name
10020 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10021 (let* ((path (match-string 1 link))
10022 (case-fold-search nil)
10023 (search (match-string 2 link)))
10024 (save-match-data
10025 (if (equal (file-truename buffer-file-name) (file-truename path))
10026 ;; We are linking to this same file, with a search option
10027 (setq link search)))))
10029 ;; Check if we can/should use a relative path. If yes, simplify the link
10030 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10031 (let* ((type (match-string 1 link))
10032 (path (match-string 2 link))
10033 (origpath path)
10034 (case-fold-search nil))
10035 (cond
10036 ((or (eq org-link-file-path-type 'absolute)
10037 (equal complete-file '(16)))
10038 (setq path (abbreviate-file-name (expand-file-name path))))
10039 ((eq org-link-file-path-type 'noabbrev)
10040 (setq path (expand-file-name path)))
10041 ((eq org-link-file-path-type 'relative)
10042 (setq path (file-relative-name path)))
10044 (save-match-data
10045 (if (string-match (concat "^" (regexp-quote
10046 (expand-file-name
10047 (file-name-as-directory
10048 default-directory))))
10049 (expand-file-name path))
10050 ;; We are linking a file with relative path name.
10051 (setq path (substring (expand-file-name path)
10052 (match-end 0)))
10053 (setq path (abbreviate-file-name (expand-file-name path)))))))
10054 (setq link (concat type path))
10055 (if (equal desc origpath)
10056 (setq desc path))))
10058 (if org-make-link-description-function
10059 (setq desc
10060 (or (condition-case nil
10061 (funcall org-make-link-description-function link desc)
10062 (error (progn (message "Can't get link description from `%s'"
10063 (symbol-name org-make-link-description-function))
10064 (sit-for 2) nil)))
10065 (read-string "Description: " default-description)))
10066 (if default-description (setq desc default-description)
10067 (setq desc (or (and auto-desc desc)
10068 (read-string "Description: " desc)))))
10070 (unless (string-match "\\S-" desc) (setq desc nil))
10071 (if remove (apply 'delete-region remove))
10072 (insert (org-make-link-string link desc))))
10074 (defun org-link-try-special-completion (type)
10075 "If there is completion support for link type TYPE, offer it."
10076 (let ((fun (intern (concat "org-" type "-complete-link"))))
10077 (if (functionp fun)
10078 (funcall fun)
10079 (read-string "Link (no completion support): " (concat type ":")))))
10081 (defun org-file-complete-link (&optional arg)
10082 "Create a file link using completion."
10083 (let (file link)
10084 (setq file (org-iread-file-name "File: "))
10085 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10086 (pwd1 (file-name-as-directory (abbreviate-file-name
10087 (expand-file-name ".")))))
10088 (cond
10089 ((equal arg '(16))
10090 (setq link (concat
10091 "file:"
10092 (abbreviate-file-name (expand-file-name file)))))
10093 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10094 (setq link (concat "file:" (match-string 1 file))))
10095 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10096 (expand-file-name file))
10097 (setq link (concat
10098 "file:" (match-string 1 (expand-file-name file)))))
10099 (t (setq link (concat "file:" file)))))
10100 link))
10102 (defun org-iread-file-name (&rest args)
10103 "Read-file-name using `ido-mode' speedup if available.
10104 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10105 See `read-file-name' for a description of parameters."
10106 (org-without-partial-completion
10107 (if (and org-completion-use-ido
10108 (fboundp 'ido-read-file-name)
10109 (boundp 'ido-mode) ido-mode
10110 (listp (second args)))
10111 (let ((ido-enter-matching-directory nil))
10112 (apply 'ido-read-file-name args))
10113 (apply 'read-file-name args))))
10115 (defun org-completing-read (&rest args)
10116 "Completing-read with SPACE being a normal character."
10117 (let ((enable-recursive-minibuffers t)
10118 (minibuffer-local-completion-map
10119 (copy-keymap minibuffer-local-completion-map)))
10120 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10121 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10122 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10123 (apply 'org-icompleting-read args)))
10125 (defun org-completing-read-no-i (&rest args)
10126 (let (org-completion-use-ido org-completion-use-iswitchb)
10127 (apply 'org-completing-read args)))
10129 (defun org-iswitchb-completing-read (prompt choices &rest args)
10130 "Use iswitch as a completing-read replacement to choose from choices.
10131 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10132 from."
10133 (let* ((iswitchb-use-virtual-buffers nil)
10134 (iswitchb-make-buflist-hook
10135 (lambda ()
10136 (setq iswitchb-temp-buflist choices))))
10137 (iswitchb-read-buffer prompt)))
10139 (defun org-icompleting-read (&rest args)
10140 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10141 (org-without-partial-completion
10142 (if (and org-completion-use-ido
10143 (fboundp 'ido-completing-read)
10144 (boundp 'ido-mode) ido-mode
10145 (listp (second args)))
10146 (let ((ido-enter-matching-directory nil))
10147 (apply 'ido-completing-read (concat (car args))
10148 (if (consp (car (nth 1 args)))
10149 (mapcar 'car (nth 1 args))
10150 (nth 1 args))
10151 (cddr args)))
10152 (if (and org-completion-use-iswitchb
10153 (boundp 'iswitchb-mode) iswitchb-mode
10154 (listp (second args)))
10155 (apply 'org-iswitchb-completing-read (concat (car args))
10156 (if (consp (car (nth 1 args)))
10157 (mapcar 'car (nth 1 args))
10158 (nth 1 args))
10159 (cddr args))
10160 (apply 'completing-read args)))))
10162 (defun org-extract-attributes (s)
10163 "Extract the attributes cookie from a string and set as text property."
10164 (let (a attr (start 0) key value)
10165 (save-match-data
10166 (when (string-match "{{\\([^}]+\\)}}$" s)
10167 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10168 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10169 (setq key (match-string 1 a) value (match-string 2 a)
10170 start (match-end 0)
10171 attr (plist-put attr (intern key) value))))
10172 (org-add-props s nil 'org-attr attr))
10175 ;;; Opening/following a link
10177 (defvar org-link-search-failed nil)
10179 (defvar org-open-link-functions nil
10180 "Hook for functions finding a plain text link.
10181 These functions must take a single argument, the link content.
10182 They will be called for links that look like [[link text][description]]
10183 when LINK TEXT does not have a protocol like \"http:\" and does not look
10184 like a filename (e.g. \"./blue.png\").
10186 These functions will be called *before* Org attempts to resolve the
10187 link by doing text searches in the current buffer - so if you want a
10188 link \"[[target]]\" to still find \"<<target>>\", your function should
10189 handle this as a special case.
10191 When the function does handle the link, it must return a non-nil value.
10192 If it decides that it is not responsible for this link, it must return
10193 nil to indicate that that Org-mode can continue with other options
10194 like exact and fuzzy text search.")
10196 (defun org-next-link (&optional search-backward)
10197 "Move forward to the next link.
10198 If the link is in hidden text, expose it."
10199 (interactive "P")
10200 (when (and org-link-search-failed (eq this-command last-command))
10201 (goto-char (point-min))
10202 (message "Link search wrapped back to beginning of buffer"))
10203 (setq org-link-search-failed nil)
10204 (let* ((pos (point))
10205 (ct (org-context))
10206 (a (assoc :link ct))
10207 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10208 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10209 ((looking-at org-any-link-re)
10210 ;; Don't stay stuck at link without an org-link face
10211 (forward-char (if search-backward -1 1))))
10212 (if (funcall srch-fun org-any-link-re nil t)
10213 (progn
10214 (goto-char (match-beginning 0))
10215 (if (outline-invisible-p) (org-show-context)))
10216 (goto-char pos)
10217 (setq org-link-search-failed t)
10218 (message "No further link found"))))
10220 (defun org-previous-link ()
10221 "Move backward to the previous link.
10222 If the link is in hidden text, expose it."
10223 (interactive)
10224 (funcall 'org-next-link t))
10226 (defun org-translate-link (s)
10227 "Translate a link string if a translation function has been defined."
10228 (if (and org-link-translation-function
10229 (fboundp org-link-translation-function)
10230 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10231 (progn
10232 (setq s (funcall org-link-translation-function
10233 (match-string 1 s) (match-string 2 s)))
10234 (concat (car s) ":" (cdr s)))
10237 (defun org-translate-link-from-planner (type path)
10238 "Translate a link from Emacs Planner syntax so that Org can follow it.
10239 This is still an experimental function, your mileage may vary."
10240 (cond
10241 ((member type '("http" "https" "news" "ftp"))
10242 ;; standard Internet links are the same.
10243 nil)
10244 ((and (equal type "irc") (string-match "^//" path))
10245 ;; Planner has two / at the beginning of an irc link, we have 1.
10246 ;; We should have zero, actually....
10247 (setq path (substring path 1)))
10248 ((and (equal type "lisp") (string-match "^/" path))
10249 ;; Planner has a slash, we do not.
10250 (setq type "elisp" path (substring path 1)))
10251 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10252 ;; A typical message link. Planner has the id after the final slash,
10253 ;; we separate it with a hash mark
10254 (setq path (concat (match-string 1 path) "#"
10255 (org-remove-angle-brackets (match-string 2 path))))))
10256 (cons type path))
10258 (defun org-find-file-at-mouse (ev)
10259 "Open file link or URL at mouse."
10260 (interactive "e")
10261 (mouse-set-point ev)
10262 (org-open-at-point 'in-emacs))
10264 (defun org-open-at-mouse (ev)
10265 "Open file link or URL at mouse.
10266 See the docstring of `org-open-file' for details."
10267 (interactive "e")
10268 (mouse-set-point ev)
10269 (if (eq major-mode 'org-agenda-mode)
10270 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10271 (org-open-at-point))
10273 (defvar org-window-config-before-follow-link nil
10274 "The window configuration before following a link.
10275 This is saved in case the need arises to restore it.")
10277 (defvar org-open-link-marker (make-marker)
10278 "Marker pointing to the location where `org-open-at-point' was called.")
10280 ;;;###autoload
10281 (defun org-open-at-point-global ()
10282 "Follow a link like Org-mode does.
10283 This command can be called in any mode to follow a link that has
10284 Org-mode syntax."
10285 (interactive)
10286 (org-run-like-in-org-mode 'org-open-at-point))
10288 ;;;###autoload
10289 (defun org-open-link-from-string (s &optional arg reference-buffer)
10290 "Open a link in the string S, as if it was in Org-mode."
10291 (interactive "sLink: \nP")
10292 (let ((reference-buffer (or reference-buffer (current-buffer))))
10293 (with-temp-buffer
10294 (let ((org-inhibit-startup (not reference-buffer)))
10295 (org-mode)
10296 (insert s)
10297 (goto-char (point-min))
10298 (when reference-buffer
10299 (setq org-link-abbrev-alist-local
10300 (with-current-buffer reference-buffer
10301 org-link-abbrev-alist-local)))
10302 (org-open-at-point arg reference-buffer)))))
10304 (defvar org-open-at-point-functions nil
10305 "Hook that is run when following a link at point.
10307 Functions in this hook must return t if they identify and follow
10308 a link at point. If they don't find anything interesting at point,
10309 they must return nil.")
10311 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10312 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10313 (defun org-open-at-point (&optional arg reference-buffer)
10314 "Open link at or after point.
10315 If there is no link at point, this function will search forward up to
10316 the end of the current line.
10317 Normally, files will be opened by an appropriate application. If the
10318 optional prefix argument ARG is non-nil, Emacs will visit the file.
10319 With a double prefix argument, try to open outside of Emacs, in the
10320 application the system uses for this file type."
10321 (interactive "P")
10322 ;; if in a code block, then open the block's results
10323 (unless (call-interactively #'org-babel-open-src-block-result)
10324 (org-load-modules-maybe)
10325 (move-marker org-open-link-marker (point))
10326 (setq org-window-config-before-follow-link (current-window-configuration))
10327 (org-remove-occur-highlights nil nil t)
10328 (cond
10329 ((and (org-at-heading-p)
10330 (not (org-at-timestamp-p t))
10331 (not (org-in-regexp
10332 (concat org-plain-link-re "\\|"
10333 org-bracket-link-regexp "\\|"
10334 org-angle-link-re "\\|"
10335 "[ \t]:[^ \t\n]+:[ \t]*$")))
10336 (not (get-text-property (point) 'org-linked-text)))
10337 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10338 (lk0 (car lkall))
10339 (lk (if (stringp lk0) (list lk0) lk0))
10340 (lkend (cdr lkall)))
10341 (mapcar (lambda(l)
10342 (search-forward l nil lkend)
10343 (goto-char (match-beginning 0))
10344 (org-open-at-point))
10345 lk))
10346 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10347 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10348 ((and (org-at-timestamp-p t)
10349 (not (org-in-regexp org-bracket-link-regexp)))
10350 (org-follow-timestamp-link))
10351 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10352 (not (org-in-regexp org-any-link-re)))
10353 (org-footnote-action))
10355 (let (type path link line search (pos (point)))
10356 (catch 'match
10357 (save-excursion
10358 (or (org-in-regexp org-plain-link-re)
10359 (skip-chars-forward "^]\n\r"))
10360 (when (org-in-regexp org-bracket-link-regexp 1)
10361 (setq link (org-extract-attributes
10362 (org-link-unescape (org-match-string-no-properties 1))))
10363 (while (string-match " *\n *" link)
10364 (setq link (replace-match " " t t link)))
10365 (setq link (org-link-expand-abbrev link))
10366 (cond
10367 ((or (file-name-absolute-p link)
10368 (string-match "^\\.\\.?/" link))
10369 (setq type "file" path link))
10370 ((string-match org-link-re-with-space3 link)
10371 (setq type (match-string 1 link) path (match-string 2 link)))
10372 ((string-match "^help:+\\(.+\\)" link)
10373 (setq type "help" path (match-string 1 link)))
10374 (t (setq type "thisfile" path link)))
10375 (throw 'match t)))
10377 (when (get-text-property (point) 'org-linked-text)
10378 (setq type "thisfile"
10379 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10380 (1+ (point)) (point))
10381 path (buffer-substring
10382 (or (previous-single-property-change pos 'org-linked-text)
10383 (point-min))
10384 (or (next-single-property-change pos 'org-linked-text)
10385 (point-max)))
10386 ;; Ensure we will search for a <<<radio>>> link, not
10387 ;; a simple reference like <<ref>>
10388 path (concat "<" path))
10389 (throw 'match t))
10391 (save-excursion
10392 (when (or (org-in-regexp org-angle-link-re)
10393 (let ((match (org-in-regexp org-plain-link-re)))
10394 ;; Check a plain link is not within a bracket link
10395 (and match
10396 (save-excursion
10397 (save-match-data
10398 (progn
10399 (goto-char (car match))
10400 (not (org-in-regexp org-bracket-link-regexp)))))))
10401 (let ((line_ending (save-excursion (end-of-line) (point))))
10402 ;; We are in a line before a plain or bracket link
10403 (or (re-search-forward org-plain-link-re line_ending t)
10404 (re-search-forward org-bracket-link-regexp line_ending t))))
10405 (setq type (match-string 1)
10406 path (org-link-unescape (match-string 2)))
10407 (throw 'match t)))
10408 (save-excursion
10409 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10410 (setq type "tags"
10411 path (match-string 1))
10412 (while (string-match ":" path)
10413 (setq path (replace-match "+" t t path)))
10414 (throw 'match t)))
10415 (when (org-in-regexp "<\\([^><\n]+\\)>")
10416 (setq type "tree-match"
10417 path (match-string 1))
10418 (throw 'match t)))
10419 (unless path
10420 (user-error "No link found"))
10422 ;; switch back to reference buffer
10423 ;; needed when if called in a temporary buffer through
10424 ;; org-open-link-from-string
10425 (with-current-buffer (or reference-buffer (current-buffer))
10427 ;; Remove any trailing spaces in path
10428 (if (string-match " +\\'" path)
10429 (setq path (replace-match "" t t path)))
10430 (if (and org-link-translation-function
10431 (fboundp org-link-translation-function))
10432 ;; Check if we need to translate the link
10433 (let ((tmp (funcall org-link-translation-function type path)))
10434 (setq type (car tmp) path (cdr tmp))))
10436 (cond
10438 ((assoc type org-link-protocols)
10439 (funcall (nth 1 (assoc type org-link-protocols)) path))
10441 ((equal type "help")
10442 (let ((f-or-v (intern path)))
10443 (cond ((fboundp f-or-v)
10444 (describe-function f-or-v))
10445 ((boundp f-or-v)
10446 (describe-variable f-or-v))
10447 (t (error "Not a known function or variable")))))
10449 ((equal type "mailto")
10450 (let ((cmd (car org-link-mailto-program))
10451 (args (cdr org-link-mailto-program)) args1
10452 (address path) (subject "") a)
10453 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10454 (setq address (match-string 1 path)
10455 subject (org-link-escape (match-string 2 path))))
10456 (while args
10457 (cond
10458 ((not (stringp (car args))) (push (pop args) args1))
10459 (t (setq a (pop args))
10460 (if (string-match "%a" a)
10461 (setq a (replace-match address t t a)))
10462 (if (string-match "%s" a)
10463 (setq a (replace-match subject t t a)))
10464 (push a args1))))
10465 (apply cmd (nreverse args1))))
10467 ((member type '("http" "https" "ftp" "news"))
10468 (browse-url
10469 (concat type ":"
10470 (if (org-string-match-p
10471 (concat "[[:nonascii:]"
10472 org-link-escape-chars-browser "]")
10473 path)
10474 (org-link-escape path org-link-escape-chars-browser)
10475 path))))
10477 ((string= type "doi")
10478 (browse-url
10479 (concat org-doi-server-url
10480 (if (org-string-match-p
10481 (concat "[[:nonascii:]"
10482 org-link-escape-chars-browser "]")
10483 path)
10484 (org-link-escape path org-link-escape-chars-browser)
10485 path))))
10487 ((member type '("message"))
10488 (browse-url (concat type ":" path)))
10490 ((string= type "tags")
10491 (org-tags-view arg path))
10493 ((string= type "tree-match")
10494 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10496 ((string= type "file")
10497 (if (string-match "::\\([0-9]+\\)\\'" path)
10498 (setq line (string-to-number (match-string 1 path))
10499 path (substring path 0 (match-beginning 0)))
10500 (if (string-match "::\\(.+\\)\\'" path)
10501 (setq search (match-string 1 path)
10502 path (substring path 0 (match-beginning 0)))))
10503 (if (string-match "[*?{]" (file-name-nondirectory path))
10504 (dired path)
10505 (org-open-file path arg line search)))
10507 ((string= type "shell")
10508 (let ((buf (generate-new-buffer "*Org Shell Output"))
10509 (cmd path))
10510 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10511 (string-match org-confirm-shell-link-not-regexp cmd))
10512 (not org-confirm-shell-link-function)
10513 (funcall org-confirm-shell-link-function
10514 (format "Execute \"%s\" in shell? "
10515 (org-add-props cmd nil
10516 'face 'org-warning))))
10517 (progn
10518 (message "Executing %s" cmd)
10519 (shell-command cmd buf)
10520 (if (featurep 'midnight)
10521 (setq clean-buffer-list-kill-buffer-names
10522 (cons buf clean-buffer-list-kill-buffer-names))))
10523 (error "Abort"))))
10525 ((string= type "elisp")
10526 (let ((cmd path))
10527 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10528 (string-match org-confirm-elisp-link-not-regexp cmd))
10529 (not org-confirm-elisp-link-function)
10530 (funcall org-confirm-elisp-link-function
10531 (format "Execute \"%s\" as elisp? "
10532 (org-add-props cmd nil
10533 'face 'org-warning))))
10534 (message "%s => %s" cmd
10535 (if (equal (string-to-char cmd) ?\()
10536 (eval (read cmd))
10537 (call-interactively (read cmd))))
10538 (error "Abort"))))
10540 ((and (string= type "thisfile")
10541 (or (run-hook-with-args-until-success
10542 'org-open-link-functions path)
10543 (and link
10544 (string-match "^id:" link)
10545 (or (featurep 'org-id) (require 'org-id))
10546 (progn
10547 (funcall (nth 1 (assoc "id" org-link-protocols))
10548 (substring path 3))
10549 t)))))
10551 ((string= type "thisfile")
10552 (if arg
10553 (switch-to-buffer-other-window
10554 (org-get-buffer-for-internal-link (current-buffer)))
10555 (org-mark-ring-push))
10556 (let ((cmd `(org-link-search
10557 ,path
10558 ,(cond ((equal arg '(4)) ''occur)
10559 ((equal arg '(16)) ''org-occur))
10560 ,pos)))
10561 (condition-case nil (let ((org-link-search-inhibit-query t))
10562 (eval cmd))
10563 (error (progn (widen) (eval cmd))))))
10565 (t (browse-url-at-point)))))))
10566 (move-marker org-open-link-marker nil)
10567 (run-hook-with-args 'org-follow-link-hook)))
10569 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10570 "Offer links in the current entry and return the selected link.
10571 If there is only one link, return it.
10572 If NTH is an integer, return the NTH link found.
10573 If ZERO is a string, check also this string for a link, and if
10574 there is one, return it."
10575 (with-current-buffer buffer
10576 (save-excursion
10577 (save-restriction
10578 (widen)
10579 (goto-char marker)
10580 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10581 "\\(" org-angle-link-re "\\)\\|"
10582 "\\(" org-plain-link-re "\\)"))
10583 (cnt ?0)
10584 (in-emacs (if (integerp nth) nil nth))
10585 have-zero end links link c)
10586 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10587 (push (match-string 0 zero) links)
10588 (setq cnt (1- cnt) have-zero t))
10589 (save-excursion
10590 (org-back-to-heading t)
10591 (setq end (save-excursion (outline-next-heading) (point)))
10592 (while (re-search-forward re end t)
10593 (push (match-string 0) links))
10594 (setq links (org-uniquify (reverse links))))
10595 (cond
10596 ((null links)
10597 (message "No links"))
10598 ((equal (length links) 1)
10599 (setq link (car links)))
10600 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10601 (setq link (nth (if have-zero nth (1- nth)) links)))
10602 (t ; we have to select a link
10603 (save-excursion
10604 (save-window-excursion
10605 (delete-other-windows)
10606 (with-output-to-temp-buffer "*Select Link*"
10607 (mapc (lambda (l)
10608 (if (not (string-match org-bracket-link-regexp l))
10609 (princ (format "[%c] %s\n" (incf cnt)
10610 (org-remove-angle-brackets l)))
10611 (if (match-end 3)
10612 (princ (format "[%c] %s (%s)\n" (incf cnt)
10613 (match-string 3 l) (match-string 1 l)))
10614 (princ (format "[%c] %s\n" (incf cnt)
10615 (match-string 1 l))))))
10616 links))
10617 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10618 (message "Select link to open, RET to open all:")
10619 (setq c (read-char-exclusive))
10620 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10621 (when (equal c ?q) (error "Abort"))
10622 (if (equal c ?\C-m)
10623 (setq link links)
10624 (setq nth (- c ?0))
10625 (if have-zero (setq nth (1+ nth)))
10626 (unless (and (integerp nth) (>= (length links) nth))
10627 (user-error "Invalid link selection"))
10628 (setq link (nth (1- nth) links)))))
10629 (cons link end))))))
10631 ;; Add special file links that specify the way of opening
10633 (org-add-link-type "file+sys" 'org-open-file-with-system)
10634 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10635 (defun org-open-file-with-system (path)
10636 "Open file at PATH using the system way of opening it."
10637 (org-open-file path 'system))
10638 (defun org-open-file-with-emacs (path)
10639 "Open file at PATH in Emacs."
10640 (org-open-file path 'emacs))
10643 ;;; File search
10645 (defvar org-create-file-search-functions nil
10646 "List of functions to construct the right search string for a file link.
10647 These functions are called in turn with point at the location to
10648 which the link should point.
10650 A function in the hook should first test if it would like to
10651 handle this file type, for example by checking the `major-mode'
10652 or the file extension. If it decides not to handle this file, it
10653 should just return nil to give other functions a chance. If it
10654 does handle the file, it must return the search string to be used
10655 when following the link. The search string will be part of the
10656 file link, given after a double colon, and `org-open-at-point'
10657 will automatically search for it. If special measures must be
10658 taken to make the search successful, another function should be
10659 added to the companion hook `org-execute-file-search-functions',
10660 which see.
10662 A function in this hook may also use `setq' to set the variable
10663 `description' to provide a suggestion for the descriptive text to
10664 be used for this link when it gets inserted into an Org-mode
10665 buffer with \\[org-insert-link].")
10667 (defvar org-execute-file-search-functions nil
10668 "List of functions to execute a file search triggered by a link.
10670 Functions added to this hook must accept a single argument, the
10671 search string that was part of the file link, the part after the
10672 double colon. The function must first check if it would like to
10673 handle this search, for example by checking the `major-mode' or
10674 the file extension. If it decides not to handle this search, it
10675 should just return nil to give other functions a chance. If it
10676 does handle the search, it must return a non-nil value to keep
10677 other functions from trying.
10679 Each function can access the current prefix argument through the
10680 variable `current-prefix-arg'. Note that a single prefix is used
10681 to force opening a link in Emacs, so it may be good to only use a
10682 numeric or double prefix to guide the search function.
10684 In case this is needed, a function in this hook can also restore
10685 the window configuration before `org-open-at-point' was called using:
10687 (set-window-configuration org-window-config-before-follow-link)")
10689 (defun org-link-search (s &optional type avoid-pos stealth)
10690 "Search for a link search option.
10691 If S is surrounded by forward slashes, it is interpreted as a
10692 regular expression. In org-mode files, this will create an `org-occur'
10693 sparse tree. In ordinary files, `occur' will be used to list matches.
10694 If the current buffer is in `dired-mode', grep will be used to search
10695 in all files. If AVOID-POS is given, ignore matches near that position.
10697 When optional argument STEALTH is non-nil, do not modify
10698 visibility around point, thus ignoring
10699 `org-show-hierarchy-above', `org-show-following-heading' and
10700 `org-show-siblings' variables."
10701 (let ((case-fold-search t)
10702 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10703 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10704 (append '(("") (" ") ("\t") ("\n"))
10705 org-emphasis-alist)
10706 "\\|") "\\)"))
10707 (pos (point))
10708 (pre nil) (post nil)
10709 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10710 (cond
10711 ;; First check if there are any special search functions
10712 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10713 ;; Now try the builtin stuff
10714 ((and (equal (string-to-char s0) ?#)
10715 (> (length s0) 1)
10716 (save-excursion
10717 (goto-char (point-min))
10718 (and
10719 (re-search-forward
10720 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10721 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10722 (setq type 'dedicated
10723 pos (match-beginning 0))))
10724 ;; There is an exact target for this
10725 (goto-char pos)
10726 (org-back-to-heading t)))
10727 ((save-excursion
10728 (goto-char (point-min))
10729 (and
10730 (re-search-forward
10731 (concat "<<" (regexp-quote s0) ">>") nil t)
10732 (setq type 'dedicated
10733 pos (match-beginning 0))))
10734 ;; There is an exact target for this
10735 (goto-char pos))
10736 ((save-excursion
10737 (goto-char (point-min))
10738 (and
10739 (re-search-forward
10740 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10741 (setq type 'dedicated pos (match-beginning 0))))
10742 ;; Found an element with a matching #+name affiliated keyword.
10743 (goto-char pos))
10744 ((and (string-match "^(\\(.*\\))$" s0)
10745 (save-excursion
10746 (goto-char (point-min))
10747 (and
10748 (re-search-forward
10749 (concat "[^[]" (regexp-quote
10750 (format org-coderef-label-format
10751 (match-string 1 s0))))
10752 nil t)
10753 (setq type 'dedicated
10754 pos (1+ (match-beginning 0))))))
10755 ;; There is a coderef target for this
10756 (goto-char pos))
10757 ((string-match "^/\\(.*\\)/$" s)
10758 ;; A regular expression
10759 (cond
10760 ((derived-mode-p 'org-mode)
10761 (org-occur (match-string 1 s)))
10762 (t (org-do-occur (match-string 1 s)))))
10763 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10764 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10765 (goto-char (point-min))
10766 (cond
10767 ((let (case-fold-search)
10768 (re-search-forward (format org-complex-heading-regexp-format
10769 (regexp-quote s))
10770 nil t))
10771 ;; OK, found a match
10772 (setq type 'dedicated)
10773 (goto-char (match-beginning 0)))
10774 ((and (not org-link-search-inhibit-query)
10775 (eq org-link-search-must-match-exact-headline 'query-to-create)
10776 (y-or-n-p "No match - create this as a new heading? "))
10777 (goto-char (point-max))
10778 (or (bolp) (newline))
10779 (insert "* " s "\n")
10780 (beginning-of-line 0))
10782 (goto-char pos)
10783 (error "No match"))))
10785 ;; A normal search string
10786 (when (equal (string-to-char s) ?*)
10787 ;; Anchor on headlines, post may include tags.
10788 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10789 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10790 s (substring s 1)))
10791 (remove-text-properties
10792 0 (length s)
10793 '(face nil mouse-face nil keymap nil fontified nil) s)
10794 ;; Make a series of regular expressions to find a match
10795 (setq words (org-split-string s "[ \n\r\t]+")
10797 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10798 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10799 "\\)" markers)
10800 re2a_ (concat "\\(" (mapconcat 'downcase words
10801 "[ \t\r\n]+") "\\)[ \t\r\n]")
10802 re2a (concat "[ \t\r\n]" re2a_)
10803 re4_ (concat "\\(" (mapconcat 'downcase words
10804 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10805 re4 (concat "[^a-zA-Z_]" re4_)
10807 re1 (concat pre re2 post)
10808 re3 (concat pre (if pre re4_ re4) post)
10809 re5 (concat pre ".*" re4)
10810 re2 (concat pre re2)
10811 re2a (concat pre (if pre re2a_ re2a))
10812 re4 (concat pre (if pre re4_ re4))
10813 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10814 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10815 re5 "\\)"))
10816 (cond
10817 ((eq type 'org-occur) (org-occur reall))
10818 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10819 (t (goto-char (point-min))
10820 (setq type 'fuzzy)
10821 (if (or (and (org-search-not-self 1 re0 nil t)
10822 (setq type 'dedicated))
10823 (org-search-not-self 1 re1 nil t)
10824 (org-search-not-self 1 re2 nil t)
10825 (org-search-not-self 1 re2a nil t)
10826 (org-search-not-self 1 re3 nil t)
10827 (org-search-not-self 1 re4 nil t)
10828 (org-search-not-self 1 re5 nil t))
10829 (goto-char (match-beginning 1))
10830 (goto-char pos)
10831 (error "No match"))))))
10832 (and (derived-mode-p 'org-mode)
10833 (not stealth)
10834 (org-show-context 'link-search))
10835 type))
10837 (defun org-search-not-self (group &rest args)
10838 "Execute `re-search-forward', but only accept matches that do not
10839 enclose the position of `org-open-link-marker'."
10840 (let ((m org-open-link-marker))
10841 (catch 'exit
10842 (while (apply 're-search-forward args)
10843 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10844 (goto-char (match-end group))
10845 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10846 (> (match-beginning 0) (marker-position m))
10847 (< (match-end 0) (marker-position m)))
10848 (save-match-data
10849 (or (not (org-in-regexp
10850 org-bracket-link-analytic-regexp 1))
10851 (not (match-end 4)) ; no description
10852 (and (<= (match-beginning 4) (point))
10853 (>= (match-end 4) (point))))))
10854 (throw 'exit (point))))))))
10856 (defun org-get-buffer-for-internal-link (buffer)
10857 "Return a buffer to be used for displaying the link target of internal links."
10858 (cond
10859 ((not org-display-internal-link-with-indirect-buffer)
10860 buffer)
10861 ((string-match "(Clone)$" (buffer-name buffer))
10862 (message "Buffer is already a clone, not making another one")
10863 ;; we also do not modify visibility in this case
10864 buffer)
10865 (t ; make a new indirect buffer for displaying the link
10866 (let* ((bn (buffer-name buffer))
10867 (ibn (concat bn "(Clone)"))
10868 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10869 (with-current-buffer ib (org-overview))
10870 ib))))
10872 (defun org-do-occur (regexp &optional cleanup)
10873 "Call the Emacs command `occur'.
10874 If CLEANUP is non-nil, remove the printout of the regular expression
10875 in the *Occur* buffer. This is useful if the regex is long and not useful
10876 to read."
10877 (occur regexp)
10878 (when cleanup
10879 (let ((cwin (selected-window)) win beg end)
10880 (when (setq win (get-buffer-window "*Occur*"))
10881 (select-window win))
10882 (goto-char (point-min))
10883 (when (re-search-forward "match[a-z]+" nil t)
10884 (setq beg (match-end 0))
10885 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10886 (setq end (1- (match-beginning 0)))))
10887 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10888 (goto-char (point-min))
10889 (select-window cwin))))
10891 ;;; The mark ring for links jumps
10893 (defvar org-mark-ring nil
10894 "Mark ring for positions before jumps in Org-mode.")
10895 (defvar org-mark-ring-last-goto nil
10896 "Last position in the mark ring used to go back.")
10897 ;; Fill and close the ring
10898 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10899 (loop for i from 1 to org-mark-ring-length do
10900 (push (make-marker) org-mark-ring))
10901 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10902 org-mark-ring)
10904 (defun org-mark-ring-push (&optional pos buffer)
10905 "Put the current position or POS into the mark ring and rotate it."
10906 (interactive)
10907 (setq pos (or pos (point)))
10908 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10909 (move-marker (car org-mark-ring)
10910 (or pos (point))
10911 (or buffer (current-buffer)))
10912 (message "%s"
10913 (substitute-command-keys
10914 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10916 (defun org-mark-ring-goto (&optional n)
10917 "Jump to the previous position in the mark ring.
10918 With prefix arg N, jump back that many stored positions. When
10919 called several times in succession, walk through the entire ring.
10920 Org-mode commands jumping to a different position in the current file,
10921 or to another Org-mode file, automatically push the old position
10922 onto the ring."
10923 (interactive "p")
10924 (let (p m)
10925 (if (eq last-command this-command)
10926 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10927 (setq p org-mark-ring))
10928 (setq org-mark-ring-last-goto p)
10929 (setq m (car p))
10930 (org-pop-to-buffer-same-window (marker-buffer m))
10931 (goto-char m)
10932 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10934 (defun org-remove-angle-brackets (s)
10935 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10936 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10938 (defun org-add-angle-brackets (s)
10939 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10940 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10942 (defun org-remove-double-quotes (s)
10943 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10944 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10947 ;;; Following specific links
10949 (defun org-follow-timestamp-link ()
10950 "Open an agenda view for the time-stamp date/range at point."
10951 (cond
10952 ((org-at-date-range-p t)
10953 (let ((org-agenda-start-on-weekday)
10954 (t1 (match-string 1))
10955 (t2 (match-string 2)) tt1 tt2)
10956 (setq tt1 (time-to-days (org-time-string-to-time t1))
10957 tt2 (time-to-days (org-time-string-to-time t2)))
10958 (let ((org-agenda-buffer-tmp-name
10959 (format "*Org Agenda(a:%s)"
10960 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10961 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10962 ((org-at-timestamp-p t)
10963 (let ((org-agenda-buffer-tmp-name
10964 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10965 (org-agenda-list nil (time-to-days (org-time-string-to-time
10966 (substring (match-string 1) 0 10)))
10967 1)))
10968 (t (error "This should not happen"))))
10971 ;;; Following file links
10972 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10973 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10974 (declare-function mailcap-mime-info
10975 "mailcap" (string &optional request no-decode))
10976 (defvar org-wait nil)
10977 (defun org-open-file (path &optional in-emacs line search)
10978 "Open the file at PATH.
10979 First, this expands any special file name abbreviations. Then the
10980 configuration variable `org-file-apps' is checked if it contains an
10981 entry for this file type, and if yes, the corresponding command is launched.
10983 If no application is found, Emacs simply visits the file.
10985 With optional prefix argument IN-EMACS, Emacs will visit the file.
10986 With a double \\[universal-argument] \\[universal-argument] \
10987 prefix arg, Org tries to avoid opening in Emacs
10988 and to use an external application to visit the file.
10990 Optional LINE specifies a line to go to, optional SEARCH a string
10991 to search for. If LINE or SEARCH is given, the file will be
10992 opened in Emacs, unless an entry from org-file-apps that makes
10993 use of groups in a regexp matches.
10995 If you want to change the way frames are used when following a
10996 link, please customize `org-link-frame-setup'.
10998 If the file does not exist, an error is thrown."
10999 (let* ((file (if (equal path "")
11000 buffer-file-name
11001 (substitute-in-file-name (expand-file-name path))))
11002 (file-apps (append org-file-apps (org-default-apps)))
11003 (apps (org-remove-if
11004 'org-file-apps-entry-match-against-dlink-p file-apps))
11005 (apps-dlink (org-remove-if-not
11006 'org-file-apps-entry-match-against-dlink-p file-apps))
11007 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11008 (dirp (if remp nil (file-directory-p file)))
11009 (file (if (and dirp org-open-directory-means-index-dot-org)
11010 (concat (file-name-as-directory file) "index.org")
11011 file))
11012 (a-m-a-p (assq 'auto-mode apps))
11013 (dfile (downcase file))
11014 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
11015 (link (cond ((and (eq line nil)
11016 (eq search nil))
11017 file)
11018 (line
11019 (concat file "::" (number-to-string line)))
11020 (search
11021 (concat file "::" search))))
11022 (dlink (downcase link))
11023 (old-buffer (current-buffer))
11024 (old-pos (point))
11025 (old-mode major-mode)
11026 ext cmd link-match-data)
11027 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11028 (setq ext (match-string 1 dfile))
11029 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11030 (setq ext (match-string 1 dfile))))
11031 (cond
11032 ((member in-emacs '((16) system))
11033 (setq cmd (cdr (assoc 'system apps))))
11034 (in-emacs (setq cmd 'emacs))
11036 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11037 (and dirp (cdr (assoc 'directory apps)))
11038 ; first, try matching against apps-dlink
11039 ; if we get a match here, store the match data for later
11040 (let ((match (assoc-default dlink apps-dlink
11041 'string-match)))
11042 (if match
11043 (progn (setq link-match-data (match-data))
11044 match)
11045 (progn (setq in-emacs (or in-emacs line search))
11046 nil))) ; if we have no match in apps-dlink,
11047 ; always open the file in emacs if line or search
11048 ; is given (for backwards compatibility)
11049 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11050 'string-match)
11051 (cdr (assoc ext apps))
11052 (cdr (assoc t apps))))))
11053 (when (eq cmd 'system)
11054 (setq cmd (cdr (assoc 'system apps))))
11055 (when (eq cmd 'default)
11056 (setq cmd (cdr (assoc t apps))))
11057 (when (eq cmd 'mailcap)
11058 (require 'mailcap)
11059 (mailcap-parse-mailcaps)
11060 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11061 (command (mailcap-mime-info mime-type)))
11062 (if (stringp command)
11063 (setq cmd command)
11064 (setq cmd 'emacs))))
11065 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11066 (not (file-exists-p file))
11067 (not org-open-non-existing-files))
11068 (user-error "No such file: %s" file))
11069 (cond
11070 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11071 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11072 (while (string-match "['\"]%s['\"]" cmd)
11073 (setq cmd (replace-match "%s" t t cmd)))
11074 (while (string-match "%s" cmd)
11075 (setq cmd (replace-match
11076 (save-match-data
11077 (shell-quote-argument
11078 (convert-standard-filename file)))
11079 t t cmd)))
11081 ;; Replace "%1", "%2" etc. in command with group matches from regex
11082 (save-match-data
11083 (let ((match-index 1)
11084 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11085 (set-match-data link-match-data)
11086 (while (<= match-index number-of-groups)
11087 (let ((regex (concat "%" (number-to-string match-index)))
11088 (replace-with (match-string match-index dlink)))
11089 (while (string-match regex cmd)
11090 (setq cmd (replace-match replace-with t t cmd))))
11091 (setq match-index (+ match-index 1)))))
11093 (save-window-excursion
11094 (message "Running %s...done" cmd)
11095 (start-process-shell-command cmd nil cmd)
11096 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11097 ((or (stringp cmd)
11098 (eq cmd 'emacs))
11099 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11100 (widen)
11101 (if line (org-goto-line line)
11102 (if search (org-link-search search))))
11103 ((consp cmd)
11104 (let ((file (convert-standard-filename file)))
11105 (save-match-data
11106 (set-match-data link-match-data)
11107 (eval cmd))))
11108 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11109 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11110 (or (not (equal old-buffer (current-buffer)))
11111 (not (equal old-pos (point))))
11112 (org-mark-ring-push old-pos old-buffer))))
11114 (defun org-file-apps-entry-match-against-dlink-p (entry)
11115 "This function returns non-nil if `entry' uses a regular
11116 expression which should be matched against the whole link by
11117 org-open-file.
11119 It assumes that is the case when the entry uses a regular
11120 expression which has at least one grouping construct and the
11121 action is either a lisp form or a command string containing
11122 '%1', i.e. using at least one subexpression match as a
11123 parameter."
11124 (let ((selector (car entry))
11125 (action (cdr entry)))
11126 (if (stringp selector)
11127 (and (> (regexp-opt-depth selector) 0)
11128 (or (and (stringp action)
11129 (string-match "%[0-9]" action))
11130 (consp action)))
11131 nil)))
11133 (defun org-default-apps ()
11134 "Return the default applications for this operating system."
11135 (cond
11136 ((eq system-type 'darwin)
11137 org-file-apps-defaults-macosx)
11138 ((eq system-type 'windows-nt)
11139 org-file-apps-defaults-windowsnt)
11140 (t org-file-apps-defaults-gnu)))
11142 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11143 "Convert extensions to regular expressions in the cars of LIST.
11144 Also, weed out any non-string entries, because the return value is used
11145 only for regexp matching.
11146 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11147 point to the symbol `emacs', indicating that the file should
11148 be opened in Emacs."
11149 (append
11150 (delq nil
11151 (mapcar (lambda (x)
11152 (if (not (stringp (car x)))
11154 (if (string-match "\\W" (car x))
11156 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11157 list))
11158 (if add-auto-mode
11159 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11161 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11162 (defun org-file-remote-p (file)
11163 "Test whether FILE specifies a location on a remote system.
11164 Return non-nil if the location is indeed remote.
11166 For example, the filename \"/user@host:/foo\" specifies a location
11167 on the system \"/user@host:\"."
11168 (cond ((fboundp 'file-remote-p)
11169 (file-remote-p file))
11170 ((fboundp 'tramp-handle-file-remote-p)
11171 (tramp-handle-file-remote-p file))
11172 ((and (boundp 'ange-ftp-name-format)
11173 (string-match (car ange-ftp-name-format) file))
11174 t)))
11177 ;;;; Refiling
11179 (defun org-get-org-file ()
11180 "Read a filename, with default directory `org-directory'."
11181 (let ((default (or org-default-notes-file remember-data-file)))
11182 (read-file-name (format "File name [%s]: " default)
11183 (file-name-as-directory org-directory)
11184 default)))
11186 (defun org-notes-order-reversed-p ()
11187 "Check if the current file should receive notes in reversed order."
11188 (cond
11189 ((not org-reverse-note-order) nil)
11190 ((eq t org-reverse-note-order) t)
11191 ((not (listp org-reverse-note-order)) nil)
11192 (t (catch 'exit
11193 (let ((all org-reverse-note-order)
11194 entry)
11195 (while (setq entry (pop all))
11196 (if (string-match (car entry) buffer-file-name)
11197 (throw 'exit (cdr entry))))
11198 nil)))))
11200 (defvar org-refile-target-table nil
11201 "The list of refile targets, created by `org-refile'.")
11203 (defvar org-agenda-new-buffers nil
11204 "Buffers created to visit agenda files.")
11206 (defvar org-refile-cache nil
11207 "Cache for refile targets.")
11209 (defvar org-refile-markers nil
11210 "All the markers used for caching refile locations.")
11212 (defun org-refile-marker (pos)
11213 "Get a new refile marker, but only if caching is in use."
11214 (if (not org-refile-use-cache)
11216 (let ((m (make-marker)))
11217 (move-marker m pos)
11218 (push m org-refile-markers)
11219 m)))
11221 (defun org-refile-cache-clear ()
11222 "Clear the refile cache and disable all the markers."
11223 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11224 (setq org-refile-markers nil)
11225 (setq org-refile-cache nil)
11226 (message "Refile cache has been cleared"))
11228 (defun org-refile-cache-check-set (set)
11229 "Check if all the markers in the cache still have live buffers."
11230 (let (marker)
11231 (catch 'exit
11232 (while (and set (setq marker (nth 3 (pop set))))
11233 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11234 (when (and marker (null (marker-buffer marker)))
11235 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11236 (sit-for 3)
11237 (throw 'exit nil)))
11238 t)))
11240 (defun org-refile-cache-put (set &rest identifiers)
11241 "Push the refile targets SET into the cache, under IDENTIFIERS."
11242 (let* ((key (sha1 (prin1-to-string identifiers)))
11243 (entry (assoc key org-refile-cache)))
11244 (if entry
11245 (setcdr entry set)
11246 (push (cons key set) org-refile-cache))))
11248 (defun org-refile-cache-get (&rest identifiers)
11249 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11250 (cond
11251 ((not org-refile-cache) nil)
11252 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11254 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11255 org-refile-cache))))
11256 (and set (org-refile-cache-check-set set) set)))))
11258 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11259 "Produce a table with refile targets."
11260 (let ((case-fold-search nil)
11261 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11262 (entries (or org-refile-targets '((nil . (:level . 1)))))
11263 targets tgs txt re files f desc descre fast-path-p level pos0)
11264 (message "Getting targets...")
11265 (with-current-buffer (or default-buffer (current-buffer))
11266 (while (setq entry (pop entries))
11267 (setq files (car entry) desc (cdr entry))
11268 (setq fast-path-p nil)
11269 (cond
11270 ((null files) (setq files (list (current-buffer))))
11271 ((eq files 'org-agenda-files)
11272 (setq files (org-agenda-files 'unrestricted)))
11273 ((and (symbolp files) (fboundp files))
11274 (setq files (funcall files)))
11275 ((and (symbolp files) (boundp files))
11276 (setq files (symbol-value files))))
11277 (if (stringp files) (setq files (list files)))
11278 (cond
11279 ((eq (car desc) :tag)
11280 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11281 ((eq (car desc) :todo)
11282 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11283 ((eq (car desc) :regexp)
11284 (setq descre (cdr desc)))
11285 ((eq (car desc) :level)
11286 (setq descre (concat "^\\*\\{" (number-to-string
11287 (if org-odd-levels-only
11288 (1- (* 2 (cdr desc)))
11289 (cdr desc)))
11290 "\\}[ \t]")))
11291 ((eq (car desc) :maxlevel)
11292 (setq fast-path-p t)
11293 (setq descre (concat "^\\*\\{1," (number-to-string
11294 (if org-odd-levels-only
11295 (1- (* 2 (cdr desc)))
11296 (cdr desc)))
11297 "\\}[ \t]")))
11298 (t (error "Bad refiling target description %s" desc)))
11299 (while (setq f (pop files))
11300 (with-current-buffer
11301 (if (bufferp f) f (org-get-agenda-file-buffer f))
11303 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11304 (progn
11305 (if (bufferp f) (setq f (buffer-file-name
11306 (buffer-base-buffer f))))
11307 (setq f (and f (expand-file-name f)))
11308 (if (eq org-refile-use-outline-path 'file)
11309 (push (list (file-name-nondirectory f) f nil nil) tgs))
11310 (save-excursion
11311 (save-restriction
11312 (widen)
11313 (goto-char (point-min))
11314 (while (re-search-forward descre nil t)
11315 (goto-char (setq pos0 (point-at-bol)))
11316 (catch 'next
11317 (when org-refile-target-verify-function
11318 (save-match-data
11319 (or (funcall org-refile-target-verify-function)
11320 (throw 'next t))))
11321 (when (and (looking-at org-complex-heading-regexp)
11322 (not (member (match-string 4) excluded-entries))
11323 (match-string 4))
11324 (setq level (org-reduced-level
11325 (- (match-end 1) (match-beginning 1)))
11326 txt (org-link-display-format (match-string 4))
11327 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11328 re (format org-complex-heading-regexp-format
11329 (regexp-quote (match-string 4))))
11330 (when org-refile-use-outline-path
11331 (setq txt (mapconcat
11332 'org-protect-slash
11333 (append
11334 (if (eq org-refile-use-outline-path
11335 'file)
11336 (list (file-name-nondirectory
11337 (buffer-file-name
11338 (buffer-base-buffer))))
11339 (if (eq org-refile-use-outline-path
11340 'full-file-path)
11341 (list (buffer-file-name
11342 (buffer-base-buffer)))))
11343 (org-get-outline-path fast-path-p
11344 level txt)
11345 (list txt))
11346 "/")))
11347 (push (list txt f re (org-refile-marker (point)))
11348 tgs)))
11349 (when (= (point) pos0)
11350 ;; verification function has not moved point
11351 (goto-char (point-at-eol))))))))
11352 (when org-refile-use-cache
11353 (org-refile-cache-put tgs (buffer-file-name) descre))
11354 (setq targets (append tgs targets))))))
11355 (message "Getting targets...done")
11356 (nreverse targets)))
11358 (defun org-protect-slash (s)
11359 (while (string-match "/" s)
11360 (setq s (replace-match "\\" t t s)))
11363 (defvar org-olpa (make-vector 20 nil))
11365 (defun org-get-outline-path (&optional fastp level heading)
11366 "Return the outline path to the current entry, as a list.
11368 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11369 routine which makes outline path derivations for an entire file,
11370 avoiding backtracing. Refile target collection makes use of that."
11371 (if fastp
11372 (progn
11373 (if (> level 19)
11374 (error "Outline path failure, more than 19 levels"))
11375 (loop for i from level upto 19 do
11376 (aset org-olpa i nil))
11377 (prog1
11378 (delq nil (append org-olpa nil))
11379 (aset org-olpa level heading)))
11380 (let (rtn case-fold-search)
11381 (save-excursion
11382 (save-restriction
11383 (widen)
11384 (while (org-up-heading-safe)
11385 (when (looking-at org-complex-heading-regexp)
11386 (push (org-trim
11387 (replace-regexp-in-string
11388 ;; Remove statistical/checkboxes cookies
11389 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11390 (org-match-string-no-properties 4)))
11391 rtn)))
11392 rtn)))))
11394 (defun org-format-outline-path (path &optional width prefix separator)
11395 "Format the outline path PATH for display.
11396 WIDTH is the maximum number of characters that is available.
11397 PREFIX is a prefix to be included in the returned string,
11398 such as the file name.
11399 SEPARATOR is inserted between the different parts of the path,
11400 the default is \"/\"."
11401 (setq width (or width 79))
11402 (if prefix (setq width (- width (length prefix))))
11403 (if (not path)
11404 (or prefix "")
11405 (let* ((nsteps (length path))
11406 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11407 (maxwidth (if (<= total-width width)
11408 10000 ;; everything fits
11409 ;; we need to shorten the level headings
11410 (/ (- width nsteps) nsteps)))
11411 (org-odd-levels-only nil)
11412 (n 0)
11413 (total (1+ (length prefix))))
11414 (setq maxwidth (max maxwidth 10))
11415 (concat prefix
11416 (if prefix (or separator "/"))
11417 (mapconcat
11418 (lambda (h)
11419 (setq n (1+ n))
11420 (if (and (= n nsteps) (< maxwidth 10000))
11421 (setq maxwidth (- total-width total)))
11422 (if (< (length h) maxwidth)
11423 (progn (setq total (+ total (length h) 1)) h)
11424 (setq h (substring h 0 (- maxwidth 2))
11425 total (+ total maxwidth 1))
11426 (if (string-match "[ \t]+\\'" h)
11427 (setq h (substring h 0 (match-beginning 0))))
11428 (setq h (concat h "..")))
11429 (org-add-props h nil 'face
11430 (nth (% (1- n) org-n-level-faces)
11431 org-level-faces))
11433 path (or separator "/"))))))
11435 (defun org-display-outline-path (&optional file current separator just-return-string)
11436 "Display the current outline path in the echo area.
11438 If FILE is non-nil, prepend the output with the file name.
11439 If CURRENT is non-nil, append the current heading to the output.
11440 SEPARATOR is passed through to `org-format-outline-path'. It separates
11441 the different parts of the path and defaults to \"/\".
11442 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11443 (interactive "P")
11444 (let* (case-fold-search
11445 (bfn (buffer-file-name (buffer-base-buffer)))
11446 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11447 res)
11448 (if current (setq path (append path
11449 (save-excursion
11450 (org-back-to-heading t)
11451 (if (looking-at org-complex-heading-regexp)
11452 (list (match-string 4)))))))
11453 (setq res
11454 (org-format-outline-path
11455 path
11456 (1- (frame-width))
11457 (and file bfn (concat (file-name-nondirectory bfn) separator))
11458 separator))
11459 (if just-return-string
11460 (org-no-properties res)
11461 (org-unlogged-message "%s" res))))
11463 (defvar org-refile-history nil
11464 "History for refiling operations.")
11466 (defvar org-after-refile-insert-hook nil
11467 "Hook run after `org-refile' has inserted its stuff at the new location.
11468 Note that this is still *before* the stuff will be removed from
11469 the *old* location.")
11471 (defvar org-capture-last-stored-marker)
11472 (defvar org-refile-keep nil
11473 "Non-nil means `org-refile' will copy instead of refile.")
11475 (defun org-copy ()
11476 "Like `org-refile', but copy."
11477 (interactive)
11478 (let ((org-refile-keep t))
11479 (funcall 'org-refile nil nil nil "Copy")))
11481 (defun org-refile (&optional goto default-buffer rfloc msg)
11482 "Move the entry or entries at point to another heading.
11483 The list of target headings is compiled using the information in
11484 `org-refile-targets', which see.
11486 At the target location, the entry is filed as a subitem of the target
11487 heading. Depending on `org-reverse-note-order', the new subitem will
11488 either be the first or the last subitem.
11490 If there is an active region, all entries in that region will be moved.
11491 However, the region must fulfill the requirement that the first heading
11492 is the first one sets the top-level of the moved text - at most siblings
11493 below it are allowed.
11495 With prefix arg GOTO, the command will only visit the target location
11496 and not actually move anything.
11498 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11499 go to the location where the last refiling operation has put the subtree.
11501 With a numeric prefix argument of `2', refile to the running clock.
11503 With a numeric prefix argument of `3', emulate `org-refile-keep'
11504 being set to `t' and copy to the target location, don't move it.
11505 Beware that keeping refiled entries may result in duplicated ID
11506 properties.
11508 RFLOC can be a refile location obtained in a different way.
11510 MSG is a string to replace \"Refile\" in the default prompt with
11511 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11513 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11515 If you are using target caching (see `org-refile-use-cache'),
11516 you have to clear the target cache in order to find new targets.
11517 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11518 prefix argument (`C-u C-u C-u C-c C-w')."
11520 (interactive "P")
11521 (if (member goto '(0 (64)))
11522 (org-refile-cache-clear)
11523 (let* ((actionmsg (cond (msg msg)
11524 ((equal goto 3) "Refile (and keep)")
11525 (t "Refile")))
11526 (cbuf (current-buffer))
11527 (regionp (org-region-active-p))
11528 (region-start (and regionp (region-beginning)))
11529 (region-end (and regionp (region-end)))
11530 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11531 (org-refile-keep (if (equal goto 3) t org-refile-keep))
11532 pos it nbuf file re level reversed)
11533 (setq last-command nil)
11534 (when regionp
11535 (goto-char region-start)
11536 (or (bolp) (goto-char (point-at-bol)))
11537 (setq region-start (point))
11538 (unless (or (org-kill-is-subtree-p
11539 (buffer-substring region-start region-end))
11540 (prog1 org-refile-active-region-within-subtree
11541 (let ((s (point-at-eol)))
11542 (org-toggle-heading)
11543 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11544 (user-error "The region is not a (sequence of) subtree(s)")))
11545 (if (equal goto '(16))
11546 (org-refile-goto-last-stored)
11547 (when (or
11548 (and (equal goto 2)
11549 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11550 (prog1
11551 (setq it (list (or org-clock-heading "running clock")
11552 (buffer-file-name
11553 (marker-buffer org-clock-hd-marker))
11555 (marker-position org-clock-hd-marker)))
11556 (setq goto nil)))
11557 (setq it (or rfloc
11558 (let (heading-text)
11559 (save-excursion
11560 (unless (and goto (listp goto))
11561 (org-back-to-heading t)
11562 (setq heading-text
11563 (nth 4 (org-heading-components))))
11565 (org-refile-get-location
11566 (cond ((and goto (listp goto)) "Goto")
11567 (regionp (concat actionmsg " region to"))
11568 (t (concat actionmsg " subtree \""
11569 heading-text "\" to")))
11570 default-buffer
11571 (and (not (equal '(4) goto))
11572 org-refile-allow-creating-parent-nodes)
11573 goto))))))
11574 (setq file (nth 1 it)
11575 re (nth 2 it)
11576 pos (nth 3 it))
11577 (if (and (not goto)
11579 (equal (buffer-file-name) file)
11580 (if regionp
11581 (and (>= pos region-start)
11582 (<= pos region-end))
11583 (and (>= pos (point))
11584 (< pos (save-excursion
11585 (org-end-of-subtree t t))))))
11586 (error "Cannot refile to position inside the tree or region"))
11588 (setq nbuf (or (find-buffer-visiting file)
11589 (find-file-noselect file)))
11590 (if (and goto (not (equal goto 3)))
11591 (progn
11592 (org-pop-to-buffer-same-window nbuf)
11593 (goto-char pos)
11594 (org-show-context 'org-goto))
11595 (if regionp
11596 (progn
11597 (org-kill-new (buffer-substring region-start region-end))
11598 (org-save-markers-in-region region-start region-end))
11599 (org-copy-subtree 1 nil t))
11600 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11601 (find-file-noselect file)))
11602 (setq reversed (org-notes-order-reversed-p))
11603 (save-excursion
11604 (save-restriction
11605 (widen)
11606 (if pos
11607 (progn
11608 (goto-char pos)
11609 (looking-at org-outline-regexp)
11610 (setq level (org-get-valid-level (funcall outline-level) 1))
11611 (goto-char
11612 (if reversed
11613 (or (outline-next-heading) (point-max))
11614 (or (save-excursion (org-get-next-sibling))
11615 (org-end-of-subtree t t)
11616 (point-max)))))
11617 (setq level 1)
11618 (if (not reversed)
11619 (goto-char (point-max))
11620 (goto-char (point-min))
11621 (or (outline-next-heading) (goto-char (point-max)))))
11622 (if (not (bolp)) (newline))
11623 (org-paste-subtree level)
11624 (when org-log-refile
11625 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11626 (unless (eq org-log-refile 'note)
11627 (save-excursion (org-add-log-note))))
11628 (and org-auto-align-tags
11629 (let ((org-loop-over-headlines-in-active-region nil))
11630 (org-set-tags nil t)))
11631 (let ((bookmark-name (plist-get org-bookmark-names-plist
11632 :last-refile)))
11633 (when bookmark-name
11634 (with-demoted-errors
11635 (bookmark-set bookmark-name))))
11636 ;; If we are refiling for capture, make sure that the
11637 ;; last-capture pointers point here
11638 (when (org-bound-and-true-p org-refile-for-capture)
11639 (let ((bookmark-name (plist-get org-bookmark-names-plist
11640 :last-capture-marker)))
11641 (when bookmark-name
11642 (with-demoted-errors
11643 (bookmark-set bookmark-name))))
11644 (move-marker org-capture-last-stored-marker (point)))
11645 (if (fboundp 'deactivate-mark) (deactivate-mark))
11646 (run-hooks 'org-after-refile-insert-hook))))
11647 (unless org-refile-keep
11648 (if regionp
11649 (delete-region (point) (+ (point) (- region-end region-start)))
11650 (delete-region
11651 (and (org-back-to-heading t) (point))
11652 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11653 (when (featurep 'org-inlinetask)
11654 (org-inlinetask-remove-END-maybe))
11655 (setq org-markers-to-move nil)
11656 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11658 (defun org-refile-goto-last-stored ()
11659 "Go to the location where the last refile was stored."
11660 (interactive)
11661 (bookmark-jump "org-refile-last-stored")
11662 (message "This is the location of the last refile"))
11664 (defun org-refile--get-location (refloc tbl)
11665 "When user refile to REFLOC, find the associated target in TBL.
11666 Also check `org-refile-target-table'."
11667 (car (delq
11669 (mapcar
11670 (lambda (r) (or (assoc r tbl)
11671 (assoc r org-refile-target-table)))
11672 (list (replace-regexp-in-string "/$" "" refloc)
11673 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11675 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11676 no-exclude)
11677 "Prompt the user for a refile location, using PROMPT.
11678 PROMPT should not be suffixed with a colon and a space, because
11679 this function appends the default value from
11680 `org-refile-history' automatically, if that is not empty.
11681 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11682 this is used for the GOTO interface."
11683 (let ((org-refile-targets org-refile-targets)
11684 (org-refile-use-outline-path org-refile-use-outline-path)
11685 excluded-entries)
11686 (when (and (derived-mode-p 'org-mode)
11687 (not org-refile-use-cache)
11688 (not no-exclude))
11689 (org-map-tree
11690 (lambda()
11691 (setq excluded-entries
11692 (append excluded-entries (list (org-get-heading t t)))))))
11693 (setq org-refile-target-table
11694 (org-refile-get-targets default-buffer excluded-entries)))
11695 (unless org-refile-target-table
11696 (user-error "No refile targets"))
11697 (let* ((cbuf (current-buffer))
11698 (partial-completion-mode nil)
11699 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11700 (cfunc (if (and org-refile-use-outline-path
11701 org-outline-path-complete-in-steps)
11702 'org-olpath-completing-read
11703 'org-icompleting-read))
11704 (extra (if org-refile-use-outline-path "/" ""))
11705 (cbnex (concat (buffer-name) extra))
11706 (filename (and cfn (expand-file-name cfn)))
11707 (tbl (mapcar
11708 (lambda (x)
11709 (if (and (not (member org-refile-use-outline-path
11710 '(file full-file-path)))
11711 (not (equal filename (nth 1 x))))
11712 (cons (concat (car x) extra " ("
11713 (file-name-nondirectory (nth 1 x)) ")")
11714 (cdr x))
11715 (cons (concat (car x) extra) (cdr x))))
11716 org-refile-target-table))
11717 (completion-ignore-case t)
11718 cdef
11719 (prompt (concat prompt
11720 (or (and (car org-refile-history)
11721 (concat " (default " (car org-refile-history) ")"))
11722 (and (assoc cbnex tbl) (setq cdef cbnex)
11723 (concat " (default " cbnex ")"))) ": "))
11724 pa answ parent-target child parent old-hist)
11725 (setq old-hist org-refile-history)
11726 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11727 nil 'org-refile-history (or cdef (car org-refile-history))))
11728 (if (setq pa (org-refile--get-location answ tbl))
11729 (progn
11730 (org-refile-check-position pa)
11731 (when (or (not org-refile-history)
11732 (not (eq old-hist org-refile-history))
11733 (not (equal (car pa) (car org-refile-history))))
11734 (setq org-refile-history
11735 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11736 org-refile-history
11737 (cdr org-refile-history))))
11738 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11739 (pop org-refile-history)))
11741 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11742 (progn
11743 (setq parent (match-string 1 answ)
11744 child (match-string 2 answ))
11745 (setq parent-target (org-refile--get-location parent tbl))
11746 (when (and parent-target
11747 (or (eq new-nodes t)
11748 (and (eq new-nodes 'confirm)
11749 (y-or-n-p (format "Create new node \"%s\"? "
11750 child)))))
11751 (org-refile-new-child parent-target child)))
11752 (user-error "Invalid target location")))))
11754 (declare-function org-string-nw-p "org-macs" (s))
11755 (defun org-refile-check-position (refile-pointer)
11756 "Check if the refile pointer matches the headline to which it points."
11757 (let* ((file (nth 1 refile-pointer))
11758 (re (nth 2 refile-pointer))
11759 (pos (nth 3 refile-pointer))
11760 buffer)
11761 (if (and (not (markerp pos)) (not file))
11762 (user-error "Please save the buffer to a file before refiling")
11763 (when (org-string-nw-p re)
11764 (setq buffer (if (markerp pos)
11765 (marker-buffer pos)
11766 (or (find-buffer-visiting file)
11767 (find-file-noselect file))))
11768 (with-current-buffer buffer
11769 (save-excursion
11770 (save-restriction
11771 (widen)
11772 (goto-char pos)
11773 (beginning-of-line 1)
11774 (unless (org-looking-at-p re)
11775 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11777 (defun org-refile-new-child (parent-target child)
11778 "Use refile target PARENT-TARGET to add new CHILD below it."
11779 (unless parent-target
11780 (error "Cannot find parent for new node"))
11781 (let ((file (nth 1 parent-target))
11782 (pos (nth 3 parent-target))
11783 level)
11784 (with-current-buffer (or (find-buffer-visiting file)
11785 (find-file-noselect file))
11786 (save-excursion
11787 (save-restriction
11788 (widen)
11789 (if pos
11790 (goto-char pos)
11791 (goto-char (point-max))
11792 (if (not (bolp)) (newline)))
11793 (when (looking-at org-outline-regexp)
11794 (setq level (funcall outline-level))
11795 (org-end-of-subtree t t))
11796 (org-back-over-empty-lines)
11797 (insert "\n" (make-string
11798 (if pos (org-get-valid-level level 1) 1) ?*)
11799 " " child "\n")
11800 (beginning-of-line 0)
11801 (list (concat (car parent-target) "/" child) file "" (point)))))))
11803 (defun org-olpath-completing-read (prompt collection &rest args)
11804 "Read an outline path like a file name."
11805 (let ((thetable collection)
11806 (org-completion-use-ido nil) ; does not work with ido.
11807 (org-completion-use-iswitchb nil)) ; or iswitchb
11808 (apply
11809 'org-icompleting-read prompt
11810 (lambda (string predicate &optional flag)
11811 (let (rtn r f (l (length string)))
11812 (cond
11813 ((eq flag nil)
11814 ;; try completion
11815 (try-completion string thetable))
11816 ((eq flag t)
11817 ;; all-completions
11818 (setq rtn (all-completions string thetable predicate))
11819 (mapcar
11820 (lambda (x)
11821 (setq r (substring x l))
11822 (if (string-match " ([^)]*)$" x)
11823 (setq f (match-string 0 x))
11824 (setq f ""))
11825 (if (string-match "/" r)
11826 (concat string (substring r 0 (match-end 0)) f)
11828 rtn))
11829 ((eq flag 'lambda)
11830 ;; exact match?
11831 (assoc string thetable)))))
11832 args)))
11834 ;;;; Dynamic blocks
11836 (defun org-find-dblock (name)
11837 "Find the first dynamic block with name NAME in the buffer.
11838 If not found, stay at current position and return nil."
11839 (let ((case-fold-search t) pos)
11840 (save-excursion
11841 (goto-char (point-min))
11842 (setq pos (and (re-search-forward
11843 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11844 (match-beginning 0))))
11845 (if pos (goto-char pos))
11846 pos))
11848 (defconst org-dblock-start-re
11849 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11850 "Matches the start line of a dynamic block, with parameters.")
11852 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11853 "Matches the end of a dynamic block.")
11855 (defun org-create-dblock (plist)
11856 "Create a dynamic block section, with parameters taken from PLIST.
11857 PLIST must contain a :name entry which is used as name of the block."
11858 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11859 (end-of-line 1)
11860 (newline))
11861 (let ((col (current-column))
11862 (name (plist-get plist :name)))
11863 (insert "#+BEGIN: " name)
11864 (while plist
11865 (if (eq (car plist) :name)
11866 (setq plist (cddr plist))
11867 (insert " " (prin1-to-string (pop plist)))))
11868 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11869 (beginning-of-line -2)))
11871 (defun org-prepare-dblock ()
11872 "Prepare dynamic block for refresh.
11873 This empties the block, puts the cursor at the insert position and returns
11874 the property list including an extra property :name with the block name."
11875 (unless (looking-at org-dblock-start-re)
11876 (user-error "Not at a dynamic block"))
11877 (let* ((begdel (1+ (match-end 0)))
11878 (name (org-no-properties (match-string 1)))
11879 (params (append (list :name name)
11880 (read (concat "(" (match-string 3) ")")))))
11881 (save-excursion
11882 (beginning-of-line 1)
11883 (skip-chars-forward " \t")
11884 (setq params (plist-put params :indentation-column (current-column))))
11885 (unless (re-search-forward org-dblock-end-re nil t)
11886 (error "Dynamic block not terminated"))
11887 (setq params
11888 (append params
11889 (list :content (buffer-substring
11890 begdel (match-beginning 0)))))
11891 (delete-region begdel (match-beginning 0))
11892 (goto-char begdel)
11893 (open-line 1)
11894 params))
11896 (defun org-map-dblocks (&optional command)
11897 "Apply COMMAND to all dynamic blocks in the current buffer.
11898 If COMMAND is not given, use `org-update-dblock'."
11899 (let ((cmd (or command 'org-update-dblock)))
11900 (save-excursion
11901 (goto-char (point-min))
11902 (while (re-search-forward org-dblock-start-re nil t)
11903 (goto-char (match-beginning 0))
11904 (save-excursion
11905 (condition-case nil
11906 (funcall cmd)
11907 (error (message "Error during update of dynamic block"))))
11908 (unless (re-search-forward org-dblock-end-re nil t)
11909 (error "Dynamic block not terminated"))))))
11911 (defun org-dblock-update (&optional arg)
11912 "User command for updating dynamic blocks.
11913 Update the dynamic block at point. With prefix ARG, update all dynamic
11914 blocks in the buffer."
11915 (interactive "P")
11916 (if arg
11917 (org-update-all-dblocks)
11918 (or (looking-at org-dblock-start-re)
11919 (org-beginning-of-dblock))
11920 (org-update-dblock)))
11922 (defun org-update-dblock ()
11923 "Update the dynamic block at point.
11924 This means to empty the block, parse for parameters and then call
11925 the correct writing function."
11926 (interactive)
11927 (save-window-excursion
11928 (let* ((pos (point))
11929 (line (org-current-line))
11930 (params (org-prepare-dblock))
11931 (name (plist-get params :name))
11932 (indent (plist-get params :indentation-column))
11933 (cmd (intern (concat "org-dblock-write:" name))))
11934 (message "Updating dynamic block `%s' at line %d..." name line)
11935 (funcall cmd params)
11936 (message "Updating dynamic block `%s' at line %d...done" name line)
11937 (goto-char pos)
11938 (when (and indent (> indent 0))
11939 (setq indent (make-string indent ?\ ))
11940 (save-excursion
11941 (org-beginning-of-dblock)
11942 (forward-line 1)
11943 (while (not (looking-at org-dblock-end-re))
11944 (insert indent)
11945 (beginning-of-line 2))
11946 (when (looking-at org-dblock-end-re)
11947 (and (looking-at "[ \t]+")
11948 (replace-match ""))
11949 (insert indent)))))))
11951 (defun org-beginning-of-dblock ()
11952 "Find the beginning of the dynamic block at point.
11953 Error if there is no such block at point."
11954 (let ((pos (point))
11955 beg)
11956 (end-of-line 1)
11957 (if (and (re-search-backward org-dblock-start-re nil t)
11958 (setq beg (match-beginning 0))
11959 (re-search-forward org-dblock-end-re nil t)
11960 (> (match-end 0) pos))
11961 (goto-char beg)
11962 (goto-char pos)
11963 (error "Not in a dynamic block"))))
11965 (defun org-update-all-dblocks ()
11966 "Update all dynamic blocks in the buffer.
11967 This function can be used in a hook."
11968 (interactive)
11969 (when (derived-mode-p 'org-mode)
11970 (org-map-dblocks 'org-update-dblock)))
11973 ;;;; Completion
11975 (declare-function org-export-backend-name "org-export" (cl-x))
11976 (declare-function org-export-backend-options "org-export" (cl-x))
11977 (defun org-get-export-keywords ()
11978 "Return a list of all currently understood export keywords.
11979 Export keywords include options, block names, attributes and
11980 keywords relative to each registered export back-end."
11981 (let (keywords)
11982 (dolist (backend
11983 (org-bound-and-true-p org-export--registered-backends)
11984 (delq nil keywords))
11985 ;; Back-end name (for keywords, like #+LATEX:)
11986 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
11987 (dolist (option-entry (org-export-backend-options backend))
11988 ;; Back-end options.
11989 (push (nth 1 option-entry) keywords)))))
11991 (defconst org-options-keywords
11992 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11993 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11994 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11995 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11996 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11998 (defcustom org-structure-template-alist
11999 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC" "<src lang=\"?\">\n\n</src>")
12000 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE" "<example>\n?\n</example>")
12001 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE" "<quote>\n?\n</quote>")
12002 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE" "<verse>\n?\n</verse>")
12003 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM" "<verbatim>\n?\n</verbatim>")
12004 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER" "<center>\n?\n</center>")
12005 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
12006 "<literal style=\"latex\">\n?\n</literal>")
12007 ("L" "#+LaTeX: " "<literal style=\"latex\">?</literal>")
12008 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
12009 "<literal style=\"html\">\n?\n</literal>")
12010 ("H" "#+HTML: " "<literal style=\"html\">?</literal>")
12011 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII" "")
12012 ("A" "#+ASCII: " "")
12013 ("i" "#+INDEX: ?" "#+INDEX: ?")
12014 ("I" "#+INCLUDE: %file ?"
12015 "<include file=%file markup=\"?\">"))
12016 "Structure completion elements.
12017 This is a list of abbreviation keys and values. The value gets inserted
12018 if you type `<' followed by the key and then press the completion key,
12019 usually `M-TAB'. %file will be replaced by a file name after prompting
12020 for the file using completion. The cursor will be placed at the position
12021 of the `?` in the template.
12022 There are two templates for each key, the first uses the original Org syntax,
12023 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12024 the default when the /org-mtags.el/ module has been loaded. See also the
12025 variable `org-mtags-prefer-muse-templates'."
12026 :group 'org-completion
12027 :type '(repeat
12028 (list
12029 (string :tag "Key")
12030 (string :tag "Template")
12031 (string :tag "Muse Template"))))
12033 (defun org-try-structure-completion ()
12034 "Try to complete a structure template before point.
12035 This looks for strings like \"<e\" on an otherwise empty line and
12036 expands them."
12037 (let ((l (buffer-substring (point-at-bol) (point)))
12039 (when (and (looking-at "[ \t]*$")
12040 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12041 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12042 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12043 (match-beginning 1)) a)
12044 t)))
12046 (defun org-complete-expand-structure-template (start cell)
12047 "Expand a structure template."
12048 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
12049 (rpl (nth (if musep 2 1) cell))
12050 (ind ""))
12051 (delete-region start (point))
12052 (when (string-match "\\`#\\+" rpl)
12053 (cond
12054 ((bolp))
12055 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12056 (setq ind (buffer-substring (point-at-bol) (point))))
12057 (t (newline))))
12058 (setq start (point))
12059 (if (string-match "%file" rpl)
12060 (setq rpl (replace-match
12061 (concat
12062 "\""
12063 (save-match-data
12064 (abbreviate-file-name (read-file-name "Include file: ")))
12065 "\"")
12066 t t rpl)))
12067 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12068 (concat "\n" ind)))
12069 (insert rpl)
12070 (if (re-search-backward "\\?" start t) (delete-char 1))))
12072 ;;;; TODO, DEADLINE, Comments
12074 (defun org-toggle-comment ()
12075 "Change the COMMENT state of an entry."
12076 (interactive)
12077 (save-excursion
12078 (org-back-to-heading)
12079 (let (case-fold-search)
12080 (cond
12081 ((looking-at (format org-heading-keyword-regexp-format
12082 org-comment-string))
12083 (goto-char (match-end 1))
12084 (looking-at (concat " +" org-comment-string))
12085 (replace-match "" t t)
12086 (when (eolp) (insert " ")))
12087 ((looking-at org-outline-regexp)
12088 (goto-char (match-end 0))
12089 (insert org-comment-string " "))))))
12091 (defvar org-last-todo-state-is-todo nil
12092 "This is non-nil when the last TODO state change led to a TODO state.
12093 If the last change removed the TODO tag or switched to DONE, then
12094 this is nil.")
12096 (defvar org-setting-tags nil) ; dynamically skipped
12098 (defvar org-todo-setup-filter-hook nil
12099 "Hook for functions that pre-filter todo specs.
12100 Each function takes a todo spec and returns either nil or the spec
12101 transformed into canonical form." )
12103 (defvar org-todo-get-default-hook nil
12104 "Hook for functions that get a default item for todo.
12105 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12106 nil or a string to be used for the todo mark." )
12108 (defvar org-agenda-headline-snapshot-before-repeat)
12110 (defun org-current-effective-time ()
12111 "Return current time adjusted for `org-extend-today-until' variable."
12112 (let* ((ct (org-current-time))
12113 (dct (decode-time ct))
12114 (ct1
12115 (cond
12116 (org-use-last-clock-out-time-as-effective-time
12117 (or (org-clock-get-last-clock-out-time) ct))
12118 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12119 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12120 (t ct))))
12121 ct1))
12123 (defun org-todo-yesterday (&optional arg)
12124 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12125 (interactive "P")
12126 (if (eq major-mode 'org-agenda-mode)
12127 (apply 'org-agenda-todo-yesterday arg)
12128 (let* ((hour (third (decode-time
12129 (org-current-time))))
12130 (org-extend-today-until (1+ hour)))
12131 (org-todo arg))))
12133 (defvar org-block-entry-blocking ""
12134 "First entry preventing the TODO state change.")
12136 (defun org-todo (&optional arg)
12137 "Change the TODO state of an item.
12138 The state of an item is given by a keyword at the start of the heading,
12139 like
12140 *** TODO Write paper
12141 *** DONE Call mom
12143 The different keywords are specified in the variable `org-todo-keywords'.
12144 By default the available states are \"TODO\" and \"DONE\".
12145 So for this example: when the item starts with TODO, it is changed to DONE.
12146 When it starts with DONE, the DONE is removed. And when neither TODO nor
12147 DONE are present, add TODO at the beginning of the heading.
12149 With \\[universal-argument] prefix arg, use completion to determine the new \
12150 state.
12151 With numeric prefix arg, switch to that state.
12152 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12153 keywords (nextset).
12154 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12155 With a numeric prefix arg of 0, inhibit note taking for the change.
12157 For calling through lisp, arg is also interpreted in the following way:
12158 'none -> empty state
12159 \"\"(empty string) -> switch to empty state
12160 'done -> switch to DONE
12161 'nextset -> switch to the next set of keywords
12162 'previousset -> switch to the previous set of keywords
12163 \"WAITING\" -> switch to the specified keyword, but only if it
12164 really is a member of `org-todo-keywords'."
12165 (interactive "P")
12166 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12167 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12168 'region-start-level 'region))
12169 org-loop-over-headlines-in-active-region)
12170 (org-map-entries
12171 `(org-todo ,arg)
12172 org-loop-over-headlines-in-active-region
12173 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12174 (if (equal arg '(16)) (setq arg 'nextset))
12175 (let ((org-blocker-hook org-blocker-hook)
12176 commentp
12177 case-fold-search)
12178 (when (equal arg '(64))
12179 (setq arg nil org-blocker-hook nil))
12180 (when (and org-blocker-hook
12181 (or org-inhibit-blocking
12182 (org-entry-get nil "NOBLOCKING")))
12183 (setq org-blocker-hook nil))
12184 (save-excursion
12185 (catch 'exit
12186 (org-back-to-heading t)
12187 (when (looking-at (concat "^\\*+ " org-comment-string))
12188 (org-toggle-comment)
12189 (setq commentp t))
12190 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12191 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12192 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12193 (let* ((match-data (match-data))
12194 (startpos (point-at-bol))
12195 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12196 (org-log-done org-log-done)
12197 (org-log-repeat org-log-repeat)
12198 (org-todo-log-states org-todo-log-states)
12199 (org-inhibit-logging
12200 (if (equal arg 0)
12201 (progn (setq arg nil) 'note) org-inhibit-logging))
12202 (this (match-string 1))
12203 (hl-pos (match-beginning 0))
12204 (head (org-get-todo-sequence-head this))
12205 (ass (assoc head org-todo-kwd-alist))
12206 (interpret (nth 1 ass))
12207 (done-word (nth 3 ass))
12208 (final-done-word (nth 4 ass))
12209 (org-last-state (or this ""))
12210 (completion-ignore-case t)
12211 (member (member this org-todo-keywords-1))
12212 (tail (cdr member))
12213 (org-state (cond
12214 ((and org-todo-key-trigger
12215 (or (and (equal arg '(4))
12216 (eq org-use-fast-todo-selection 'prefix))
12217 (and (not arg) org-use-fast-todo-selection
12218 (not (eq org-use-fast-todo-selection
12219 'prefix)))))
12220 ;; Use fast selection
12221 (org-fast-todo-selection))
12222 ((and (equal arg '(4))
12223 (or (not org-use-fast-todo-selection)
12224 (not org-todo-key-trigger)))
12225 ;; Read a state with completion
12226 (org-icompleting-read
12227 "State: " (mapcar 'list org-todo-keywords-1)
12228 nil t))
12229 ((eq arg 'right)
12230 (if this
12231 (if tail (car tail) nil)
12232 (car org-todo-keywords-1)))
12233 ((eq arg 'left)
12234 (if (equal member org-todo-keywords-1)
12236 (if this
12237 (nth (- (length org-todo-keywords-1)
12238 (length tail) 2)
12239 org-todo-keywords-1)
12240 (org-last org-todo-keywords-1))))
12241 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12242 (setq arg nil))) ; hack to fall back to cycling
12243 (arg
12244 ;; user or caller requests a specific state
12245 (cond
12246 ((equal arg "") nil)
12247 ((eq arg 'none) nil)
12248 ((eq arg 'done) (or done-word (car org-done-keywords)))
12249 ((eq arg 'nextset)
12250 (or (car (cdr (member head org-todo-heads)))
12251 (car org-todo-heads)))
12252 ((eq arg 'previousset)
12253 (let ((org-todo-heads (reverse org-todo-heads)))
12254 (or (car (cdr (member head org-todo-heads)))
12255 (car org-todo-heads))))
12256 ((car (member arg org-todo-keywords-1)))
12257 ((stringp arg)
12258 (user-error "State `%s' not valid in this file" arg))
12259 ((nth (1- (prefix-numeric-value arg))
12260 org-todo-keywords-1))))
12261 ((null member) (or head (car org-todo-keywords-1)))
12262 ((equal this final-done-word) nil) ;; -> make empty
12263 ((null tail) nil) ;; -> first entry
12264 ((memq interpret '(type priority))
12265 (if (eq this-command last-command)
12266 (car tail)
12267 (if (> (length tail) 0)
12268 (or done-word (car org-done-keywords))
12269 nil)))
12271 (car tail))))
12272 (org-state (or
12273 (run-hook-with-args-until-success
12274 'org-todo-get-default-hook org-state org-last-state)
12275 org-state))
12276 (next (if org-state (concat " " org-state " ") " "))
12277 (change-plist (list :type 'todo-state-change :from this :to org-state
12278 :position startpos))
12279 dolog now-done-p)
12280 (when org-blocker-hook
12281 (setq org-last-todo-state-is-todo
12282 (not (member this org-done-keywords)))
12283 (unless (save-excursion
12284 (save-match-data
12285 (org-with-wide-buffer
12286 (run-hook-with-args-until-failure
12287 'org-blocker-hook change-plist))))
12288 (if (org-called-interactively-p 'interactive)
12289 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12290 this org-state org-block-entry-blocking)
12291 ;; fail silently
12292 (message "TODO state change from %s to %s blocked (by \"%s\")"
12293 this org-state org-block-entry-blocking)
12294 (throw 'exit nil))))
12295 (store-match-data match-data)
12296 (replace-match next t t)
12297 (unless (pos-visible-in-window-p hl-pos)
12298 (message "TODO state changed to %s" (org-trim next)))
12299 (unless head
12300 (setq head (org-get-todo-sequence-head org-state)
12301 ass (assoc head org-todo-kwd-alist)
12302 interpret (nth 1 ass)
12303 done-word (nth 3 ass)
12304 final-done-word (nth 4 ass)))
12305 (when (memq arg '(nextset previousset))
12306 (message "Keyword-Set %d/%d: %s"
12307 (- (length org-todo-sets) -1
12308 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12309 (length org-todo-sets)
12310 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12311 (setq org-last-todo-state-is-todo
12312 (not (member org-state org-done-keywords)))
12313 (setq now-done-p (and (member org-state org-done-keywords)
12314 (not (member this org-done-keywords))))
12315 (and logging (org-local-logging logging))
12316 (when (and (or org-todo-log-states org-log-done)
12317 (not (eq org-inhibit-logging t))
12318 (not (memq arg '(nextset previousset))))
12319 ;; we need to look at recording a time and note
12320 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12321 (nth 2 (assoc this org-todo-log-states))))
12322 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12323 (setq dolog 'time))
12324 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12325 (and org-state
12326 (member org-state org-not-done-keywords)
12327 (not (member this org-not-done-keywords))))
12328 ;; This is now a todo state and was not one before
12329 ;; If there was a CLOSED time stamp, get rid of it.
12330 (org-add-planning-info nil nil 'closed))
12331 (when (and now-done-p org-log-done)
12332 ;; It is now done, and it was not done before
12333 (org-add-planning-info 'closed (org-current-effective-time))
12334 (if (and (not dolog) (eq 'note org-log-done))
12335 (org-add-log-setup 'done org-state this 'findpos 'note)))
12336 (when (and org-state dolog)
12337 ;; This is a non-nil state, and we need to log it
12338 (org-add-log-setup 'state org-state this 'findpos dolog)))
12339 ;; Fixup tag positioning
12340 (org-todo-trigger-tag-changes org-state)
12341 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12342 (when org-provide-todo-statistics
12343 (org-update-parent-todo-statistics))
12344 (run-hooks 'org-after-todo-state-change-hook)
12345 (if (and arg (not (member org-state org-done-keywords)))
12346 (setq head (org-get-todo-sequence-head org-state)))
12347 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12348 ;; Do we need to trigger a repeat?
12349 (when now-done-p
12350 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12351 ;; This is for the agenda, take a snapshot of the headline.
12352 (save-match-data
12353 (setq org-agenda-headline-snapshot-before-repeat
12354 (org-get-heading))))
12355 (org-auto-repeat-maybe org-state))
12356 ;; Fixup cursor location if close to the keyword
12357 (if (and (outline-on-heading-p)
12358 (not (bolp))
12359 (save-excursion (beginning-of-line 1)
12360 (looking-at org-todo-line-regexp))
12361 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12362 (progn
12363 (goto-char (or (match-end 2) (match-end 1)))
12364 (and (looking-at " ") (just-one-space))))
12365 (when org-trigger-hook
12366 (save-excursion
12367 (run-hook-with-args 'org-trigger-hook change-plist)))
12368 (when commentp (org-toggle-comment))))))))
12370 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12371 "Block turning an entry into a TODO, using the hierarchy.
12372 This checks whether the current task should be blocked from state
12373 changes. Such blocking occurs when:
12375 1. The task has children which are not all in a completed state.
12377 2. A task has a parent with the property :ORDERED:, and there
12378 are siblings prior to the current task with incomplete
12379 status.
12381 3. The parent of the task is blocked because it has siblings that should
12382 be done first, or is child of a block grandparent TODO entry."
12384 (if (not org-enforce-todo-dependencies)
12385 t ; if locally turned off don't block
12386 (catch 'dont-block
12387 ;; If this is not a todo state change, or if this entry is already DONE,
12388 ;; do not block
12389 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12390 (member (plist-get change-plist :from)
12391 (cons 'done org-done-keywords))
12392 (member (plist-get change-plist :to)
12393 (cons 'todo org-not-done-keywords))
12394 (not (plist-get change-plist :to)))
12395 (throw 'dont-block t))
12396 ;; If this task has children, and any are undone, it's blocked
12397 (save-excursion
12398 (org-back-to-heading t)
12399 (let ((this-level (funcall outline-level)))
12400 (outline-next-heading)
12401 (let ((child-level (funcall outline-level)))
12402 (while (and (not (eobp))
12403 (> child-level this-level))
12404 ;; this todo has children, check whether they are all
12405 ;; completed
12406 (if (and (not (org-entry-is-done-p))
12407 (org-entry-is-todo-p))
12408 (progn (setq org-block-entry-blocking (org-get-heading))
12409 (throw 'dont-block nil)))
12410 (outline-next-heading)
12411 (setq child-level (funcall outline-level))))))
12412 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12413 ;; any previous siblings are undone, it's blocked
12414 (save-excursion
12415 (org-back-to-heading t)
12416 (let* ((pos (point))
12417 (parent-pos (and (org-up-heading-safe) (point))))
12418 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12419 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12420 (forward-line 1)
12421 (re-search-forward org-not-done-heading-regexp pos t))
12422 (setq org-block-entry-blocking (match-string 0))
12423 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12424 ;; Search further up the hierarchy, to see if an ancestor is blocked
12425 (while t
12426 (goto-char parent-pos)
12427 (if (not (looking-at org-not-done-heading-regexp))
12428 (throw 'dont-block t)) ; do not block, parent is not a TODO
12429 (setq pos (point))
12430 (setq parent-pos (and (org-up-heading-safe) (point)))
12431 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12432 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12433 (forward-line 1)
12434 (re-search-forward org-not-done-heading-regexp pos t)
12435 (setq org-block-entry-blocking (org-get-heading)))
12436 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12438 (defcustom org-track-ordered-property-with-tag nil
12439 "Should the ORDERED property also be shown as a tag?
12440 The ORDERED property decides if an entry should require subtasks to be
12441 completed in sequence. Since a property is not very visible, setting
12442 this option means that toggling the ORDERED property with the command
12443 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12444 not relevant for the behavior, but it makes things more visible.
12446 Note that toggling the tag with tags commands will not change the property
12447 and therefore not influence behavior!
12449 This can be t, meaning the tag ORDERED should be used, It can also be a
12450 string to select a different tag for this task."
12451 :group 'org-todo
12452 :type '(choice
12453 (const :tag "No tracking" nil)
12454 (const :tag "Track with ORDERED tag" t)
12455 (string :tag "Use other tag")))
12457 (defun org-toggle-ordered-property ()
12458 "Toggle the ORDERED property of the current entry.
12459 For better visibility, you can track the value of this property with a tag.
12460 See variable `org-track-ordered-property-with-tag'."
12461 (interactive)
12462 (let* ((t1 org-track-ordered-property-with-tag)
12463 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12464 (save-excursion
12465 (org-back-to-heading)
12466 (if (org-entry-get nil "ORDERED")
12467 (progn
12468 (org-delete-property "ORDERED" "PROPERTIES")
12469 (and tag (org-toggle-tag tag 'off))
12470 (message "Subtasks can be completed in arbitrary order"))
12471 (org-entry-put nil "ORDERED" "t")
12472 (and tag (org-toggle-tag tag 'on))
12473 (message "Subtasks must be completed in sequence")))))
12475 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12476 (defun org-block-todo-from-checkboxes (change-plist)
12477 "Block turning an entry into a TODO, using checkboxes.
12478 This checks whether the current task should be blocked from state
12479 changes because there are unchecked boxes in this entry."
12480 (if (not org-enforce-todo-checkbox-dependencies)
12481 t ; if locally turned off don't block
12482 (catch 'dont-block
12483 ;; If this is not a todo state change, or if this entry is already DONE,
12484 ;; do not block
12485 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12486 (member (plist-get change-plist :from)
12487 (cons 'done org-done-keywords))
12488 (member (plist-get change-plist :to)
12489 (cons 'todo org-not-done-keywords))
12490 (not (plist-get change-plist :to)))
12491 (throw 'dont-block t))
12492 ;; If this task has checkboxes that are not checked, it's blocked
12493 (save-excursion
12494 (org-back-to-heading t)
12495 (let ((beg (point)) end)
12496 (outline-next-heading)
12497 (setq end (point))
12498 (goto-char beg)
12499 (if (org-list-search-forward
12500 (concat (org-item-beginning-re)
12501 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12502 "\\[[- ]\\]")
12503 end t)
12504 (progn
12505 (if (boundp 'org-blocked-by-checkboxes)
12506 (setq org-blocked-by-checkboxes t))
12507 (throw 'dont-block nil)))))
12508 t))) ; do not block
12510 (defun org-entry-blocked-p ()
12511 "Is the current entry blocked?"
12512 (org-with-silent-modifications
12513 (if (org-entry-get nil "NOBLOCKING")
12514 nil ;; Never block this entry
12515 (not (run-hook-with-args-until-failure
12516 'org-blocker-hook
12517 (list :type 'todo-state-change
12518 :position (point)
12519 :from 'todo
12520 :to 'done))))))
12522 (defun org-update-statistics-cookies (all)
12523 "Update the statistics cookie, either from TODO or from checkboxes.
12524 This should be called with the cursor in a line with a statistics cookie."
12525 (interactive "P")
12526 (if all
12527 (progn
12528 (org-update-checkbox-count 'all)
12529 (org-map-entries 'org-update-parent-todo-statistics))
12530 (if (not (org-at-heading-p))
12531 (org-update-checkbox-count)
12532 (let ((pos (point-marker))
12533 end l1 l2)
12534 (ignore-errors (org-back-to-heading t))
12535 (if (not (org-at-heading-p))
12536 (org-update-checkbox-count)
12537 (setq l1 (org-outline-level))
12538 (setq end (save-excursion
12539 (outline-next-heading)
12540 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12541 (point)))
12542 (if (and (save-excursion
12543 (re-search-forward
12544 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12545 (not (save-excursion (re-search-forward
12546 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12547 (org-update-checkbox-count)
12548 (if (and l2 (> l2 l1))
12549 (progn
12550 (goto-char end)
12551 (org-update-parent-todo-statistics))
12552 (goto-char pos)
12553 (beginning-of-line 1)
12554 (while (re-search-forward
12555 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12556 (point-at-eol) t)
12557 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12558 (goto-char pos)
12559 (move-marker pos nil)))))
12561 (defvar org-entry-property-inherited-from) ;; defined below
12562 (defun org-update-parent-todo-statistics ()
12563 "Update any statistics cookie in the parent of the current headline.
12564 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12565 the entire subtree and this will travel up the hierarchy and update
12566 statistics everywhere."
12567 (let* ((prop (save-excursion (org-up-heading-safe)
12568 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12569 (recursive (or (not org-hierarchical-todo-statistics)
12570 (and prop (string-match "\\<recursive\\>" prop))))
12571 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12573 (first t)
12574 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12575 level ltoggle l1 new ndel
12576 (cnt-all 0) (cnt-done 0) is-percent kwd
12577 checkbox-beg ov ovs ove cookie-present)
12578 (catch 'exit
12579 (save-excursion
12580 (beginning-of-line 1)
12581 (setq ltoggle (funcall outline-level))
12582 ;; Three situations are to consider:
12584 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12585 ;; to the top-level ancestor on the headline;
12587 ;; 2. If parent has "recursive" property, repeat up to the
12588 ;; headline setting that property, taking inheritance into
12589 ;; account;
12591 ;; 3. Else, move up to direct parent and proceed only once.
12592 (while (and (setq level (org-up-heading-safe))
12593 (or recursive first)
12594 (>= (point) lim))
12595 (setq first nil cookie-present nil)
12596 (unless (and level
12597 (not (string-match
12598 "\\<checkbox\\>"
12599 (downcase (or (org-entry-get nil "COOKIE_DATA")
12600 "")))))
12601 (throw 'exit nil))
12602 (while (re-search-forward box-re (point-at-eol) t)
12603 (setq cnt-all 0 cnt-done 0 cookie-present t)
12604 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12605 (save-match-data
12606 (unless (outline-next-heading) (throw 'exit nil))
12607 (while (and (looking-at org-complex-heading-regexp)
12608 (> (setq l1 (length (match-string 1))) level))
12609 (setq kwd (and (or recursive (= l1 ltoggle))
12610 (match-string 2)))
12611 (if (or (eq org-provide-todo-statistics 'all-headlines)
12612 (and (listp org-provide-todo-statistics)
12613 (or (member kwd org-provide-todo-statistics)
12614 (member kwd org-done-keywords))))
12615 (setq cnt-all (1+ cnt-all))
12616 (if (eq org-provide-todo-statistics t)
12617 (and kwd (setq cnt-all (1+ cnt-all)))))
12618 (and (member kwd org-done-keywords)
12619 (setq cnt-done (1+ cnt-done)))
12620 (outline-next-heading)))
12621 (setq new
12622 (if is-percent
12623 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12624 (format "[%d/%d]" cnt-done cnt-all))
12625 ndel (- (match-end 0) checkbox-beg))
12626 ;; handle overlays when updating cookie from column view
12627 (when (setq ov (car (overlays-at checkbox-beg)))
12628 (setq ovs (overlay-start ov) ove (overlay-end ov))
12629 (delete-overlay ov))
12630 (goto-char checkbox-beg)
12631 (insert new)
12632 (delete-region (point) (+ (point) ndel))
12633 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12634 (when ov (move-overlay ov ovs ove)))
12635 (when cookie-present
12636 (run-hook-with-args 'org-after-todo-statistics-hook
12637 cnt-done (- cnt-all cnt-done))))))
12638 (run-hooks 'org-todo-statistics-hook)))
12640 (defvar org-after-todo-statistics-hook nil
12641 "Hook that is called after a TODO statistics cookie has been updated.
12642 Each function is called with two arguments: the number of not-done entries
12643 and the number of done entries.
12645 For example, the following function, when added to this hook, will switch
12646 an entry to DONE when all children are done, and back to TODO when new
12647 entries are set to a TODO status. Note that this hook is only called
12648 when there is a statistics cookie in the headline!
12650 (defun org-summary-todo (n-done n-not-done)
12651 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12652 (let (org-log-done org-log-states) ; turn off logging
12653 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12656 (defvar org-todo-statistics-hook nil
12657 "Hook that is run whenever Org thinks TODO statistics should be updated.
12658 This hook runs even if there is no statistics cookie present, in which case
12659 `org-after-todo-statistics-hook' would not run.")
12661 (defun org-todo-trigger-tag-changes (state)
12662 "Apply the changes defined in `org-todo-state-tags-triggers'."
12663 (let ((l org-todo-state-tags-triggers)
12664 changes)
12665 (when (or (not state) (equal state ""))
12666 (setq changes (append changes (cdr (assoc "" l)))))
12667 (when (and (stringp state) (> (length state) 0))
12668 (setq changes (append changes (cdr (assoc state l)))))
12669 (when (member state org-not-done-keywords)
12670 (setq changes (append changes (cdr (assoc 'todo l)))))
12671 (when (member state org-done-keywords)
12672 (setq changes (append changes (cdr (assoc 'done l)))))
12673 (dolist (c changes)
12674 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12676 (defun org-local-logging (value)
12677 "Get logging settings from a property VALUE."
12678 (let* (words w a)
12679 ;; directly set the variables, they are already local.
12680 (setq org-log-done nil
12681 org-log-repeat nil
12682 org-todo-log-states nil)
12683 (setq words (org-split-string value))
12684 (while (setq w (pop words))
12685 (cond
12686 ((setq a (assoc w org-startup-options))
12687 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12688 (set (nth 1 a) (nth 2 a))))
12689 ((setq a (org-extract-log-state-settings w))
12690 (and (member (car a) org-todo-keywords-1)
12691 (push a org-todo-log-states)))))))
12693 (defun org-get-todo-sequence-head (kwd)
12694 "Return the head of the TODO sequence to which KWD belongs.
12695 If KWD is not set, check if there is a text property remembering the
12696 right sequence."
12697 (let (p)
12698 (cond
12699 ((not kwd)
12700 (or (get-text-property (point-at-bol) 'org-todo-head)
12701 (progn
12702 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12703 nil (point-at-eol)))
12704 (get-text-property p 'org-todo-head))))
12705 ((not (member kwd org-todo-keywords-1))
12706 (car org-todo-keywords-1))
12707 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12709 (defun org-fast-todo-selection ()
12710 "Fast TODO keyword selection with single keys.
12711 Returns the new TODO keyword, or nil if no state change should occur."
12712 (let* ((fulltable org-todo-key-alist)
12713 (done-keywords org-done-keywords) ;; needed for the faces.
12714 (maxlen (apply 'max (mapcar
12715 (lambda (x)
12716 (if (stringp (car x)) (string-width (car x)) 0))
12717 fulltable)))
12718 (expert nil)
12719 (fwidth (+ maxlen 3 1 3))
12720 (ncol (/ (- (window-width) 4) fwidth))
12721 tg cnt e c tbl
12722 groups ingroup)
12723 (save-excursion
12724 (save-window-excursion
12725 (if expert
12726 (set-buffer (get-buffer-create " *Org todo*"))
12727 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12728 (erase-buffer)
12729 (org-set-local 'org-done-keywords done-keywords)
12730 (setq tbl fulltable cnt 0)
12731 (while (setq e (pop tbl))
12732 (cond
12733 ((equal e '(:startgroup))
12734 (push '() groups) (setq ingroup t)
12735 (when (not (= cnt 0))
12736 (setq cnt 0)
12737 (insert "\n"))
12738 (insert "{ "))
12739 ((equal e '(:endgroup))
12740 (setq ingroup nil cnt 0)
12741 (insert "}\n"))
12742 ((equal e '(:newline))
12743 (when (not (= cnt 0))
12744 (setq cnt 0)
12745 (insert "\n")
12746 (setq e (car tbl))
12747 (while (equal (car tbl) '(:newline))
12748 (insert "\n")
12749 (setq tbl (cdr tbl)))))
12751 (setq tg (car e) c (cdr e))
12752 (if ingroup (push tg (car groups)))
12753 (setq tg (org-add-props tg nil 'face
12754 (org-get-todo-face tg)))
12755 (if (and (= cnt 0) (not ingroup)) (insert " "))
12756 (insert "[" c "] " tg (make-string
12757 (- fwidth 4 (length tg)) ?\ ))
12758 (when (= (setq cnt (1+ cnt)) ncol)
12759 (insert "\n")
12760 (if ingroup (insert " "))
12761 (setq cnt 0)))))
12762 (insert "\n")
12763 (goto-char (point-min))
12764 (if (not expert) (org-fit-window-to-buffer))
12765 (message "[a-z..]:Set [SPC]:clear")
12766 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12767 (cond
12768 ((or (= c ?\C-g)
12769 (and (= c ?q) (not (rassoc c fulltable))))
12770 (setq quit-flag t))
12771 ((= c ?\ ) nil)
12772 ((setq e (rassoc c fulltable) tg (car e))
12774 (t (setq quit-flag t)))))))
12776 (defun org-entry-is-todo-p ()
12777 (member (org-get-todo-state) org-not-done-keywords))
12779 (defun org-entry-is-done-p ()
12780 (member (org-get-todo-state) org-done-keywords))
12782 (defun org-get-todo-state ()
12783 "Return the TODO keyword of the current subtree."
12784 (save-excursion
12785 (org-back-to-heading t)
12786 (and (looking-at org-todo-line-regexp)
12787 (match-end 2)
12788 (match-string 2))))
12790 (defun org-at-date-range-p (&optional inactive-ok)
12791 "Is the cursor inside a date range?"
12792 (interactive)
12793 (save-excursion
12794 (catch 'exit
12795 (let ((pos (point)))
12796 (skip-chars-backward "^[<\r\n")
12797 (skip-chars-backward "<[")
12798 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12799 (>= (match-end 0) pos)
12800 (throw 'exit t))
12801 (skip-chars-backward "^<[\r\n")
12802 (skip-chars-backward "<[")
12803 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12804 (>= (match-end 0) pos)
12805 (throw 'exit t)))
12806 nil)))
12808 (defun org-get-repeat (&optional tagline)
12809 "Check if there is a deadline/schedule with repeater in this entry."
12810 (save-match-data
12811 (save-excursion
12812 (org-back-to-heading t)
12813 (and (re-search-forward (if tagline
12814 (concat tagline "\\s-*" org-repeat-re)
12815 org-repeat-re)
12816 (org-entry-end-position) t)
12817 (match-string-no-properties 1)))))
12819 (defvar org-last-changed-timestamp)
12820 (defvar org-last-inserted-timestamp)
12821 (defvar org-log-post-message)
12822 (defvar org-log-note-purpose)
12823 (defvar org-log-note-how)
12824 (defvar org-log-note-extra)
12825 (defun org-auto-repeat-maybe (done-word)
12826 "Check if the current headline contains a repeated deadline/schedule.
12827 If yes, set TODO state back to what it was and change the base date
12828 of repeating deadline/scheduled time stamps to new date.
12829 This function is run automatically after each state change to a DONE state."
12830 ;; last-state is dynamically scoped into this function
12831 (let* ((repeat (org-get-repeat))
12832 (aa (assoc org-last-state org-todo-kwd-alist))
12833 (interpret (nth 1 aa))
12834 (head (nth 2 aa))
12835 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12836 (msg "Entry repeats: ")
12837 (org-log-done nil)
12838 (org-todo-log-states nil)
12839 re type n what ts time to-state)
12840 (when repeat
12841 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12842 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12843 org-todo-repeat-to-state))
12844 (unless (and to-state (member to-state org-todo-keywords-1))
12845 (setq to-state (if (eq interpret 'type) org-last-state head)))
12846 (org-todo to-state)
12847 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12848 (org-entry-put nil "LAST_REPEAT" (format-time-string
12849 (org-time-stamp-format t t))))
12850 (when org-log-repeat
12851 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12852 (memq 'org-add-log-note post-command-hook))
12853 ;; OK, we are already setup for some record
12854 (if (eq org-log-repeat 'note)
12855 ;; make sure we take a note, not only a time stamp
12856 (setq org-log-note-how 'note))
12857 ;; Set up for taking a record
12858 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12859 org-last-state
12860 'findpos org-log-repeat)))
12861 (org-back-to-heading t)
12862 (org-add-planning-info nil nil 'closed)
12863 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12864 org-deadline-time-regexp "\\)\\|\\("
12865 org-ts-regexp "\\)"))
12866 (while (re-search-forward
12867 re (save-excursion (outline-next-heading) (point)) t)
12868 (setq type (if (match-end 1) org-scheduled-string
12869 (if (match-end 3) org-deadline-string "Plain:"))
12870 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12871 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12872 (setq n (string-to-number (match-string 2 ts))
12873 what (match-string 3 ts))
12874 (if (equal what "w") (setq n (* n 7) what "d"))
12875 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12876 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12877 ;; Preparation, see if we need to modify the start date for the change
12878 (when (match-end 1)
12879 (setq time (save-match-data (org-time-string-to-time ts)))
12880 (cond
12881 ((equal (match-string 1 ts) ".")
12882 ;; Shift starting date to today
12883 (org-timestamp-change
12884 (- (org-today) (time-to-days time))
12885 'day))
12886 ((equal (match-string 1 ts) "+")
12887 (let ((nshiftmax 10) (nshift 0))
12888 (while (or (= nshift 0)
12889 (<= (time-to-days time)
12890 (time-to-days (current-time))))
12891 (when (= (incf nshift) nshiftmax)
12892 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12893 (error "Abort")))
12894 (org-timestamp-change n (cdr (assoc what whata)))
12895 (org-at-timestamp-p t)
12896 (setq ts (match-string 1))
12897 (setq time (save-match-data (org-time-string-to-time ts)))))
12898 (org-timestamp-change (- n) (cdr (assoc what whata)))
12899 ;; rematch, so that we have everything in place for the real shift
12900 (org-at-timestamp-p t)
12901 (setq ts (match-string 1))
12902 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12903 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12904 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12905 (setq org-log-post-message msg)
12906 (message "%s" msg))))
12908 (defun org-show-todo-tree (arg)
12909 "Make a compact tree which shows all headlines marked with TODO.
12910 The tree will show the lines where the regexp matches, and all higher
12911 headlines above the match.
12912 With a \\[universal-argument] prefix, prompt for a regexp to match.
12913 With a numeric prefix N, construct a sparse tree for the Nth element
12914 of `org-todo-keywords-1'."
12915 (interactive "P")
12916 (let ((case-fold-search nil)
12917 (kwd-re
12918 (cond ((null arg) org-not-done-regexp)
12919 ((equal arg '(4))
12920 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12921 (mapcar 'list org-todo-keywords-1))))
12922 (concat "\\("
12923 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12924 "\\)\\>")))
12925 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12926 (regexp-quote (nth (1- (prefix-numeric-value arg))
12927 org-todo-keywords-1)))
12928 (t (user-error "Invalid prefix argument: %s" arg)))))
12929 (message "%d TODO entries found"
12930 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12932 (defun org-deadline (arg &optional time)
12933 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12934 With one universal prefix argument, remove any deadline from the item.
12935 With two universal prefix arguments, prompt for a warning delay.
12936 With argument TIME, set the deadline at the corresponding date. TIME
12937 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12938 (interactive "P")
12939 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12940 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12941 'region-start-level 'region))
12942 org-loop-over-headlines-in-active-region)
12943 (org-map-entries
12944 `(org-deadline ',arg ,time)
12945 org-loop-over-headlines-in-active-region
12946 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12947 (let* ((old-date (org-entry-get nil "DEADLINE"))
12948 (old-date-time (if old-date (org-time-string-to-time old-date)))
12949 (repeater (and old-date
12950 (string-match
12951 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12952 old-date)
12953 (match-string 1 old-date))))
12954 (cond
12955 ((equal arg '(4))
12956 (when (and old-date org-log-redeadline)
12957 (org-add-log-setup 'deldeadline nil old-date 'findpos
12958 org-log-redeadline))
12959 (org-remove-timestamp-with-keyword org-deadline-string)
12960 (message "Item no longer has a deadline."))
12961 ((equal arg '(16))
12962 (save-excursion
12963 (org-back-to-heading t)
12964 (if (re-search-forward
12965 org-deadline-time-regexp
12966 (save-excursion (outline-next-heading) (point)) t)
12967 (let* ((rpl0 (match-string 1))
12968 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12969 (replace-match
12970 (concat org-deadline-string
12971 " <" rpl
12972 (format " -%dd"
12973 (abs
12974 (- (time-to-days
12975 (save-match-data
12976 (org-read-date nil t nil "Warn starting from" old-date-time)))
12977 (time-to-days old-date-time))))
12978 ">") t t))
12979 (user-error "No deadline information to update"))))
12981 (org-add-planning-info 'deadline time 'closed)
12982 (when (and old-date org-log-redeadline
12983 (not (equal old-date
12984 (substring org-last-inserted-timestamp 1 -1))))
12985 (org-add-log-setup 'redeadline nil old-date 'findpos
12986 org-log-redeadline))
12987 (when repeater
12988 (save-excursion
12989 (org-back-to-heading t)
12990 (when (re-search-forward (concat org-deadline-string " "
12991 org-last-inserted-timestamp)
12992 (save-excursion
12993 (outline-next-heading) (point)) t)
12994 (goto-char (1- (match-end 0)))
12995 (insert " " repeater)
12996 (setq org-last-inserted-timestamp
12997 (concat (substring org-last-inserted-timestamp 0 -1)
12998 " " repeater
12999 (substring org-last-inserted-timestamp -1))))))
13000 (message "Deadline on %s" org-last-inserted-timestamp))))))
13002 (defun org-schedule (arg &optional time)
13003 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13004 With one universal prefix argument, remove any scheduling date from the item.
13005 With two universal prefix arguments, prompt for a delay cookie.
13006 With argument TIME, scheduled at the corresponding date. TIME can
13007 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13008 (interactive "P")
13009 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13010 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13011 'region-start-level 'region))
13012 org-loop-over-headlines-in-active-region)
13013 (org-map-entries
13014 `(org-schedule ',arg ,time)
13015 org-loop-over-headlines-in-active-region
13016 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13017 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13018 (old-date-time (if old-date (org-time-string-to-time old-date)))
13019 (repeater (and old-date
13020 (string-match
13021 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13022 old-date)
13023 (match-string 1 old-date))))
13024 (cond
13025 ((equal arg '(4))
13026 (progn
13027 (when (and old-date org-log-reschedule)
13028 (org-add-log-setup 'delschedule nil old-date 'findpos
13029 org-log-reschedule))
13030 (org-remove-timestamp-with-keyword org-scheduled-string)
13031 (message "Item is no longer scheduled.")))
13032 ((equal arg '(16))
13033 (save-excursion
13034 (org-back-to-heading t)
13035 (if (re-search-forward
13036 org-scheduled-time-regexp
13037 (save-excursion (outline-next-heading) (point)) t)
13038 (let* ((rpl0 (match-string 1))
13039 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13040 (replace-match
13041 (concat org-scheduled-string
13042 " <" rpl
13043 (format " -%dd"
13044 (abs
13045 (- (time-to-days
13046 (save-match-data
13047 (org-read-date nil t nil "Delay until" old-date-time)))
13048 (time-to-days old-date-time))))
13049 ">") t t))
13050 (user-error "No scheduled information to update"))))
13052 (org-add-planning-info 'scheduled time 'closed)
13053 (when (and old-date org-log-reschedule
13054 (not (equal old-date
13055 (substring org-last-inserted-timestamp 1 -1))))
13056 (org-add-log-setup 'reschedule nil old-date 'findpos
13057 org-log-reschedule))
13058 (when repeater
13059 (save-excursion
13060 (org-back-to-heading t)
13061 (when (re-search-forward (concat org-scheduled-string " "
13062 org-last-inserted-timestamp)
13063 (save-excursion
13064 (outline-next-heading) (point)) t)
13065 (goto-char (1- (match-end 0)))
13066 (insert " " repeater)
13067 (setq org-last-inserted-timestamp
13068 (concat (substring org-last-inserted-timestamp 0 -1)
13069 " " repeater
13070 (substring org-last-inserted-timestamp -1))))))
13071 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13073 (defun org-get-scheduled-time (pom &optional inherit)
13074 "Get the scheduled time as a time tuple, of a format suitable
13075 for calling org-schedule with, or if there is no scheduling,
13076 returns nil."
13077 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13078 (when time
13079 (apply 'encode-time (org-parse-time-string time)))))
13081 (defun org-get-deadline-time (pom &optional inherit)
13082 "Get the deadline as a time tuple, of a format suitable for
13083 calling org-deadline with, or if there is no scheduling, returns
13084 nil."
13085 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13086 (when time
13087 (apply 'encode-time (org-parse-time-string time)))))
13089 (defun org-remove-timestamp-with-keyword (keyword)
13090 "Remove all time stamps with KEYWORD in the current entry."
13091 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13092 beg)
13093 (save-excursion
13094 (org-back-to-heading t)
13095 (setq beg (point))
13096 (outline-next-heading)
13097 (while (re-search-backward re beg t)
13098 (replace-match "")
13099 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13100 (equal (char-before) ?\ ))
13101 (backward-delete-char 1)
13102 (if (string-match "^[ \t]*$" (buffer-substring
13103 (point-at-bol) (point-at-eol)))
13104 (delete-region (point-at-bol)
13105 (min (point-max) (1+ (point-at-eol))))))))))
13107 (defvar org-time-was-given) ; dynamically scoped parameter
13108 (defvar org-end-time-was-given) ; dynamically scoped parameter
13110 (defun org-add-planning-info (what &optional time &rest remove)
13111 "Insert new timestamp with keyword in the line directly after the headline.
13112 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13113 If non is given, the user is prompted for a date.
13114 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13115 be removed."
13116 (interactive)
13117 (let (org-time-was-given org-end-time-was-given ts
13118 end default-time default-input)
13120 (catch 'exit
13121 (when (and (memq what '(scheduled deadline))
13122 (or (not time)
13123 (and (stringp time)
13124 (string-match "^[-+]+[0-9]" time))))
13125 ;; Try to get a default date/time from existing timestamp
13126 (save-excursion
13127 (org-back-to-heading t)
13128 (setq end (save-excursion (outline-next-heading) (point)))
13129 (when (re-search-forward (if (eq what 'scheduled)
13130 org-scheduled-time-regexp
13131 org-deadline-time-regexp)
13132 end t)
13133 (setq ts (match-string 1)
13134 default-time
13135 (apply 'encode-time (org-parse-time-string ts))
13136 default-input (and ts (org-get-compact-tod ts))))))
13137 (when what
13138 (setq time
13139 (if (stringp time)
13140 ;; This is a string (relative or absolute), set proper date
13141 (apply 'encode-time
13142 (org-read-date-analyze
13143 time default-time (decode-time default-time)))
13144 ;; If necessary, get the time from the user
13145 (or time (org-read-date nil 'to-time nil nil
13146 default-time default-input)))))
13148 (when (and org-insert-labeled-timestamps-at-point
13149 (member what '(scheduled deadline)))
13150 (insert
13151 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13152 (org-insert-time-stamp time org-time-was-given
13153 nil nil nil (list org-end-time-was-given))
13154 (setq what nil))
13155 (save-excursion
13156 (save-restriction
13157 (let (col list elt ts buffer-invisibility-spec)
13158 (org-back-to-heading t)
13159 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13160 (goto-char (match-end 1))
13161 (setq col (current-column))
13162 (goto-char (match-end 0))
13163 (if (eobp) (insert "\n") (forward-char 1))
13164 (when (and (not what)
13165 (not (looking-at
13166 (concat "[ \t]*"
13167 org-keyword-time-not-clock-regexp))))
13168 ;; Nothing to add, nothing to remove...... :-)
13169 (throw 'exit nil))
13170 (if (and (not (looking-at org-outline-regexp))
13171 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13172 "[^\r\n]*"))
13173 (not (equal (match-string 1) org-clock-string)))
13174 (narrow-to-region (match-beginning 0) (match-end 0))
13175 (insert-before-markers "\n")
13176 (backward-char 1)
13177 (narrow-to-region (point) (point))
13178 (and org-adapt-indentation (org-indent-to-column col)))
13179 ;; Check if we have to remove something.
13180 (setq list (cons what remove))
13181 (while list
13182 (setq elt (pop list))
13183 (when (or (and (eq elt 'scheduled)
13184 (re-search-forward org-scheduled-time-regexp nil t))
13185 (and (eq elt 'deadline)
13186 (re-search-forward org-deadline-time-regexp nil t))
13187 (and (eq elt 'closed)
13188 (re-search-forward org-closed-time-regexp nil t)))
13189 (replace-match "")
13190 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13191 (and (looking-at "[ \t]+") (replace-match ""))
13192 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13193 (when what
13194 (insert
13195 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13196 (cond ((eq what 'scheduled) org-scheduled-string)
13197 ((eq what 'deadline) org-deadline-string)
13198 ((eq what 'closed) org-closed-string))
13199 " ")
13200 (setq ts (org-insert-time-stamp
13201 time
13202 (or org-time-was-given
13203 (and (eq what 'closed) org-log-done-with-time))
13204 (eq what 'closed)
13205 nil nil (list org-end-time-was-given)))
13206 (insert
13207 (if (not (or (bolp) (eq (char-before) ?\ )
13208 (memq (char-after) '(32 10))
13209 (eobp))) " " ""))
13210 (end-of-line 1))
13211 (goto-char (point-min))
13212 (widen)
13213 (if (and (looking-at "[ \t]*\n")
13214 (equal (char-before) ?\n))
13215 (delete-region (1- (point)) (point-at-eol)))
13216 ts))))))
13218 (defvar org-log-note-marker (make-marker))
13219 (defvar org-log-note-purpose nil)
13220 (defvar org-log-note-state nil)
13221 (defvar org-log-note-previous-state nil)
13222 (defvar org-log-note-how nil)
13223 (defvar org-log-note-extra nil)
13224 (defvar org-log-note-window-configuration nil)
13225 (defvar org-log-note-return-to (make-marker))
13226 (defvar org-log-note-effective-time nil
13227 "Remembered current time so that dynamically scoped
13228 `org-extend-today-until' affects tha timestamps in state change
13229 log")
13231 (defvar org-log-post-message nil
13232 "Message to be displayed after a log note has been stored.
13233 The auto-repeater uses this.")
13235 (defun org-add-note ()
13236 "Add a note to the current entry.
13237 This is done in the same way as adding a state change note."
13238 (interactive)
13239 (org-add-log-setup 'note nil nil 'findpos nil))
13241 (defvar org-property-end-re)
13242 (defun org-add-log-setup (&optional purpose state prev-state
13243 findpos how extra)
13244 "Set up the post command hook to take a note.
13245 If this is about to TODO state change, the new state is expected in STATE.
13246 When FINDPOS is non-nil, find the correct position for the note in
13247 the current entry. If not, assume that it can be inserted at point.
13248 HOW is an indicator what kind of note should be created.
13249 EXTRA is additional text that will be inserted into the notes buffer."
13250 (let* ((org-log-into-drawer (org-log-into-drawer))
13251 (drawer (cond ((stringp org-log-into-drawer)
13252 org-log-into-drawer)
13253 (org-log-into-drawer "LOGBOOK"))))
13254 (save-restriction
13255 (save-excursion
13256 (when findpos
13257 (org-back-to-heading t)
13258 (narrow-to-region (point) (save-excursion
13259 (outline-next-heading) (point)))
13260 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13261 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13262 "[^\r\n]*\\)?"))
13263 (goto-char (match-end 0))
13264 (cond
13265 (drawer
13266 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13267 nil t)
13268 (progn
13269 (goto-char (match-end 0))
13270 (or org-log-states-order-reversed
13271 (and (re-search-forward org-property-end-re nil t)
13272 (goto-char (1- (match-beginning 0))))))
13273 (insert "\n:" drawer ":\n:END:")
13274 (beginning-of-line 0)
13275 (org-indent-line)
13276 (beginning-of-line 2)
13277 (org-indent-line)
13278 (end-of-line 0)))
13279 ((and org-log-state-notes-insert-after-drawers
13280 (save-excursion
13281 (forward-line) (looking-at org-drawer-regexp)))
13282 (forward-line)
13283 (while (looking-at org-drawer-regexp)
13284 (goto-char (match-end 0))
13285 (re-search-forward org-property-end-re (point-max) t)
13286 (forward-line))
13287 (forward-line -1)))
13288 (unless org-log-states-order-reversed
13289 (and (= (char-after) ?\n) (forward-char 1))
13290 (org-skip-over-state-notes)
13291 (skip-chars-backward " \t\n\r")))
13292 (move-marker org-log-note-marker (point))
13293 (setq org-log-note-purpose purpose
13294 org-log-note-state state
13295 org-log-note-previous-state prev-state
13296 org-log-note-how how
13297 org-log-note-extra extra
13298 org-log-note-effective-time (org-current-effective-time))
13299 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13301 (defun org-skip-over-state-notes ()
13302 "Skip past the list of State notes in an entry."
13303 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13304 (when (ignore-errors (goto-char (org-in-item-p)))
13305 (let* ((struct (org-list-struct))
13306 (prevs (org-list-prevs-alist struct)))
13307 (while (looking-at "[ \t]*- State")
13308 (goto-char (or (org-list-get-next-item (point) struct prevs)
13309 (org-list-get-item-end (point) struct)))))))
13311 (defun org-add-log-note (&optional purpose)
13312 "Pop up a window for taking a note, and add this note later at point."
13313 (remove-hook 'post-command-hook 'org-add-log-note)
13314 (setq org-log-note-window-configuration (current-window-configuration))
13315 (delete-other-windows)
13316 (move-marker org-log-note-return-to (point))
13317 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13318 (goto-char org-log-note-marker)
13319 (org-switch-to-buffer-other-window "*Org Note*")
13320 (erase-buffer)
13321 (if (memq org-log-note-how '(time state))
13322 (let (current-prefix-arg) (org-store-log-note))
13323 (let ((org-inhibit-startup t)) (org-mode))
13324 (insert (format "# Insert note for %s.
13325 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13326 (cond
13327 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13328 ((eq org-log-note-purpose 'done) "closed todo item")
13329 ((eq org-log-note-purpose 'state)
13330 (format "state change from \"%s\" to \"%s\""
13331 (or org-log-note-previous-state "")
13332 (or org-log-note-state "")))
13333 ((eq org-log-note-purpose 'reschedule)
13334 "rescheduling")
13335 ((eq org-log-note-purpose 'delschedule)
13336 "no longer scheduled")
13337 ((eq org-log-note-purpose 'redeadline)
13338 "changing deadline")
13339 ((eq org-log-note-purpose 'deldeadline)
13340 "removing deadline")
13341 ((eq org-log-note-purpose 'refile)
13342 "refiling")
13343 ((eq org-log-note-purpose 'note)
13344 "this entry")
13345 (t (error "This should not happen")))))
13346 (if org-log-note-extra (insert org-log-note-extra))
13347 (org-set-local 'org-finish-function 'org-store-log-note)
13348 (run-hooks 'org-log-buffer-setup-hook)))
13350 (defvar org-note-abort nil) ; dynamically scoped
13351 (defun org-store-log-note ()
13352 "Finish taking a log note, and insert it to where it belongs."
13353 (let ((txt (buffer-string)))
13354 (kill-buffer (current-buffer))
13355 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13356 lines ind bul)
13357 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13358 (setq txt (replace-match "" t t txt)))
13359 (if (string-match "\\s-+\\'" txt)
13360 (setq txt (replace-match "" t t txt)))
13361 (setq lines (org-split-string txt "\n"))
13362 (when (and note (string-match "\\S-" note))
13363 (setq note
13364 (org-replace-escapes
13365 note
13366 (list (cons "%u" (user-login-name))
13367 (cons "%U" user-full-name)
13368 (cons "%t" (format-time-string
13369 (org-time-stamp-format 'long 'inactive)
13370 org-log-note-effective-time))
13371 (cons "%T" (format-time-string
13372 (org-time-stamp-format 'long nil)
13373 org-log-note-effective-time))
13374 (cons "%d" (format-time-string
13375 (org-time-stamp-format nil 'inactive)
13376 org-log-note-effective-time))
13377 (cons "%D" (format-time-string
13378 (org-time-stamp-format nil nil)
13379 org-log-note-effective-time))
13380 (cons "%s" (if org-log-note-state
13381 (concat "\"" org-log-note-state "\"")
13382 ""))
13383 (cons "%S" (if org-log-note-previous-state
13384 (concat "\"" org-log-note-previous-state "\"")
13385 "\"\"")))))
13386 (if lines (setq note (concat note " \\\\")))
13387 (push note lines))
13388 (when (or current-prefix-arg org-note-abort)
13389 (when org-log-into-drawer
13390 (org-remove-empty-drawer-at
13391 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
13392 org-log-note-marker))
13393 (setq lines nil))
13394 (when lines
13395 (with-current-buffer (marker-buffer org-log-note-marker)
13396 (save-excursion
13397 (goto-char org-log-note-marker)
13398 (move-marker org-log-note-marker nil)
13399 (end-of-line 1)
13400 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13401 (setq ind (save-excursion
13402 (if (ignore-errors (goto-char (org-in-item-p)))
13403 (let ((struct (org-list-struct)))
13404 (org-list-get-ind
13405 (org-list-get-top-point struct) struct))
13406 (skip-chars-backward " \r\t\n")
13407 (cond
13408 ((and (org-at-heading-p)
13409 org-adapt-indentation)
13410 (1+ (org-current-level)))
13411 ((org-at-heading-p) 0)
13412 (t (org-get-indentation))))))
13413 (setq bul (org-list-bullet-string "-"))
13414 (org-indent-line-to ind)
13415 (insert bul (pop lines))
13416 (let ((ind-body (+ (length bul) ind)))
13417 (while lines
13418 (insert "\n")
13419 (org-indent-line-to ind-body)
13420 (insert (pop lines))))
13421 (message "Note stored")
13422 (org-back-to-heading t)
13423 (org-cycle-hide-drawers 'children))
13424 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13425 ;; from within `org-add-log-note' because `buffer-undo-list'
13426 ;; is then modified outside of `org-with-remote-undo'.
13427 (when (eq this-command 'org-agenda-todo)
13428 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13429 ;; Don't add undo information when called from `org-agenda-todo'
13430 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13431 (set-window-configuration org-log-note-window-configuration)
13432 (with-current-buffer (marker-buffer org-log-note-return-to)
13433 (goto-char org-log-note-return-to))
13434 (move-marker org-log-note-return-to nil)
13435 (and org-log-post-message (message "%s" org-log-post-message))))
13437 (defun org-remove-empty-drawer-at (drawer pos)
13438 "Remove an empty drawer DRAWER at position POS.
13439 POS may also be a marker."
13440 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13441 (save-excursion
13442 (save-restriction
13443 (widen)
13444 (goto-char pos)
13445 (if (org-in-regexp
13446 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13447 (replace-match ""))))))
13449 (defvar org-ts-type nil)
13450 (defun org-sparse-tree (&optional arg type)
13451 "Create a sparse tree, prompt for the details.
13452 This command can create sparse trees. You first need to select the type
13453 of match used to create the tree:
13455 t Show all TODO entries.
13456 T Show entries with a specific TODO keyword.
13457 m Show entries selected by a tags/property match.
13458 p Enter a property name and its value (both with completion on existing
13459 names/values) and show entries with that property.
13460 r Show entries matching a regular expression (`/' can be used as well).
13461 b Show deadlines and scheduled items before a date.
13462 a Show deadlines and scheduled items after a date.
13463 d Show deadlines due within `org-deadline-warning-days'.
13464 D Show deadlines and scheduled items between a date range."
13465 (interactive "P")
13466 (let (ans kwd value ts-type)
13467 (setq type (or type org-sparse-tree-default-date-type))
13468 (setq org-ts-type type)
13469 (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"
13470 (cond ((eq type 'all) "all timestamps")
13471 ((eq type 'scheduled) "only scheduled")
13472 ((eq type 'deadline) "only deadline")
13473 ((eq type 'active) "only active timestamps")
13474 ((eq type 'inactive) "only inactive timestamps")
13475 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13476 ((eq type 'closed) "with a closed time-stamp")
13477 (t "scheduled/deadline")))
13478 (setq ans (read-char-exclusive))
13479 (cond
13480 ((equal ans ?c)
13481 (org-sparse-tree
13482 arg (cadr (member type '(scheduled-or-deadline
13483 all scheduled deadline active inactive closed)))))
13484 ((equal ans ?d)
13485 (call-interactively 'org-check-deadlines))
13486 ((equal ans ?b)
13487 (call-interactively 'org-check-before-date))
13488 ((equal ans ?a)
13489 (call-interactively 'org-check-after-date))
13490 ((equal ans ?D)
13491 (call-interactively 'org-check-dates-range))
13492 ((equal ans ?t)
13493 (call-interactively 'org-show-todo-tree))
13494 ((equal ans ?T)
13495 (org-show-todo-tree '(4)))
13496 ((member ans '(?T ?m))
13497 (call-interactively 'org-match-sparse-tree))
13498 ((member ans '(?p ?P))
13499 (setq kwd (org-icompleting-read "Property: "
13500 (mapcar 'list (org-buffer-property-keys))))
13501 (setq value (org-icompleting-read "Value: "
13502 (mapcar 'list (org-property-values kwd))))
13503 (unless (string-match "\\`{.*}\\'" value)
13504 (setq value (concat "\"" value "\"")))
13505 (org-match-sparse-tree arg (concat kwd "=" value)))
13506 ((member ans '(?r ?R ?/))
13507 (call-interactively 'org-occur))
13508 (t (user-error "No such sparse tree command \"%c\"" ans)))))
13510 (defvar org-occur-highlights nil
13511 "List of overlays used for occur matches.")
13512 (make-variable-buffer-local 'org-occur-highlights)
13513 (defvar org-occur-parameters nil
13514 "Parameters of the active org-occur calls.
13515 This is a list, each call to org-occur pushes as cons cell,
13516 containing the regular expression and the callback, onto the list.
13517 The list can contain several entries if `org-occur' has been called
13518 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13519 will only contain one set of parameters. When the highlights are
13520 removed (for example with `C-c C-c', or with the next edit (depending
13521 on `org-remove-highlights-with-change'), this variable is emptied
13522 as well.")
13523 (make-variable-buffer-local 'org-occur-parameters)
13525 (defun org-occur (regexp &optional keep-previous callback)
13526 "Make a compact tree which shows all matches of REGEXP.
13527 The tree will show the lines where the regexp matches, and all higher
13528 headlines above the match. It will also show the heading after the match,
13529 to make sure editing the matching entry is easy.
13530 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13531 call to `org-occur' will be kept, to allow stacking of calls to this
13532 command.
13533 If CALLBACK is non-nil, it is a function which is called to confirm
13534 that the match should indeed be shown."
13535 (interactive "sRegexp: \nP")
13536 (when (equal regexp "")
13537 (user-error "Regexp cannot be empty"))
13538 (unless keep-previous
13539 (org-remove-occur-highlights nil nil t))
13540 (push (cons regexp callback) org-occur-parameters)
13541 (let ((cnt 0))
13542 (save-excursion
13543 (goto-char (point-min))
13544 (if (or (not keep-previous) ; do not want to keep
13545 (not org-occur-highlights)) ; no previous matches
13546 ;; hide everything
13547 (org-overview))
13548 (while (re-search-forward regexp nil t)
13549 (when (or (not callback)
13550 (save-match-data (funcall callback)))
13551 (setq cnt (1+ cnt))
13552 (when org-highlight-sparse-tree-matches
13553 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13554 (org-show-context 'occur-tree))))
13555 (when org-remove-highlights-with-change
13556 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13557 nil 'local))
13558 (unless org-sparse-tree-open-archived-trees
13559 (org-hide-archived-subtrees (point-min) (point-max)))
13560 (run-hooks 'org-occur-hook)
13561 (if (org-called-interactively-p 'interactive)
13562 (message "%d match(es) for regexp %s" cnt regexp))
13563 cnt))
13565 (defun org-occur-next-match (&optional n reset)
13566 "Function for `next-error-function' to find sparse tree matches.
13567 N is the number of matches to move, when negative move backwards.
13568 RESET is entirely ignored - this function always goes back to the
13569 starting point when no match is found."
13570 (let* ((limit (if (< n 0) (point-min) (point-max)))
13571 (search-func (if (< n 0)
13572 'previous-single-char-property-change
13573 'next-single-char-property-change))
13574 (n (abs n))
13575 (pos (point))
13577 (catch 'exit
13578 (while (setq p1 (funcall search-func (point) 'org-type))
13579 (when (equal p1 limit)
13580 (goto-char pos)
13581 (error "No more matches"))
13582 (when (equal (get-char-property p1 'org-type) 'org-occur)
13583 (setq n (1- n))
13584 (when (= n 0)
13585 (goto-char p1)
13586 (throw 'exit (point))))
13587 (goto-char p1))
13588 (goto-char p1)
13589 (error "No more matches"))))
13591 (defun org-show-context (&optional key)
13592 "Make sure point and context are visible.
13593 How much context is shown depends upon the variables
13594 `org-show-hierarchy-above', `org-show-following-heading',
13595 `org-show-entry-below' and `org-show-siblings'."
13596 (let ((heading-p (org-at-heading-p t))
13597 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13598 (following-p (org-get-alist-option org-show-following-heading key))
13599 (entry-p (org-get-alist-option org-show-entry-below key))
13600 (siblings-p (org-get-alist-option org-show-siblings key)))
13601 ;; Show heading or entry text
13602 (if (and heading-p (not entry-p))
13603 (org-flag-heading nil) ; only show the heading
13604 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13605 (org-show-hidden-entry))) ; show entire entry
13606 (when following-p
13607 ;; Show next sibling, or heading below text
13608 (save-excursion
13609 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13610 (org-flag-heading nil))))
13611 (when siblings-p (org-show-siblings))
13612 (when hierarchy-p
13613 ;; show all higher headings, possibly with siblings
13614 (save-excursion
13615 (while (and (condition-case nil
13616 (progn (org-up-heading-all 1) t)
13617 (error nil))
13618 (not (bobp)))
13619 (org-flag-heading nil)
13620 (when siblings-p (org-show-siblings)))))
13621 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13623 (defvar org-reveal-start-hook nil
13624 "Hook run before revealing a location.")
13626 (defun org-reveal (&optional siblings)
13627 "Show current entry, hierarchy above it, and the following headline.
13628 This can be used to show a consistent set of context around locations
13629 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13630 not t for the search context.
13632 With optional argument SIBLINGS, on each level of the hierarchy all
13633 siblings are shown. This repairs the tree structure to what it would
13634 look like when opened with hierarchical calls to `org-cycle'.
13635 With double optional argument \\[universal-argument] \\[universal-argument], \
13636 go to the parent and show the
13637 entire tree."
13638 (interactive "P")
13639 (run-hooks 'org-reveal-start-hook)
13640 (let ((org-show-hierarchy-above t)
13641 (org-show-following-heading t)
13642 (org-show-siblings (if siblings t org-show-siblings)))
13643 (org-show-context nil))
13644 (when (equal siblings '(16))
13645 (save-excursion
13646 (when (org-up-heading-safe)
13647 (org-show-subtree)
13648 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13650 (defun org-highlight-new-match (beg end)
13651 "Highlight from BEG to END and mark the highlight is an occur headline."
13652 (let ((ov (make-overlay beg end)))
13653 (overlay-put ov 'face 'secondary-selection)
13654 (overlay-put ov 'org-type 'org-occur)
13655 (push ov org-occur-highlights)))
13657 (defun org-remove-occur-highlights (&optional beg end noremove)
13658 "Remove the occur highlights from the buffer.
13659 BEG and END are ignored. If NOREMOVE is nil, remove this function
13660 from the `before-change-functions' in the current buffer."
13661 (interactive)
13662 (unless org-inhibit-highlight-removal
13663 (mapc 'delete-overlay org-occur-highlights)
13664 (setq org-occur-highlights nil)
13665 (setq org-occur-parameters nil)
13666 (unless noremove
13667 (remove-hook 'before-change-functions
13668 'org-remove-occur-highlights 'local))))
13670 ;;;; Priorities
13672 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13673 "Regular expression matching the priority indicator.")
13675 (defvar org-remove-priority-next-time nil)
13677 (defun org-priority-up ()
13678 "Increase the priority of the current item."
13679 (interactive)
13680 (org-priority 'up))
13682 (defun org-priority-down ()
13683 "Decrease the priority of the current item."
13684 (interactive)
13685 (org-priority 'down))
13687 (defun org-priority (&optional action show)
13688 "Change the priority of an item.
13689 ACTION can be `set', `up', `down', or a character."
13690 (interactive "P")
13691 (if (equal action '(4))
13692 (org-show-priority)
13693 (unless org-enable-priority-commands
13694 (user-error "Priority commands are disabled"))
13695 (setq action (or action 'set))
13696 (let (current new news have remove)
13697 (save-excursion
13698 (org-back-to-heading t)
13699 (if (looking-at org-priority-regexp)
13700 (setq current (string-to-char (match-string 2))
13701 have t))
13702 (cond
13703 ((eq action 'remove)
13704 (setq remove t new ?\ ))
13705 ((or (eq action 'set)
13706 (if (featurep 'xemacs) (characterp action) (integerp action)))
13707 (if (not (eq action 'set))
13708 (setq new action)
13709 (message "Priority %c-%c, SPC to remove: "
13710 org-highest-priority org-lowest-priority)
13711 (save-match-data
13712 (setq new (read-char-exclusive))))
13713 (if (and (= (upcase org-highest-priority) org-highest-priority)
13714 (= (upcase org-lowest-priority) org-lowest-priority))
13715 (setq new (upcase new)))
13716 (cond ((equal new ?\ ) (setq remove t))
13717 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13718 (user-error "Priority must be between `%c' and `%c'"
13719 org-highest-priority org-lowest-priority))))
13720 ((eq action 'up)
13721 (setq new (if have
13722 (1- current) ; normal cycling
13723 ;; last priority was empty
13724 (if (eq last-command this-command)
13725 org-lowest-priority ; wrap around empty to lowest
13726 ;; default
13727 (if org-priority-start-cycle-with-default
13728 org-default-priority
13729 (1- org-default-priority))))))
13730 ((eq action 'down)
13731 (setq new (if have
13732 (1+ current) ; normal cycling
13733 ;; last priority was empty
13734 (if (eq last-command this-command)
13735 org-highest-priority ; wrap around empty to highest
13736 ;; default
13737 (if org-priority-start-cycle-with-default
13738 org-default-priority
13739 (1+ org-default-priority))))))
13740 (t (user-error "Invalid action")))
13741 (if (or (< (upcase new) org-highest-priority)
13742 (> (upcase new) org-lowest-priority))
13743 (if (and (memq action '(up down))
13744 (not have) (not (eq last-command this-command)))
13745 ;; `new' is from default priority
13746 (error
13747 "The default can not be set, see `org-default-priority' why")
13748 ;; normal cycling: `new' is beyond highest/lowest priority
13749 ;; and is wrapped around to the empty priority
13750 (setq remove t)))
13751 (setq news (format "%c" new))
13752 (if have
13753 (if remove
13754 (replace-match "" t t nil 1)
13755 (replace-match news t t nil 2))
13756 (if remove
13757 (user-error "No priority cookie found in line")
13758 (let ((case-fold-search nil))
13759 (looking-at org-todo-line-regexp))
13760 (if (match-end 2)
13761 (progn
13762 (goto-char (match-end 2))
13763 (insert " [#" news "]"))
13764 (goto-char (match-beginning 3))
13765 (insert "[#" news "] "))))
13766 (org-preserve-lc (org-set-tags nil 'align)))
13767 (if remove
13768 (message "Priority removed")
13769 (message "Priority of current item set to %s" news)))))
13771 (defun org-show-priority ()
13772 "Show the priority of the current item.
13773 This priority is composed of the main priority given with the [#A] cookies,
13774 and by additional input from the age of a schedules or deadline entry."
13775 (interactive)
13776 (let ((pri (if (eq major-mode 'org-agenda-mode)
13777 (org-get-at-bol 'priority)
13778 (save-excursion
13779 (save-match-data
13780 (beginning-of-line)
13781 (and (looking-at org-heading-regexp)
13782 (org-get-priority (match-string 0))))))))
13783 (message "Priority is %d" (if pri pri -1000))))
13785 (defun org-get-priority (s)
13786 "Find priority cookie and return priority."
13787 (save-match-data
13788 (if (functionp org-get-priority-function)
13789 (funcall org-get-priority-function)
13790 (if (not (string-match org-priority-regexp s))
13791 (* 1000 (- org-lowest-priority org-default-priority))
13792 (* 1000 (- org-lowest-priority
13793 (string-to-char (match-string 2 s))))))))
13795 ;;;; Tags
13797 (defvar org-agenda-archives-mode)
13798 (defvar org-map-continue-from nil
13799 "Position from where mapping should continue.
13800 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13802 (defvar org-scanner-tags nil
13803 "The current tag list while the tags scanner is running.")
13804 (defvar org-trust-scanner-tags nil
13805 "Should `org-get-tags-at' use the tags for the scanner.
13806 This is for internal dynamical scoping only.
13807 When this is non-nil, the function `org-get-tags-at' will return the value
13808 of `org-scanner-tags' instead of building the list by itself. This
13809 can lead to large speed-ups when the tags scanner is used in a file with
13810 many entries, and when the list of tags is retrieved, for example to
13811 obtain a list of properties. Building the tags list for each entry in such
13812 a file becomes an N^2 operation - but with this variable set, it scales
13813 as N.")
13815 (defun org-scan-tags (action matcher todo-only &optional start-level)
13816 "Sca headline tags with inheritance and produce output ACTION.
13818 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13819 or `agenda' to produce an entry list for an agenda view. It can also be
13820 a Lisp form or a function that should be called at each matched headline, in
13821 this case the return value is a list of all return values from these calls.
13823 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13824 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13825 only lines with a not-done TODO keyword are included in the output.
13826 This should be the same variable that was scoped into
13827 and set by `org-make-tags-matcher' when it constructed MATCHER.
13829 START-LEVEL can be a string with asterisks, reducing the scope to
13830 headlines matching this string."
13831 (require 'org-agenda)
13832 (let* ((re (concat "^"
13833 (if start-level
13834 ;; Get the correct level to match
13835 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13836 org-outline-regexp)
13837 " *\\(\\<\\("
13838 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13839 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13840 (props (list 'face 'default
13841 'done-face 'org-agenda-done
13842 'undone-face 'default
13843 'mouse-face 'highlight
13844 'org-not-done-regexp org-not-done-regexp
13845 'org-todo-regexp org-todo-regexp
13846 'org-complex-heading-regexp org-complex-heading-regexp
13847 'help-echo
13848 (format "mouse-2 or RET jump to org file %s"
13849 (abbreviate-file-name
13850 (or (buffer-file-name (buffer-base-buffer))
13851 (buffer-name (buffer-base-buffer)))))))
13852 (org-map-continue-from nil)
13853 lspos tags tags-list
13854 (tags-alist (list (cons 0 org-file-tags)))
13855 (llast 0) rtn rtn1 level category i txt
13856 todo marker entry priority)
13857 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13858 (setq action (list 'lambda nil action)))
13859 (save-excursion
13860 (goto-char (point-min))
13861 (when (eq action 'sparse-tree)
13862 (org-overview)
13863 (org-remove-occur-highlights))
13864 (while (let (case-fold-search)
13865 (re-search-forward re nil t))
13866 (setq org-map-continue-from nil)
13867 (catch :skip
13868 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13869 tags (if (match-end 4) (org-match-string-no-properties 4)))
13870 (goto-char (setq lspos (match-beginning 0)))
13871 (setq level (org-reduced-level (org-outline-level))
13872 category (org-get-category))
13873 (setq i llast llast level)
13874 ;; remove tag lists from same and sublevels
13875 (while (>= i level)
13876 (when (setq entry (assoc i tags-alist))
13877 (setq tags-alist (delete entry tags-alist)))
13878 (setq i (1- i)))
13879 ;; add the next tags
13880 (when tags
13881 (setq tags (org-split-string tags ":")
13882 tags-alist
13883 (cons (cons level tags) tags-alist)))
13884 ;; compile tags for current headline
13885 (setq tags-list
13886 (if org-use-tag-inheritance
13887 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13888 tags)
13889 org-scanner-tags tags-list)
13890 (when org-use-tag-inheritance
13891 (setcdr (car tags-alist)
13892 (mapcar (lambda (x)
13893 (setq x (copy-sequence x))
13894 (org-add-prop-inherited x))
13895 (cdar tags-alist))))
13896 (when (and tags org-use-tag-inheritance
13897 (or (not (eq t org-use-tag-inheritance))
13898 org-tags-exclude-from-inheritance))
13899 ;; selective inheritance, remove uninherited ones
13900 (setcdr (car tags-alist)
13901 (org-remove-uninherited-tags (cdar tags-alist))))
13902 (when (and
13904 ;; eval matcher only when the todo condition is OK
13905 (and (or (not todo-only) (member todo org-not-done-keywords))
13906 (let ((case-fold-search t) (org-trust-scanner-tags t))
13907 (eval matcher)))
13909 ;; Call the skipper, but return t if it does not skip,
13910 ;; so that the `and' form continues evaluating
13911 (progn
13912 (unless (eq action 'sparse-tree) (org-agenda-skip))
13915 ;; Check if timestamps are deselecting this entry
13916 (or (not todo-only)
13917 (and (member todo org-not-done-keywords)
13918 (or (not org-agenda-tags-todo-honor-ignore-options)
13919 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13921 ;; select this headline
13922 (cond
13923 ((eq action 'sparse-tree)
13924 (and org-highlight-sparse-tree-matches
13925 (org-get-heading) (match-end 0)
13926 (org-highlight-new-match
13927 (match-beginning 1) (match-end 1)))
13928 (org-show-context 'tags-tree))
13929 ((eq action 'agenda)
13930 (setq txt (org-agenda-format-item
13932 (concat
13933 (if (eq org-tags-match-list-sublevels 'indented)
13934 (make-string (1- level) ?.) "")
13935 (org-get-heading))
13936 level category
13937 tags-list)
13938 priority (org-get-priority txt))
13939 (goto-char lspos)
13940 (setq marker (org-agenda-new-marker))
13941 (org-add-props txt props
13942 'org-marker marker 'org-hd-marker marker 'org-category category
13943 'todo-state todo
13944 'priority priority 'type "tagsmatch")
13945 (push txt rtn))
13946 ((functionp action)
13947 (setq org-map-continue-from nil)
13948 (save-excursion
13949 (setq rtn1 (funcall action))
13950 (push rtn1 rtn)))
13951 (t (user-error "Invalid action")))
13953 ;; if we are to skip sublevels, jump to end of subtree
13954 (unless org-tags-match-list-sublevels
13955 (org-end-of-subtree t)
13956 (backward-char 1))))
13957 ;; Get the correct position from where to continue
13958 (if org-map-continue-from
13959 (goto-char org-map-continue-from)
13960 (and (= (point) lspos) (end-of-line 1)))))
13961 (when (and (eq action 'sparse-tree)
13962 (not org-sparse-tree-open-archived-trees))
13963 (org-hide-archived-subtrees (point-min) (point-max)))
13964 (nreverse rtn)))
13966 (defun org-remove-uninherited-tags (tags)
13967 "Remove all tags that are not inherited from the list TAGS."
13968 (cond
13969 ((eq org-use-tag-inheritance t)
13970 (if org-tags-exclude-from-inheritance
13971 (org-delete-all org-tags-exclude-from-inheritance tags)
13972 tags))
13973 ((not org-use-tag-inheritance) nil)
13974 ((stringp org-use-tag-inheritance)
13975 (delq nil (mapcar
13976 (lambda (x)
13977 (if (and (string-match org-use-tag-inheritance x)
13978 (not (member x org-tags-exclude-from-inheritance)))
13979 x nil))
13980 tags)))
13981 ((listp org-use-tag-inheritance)
13982 (delq nil (mapcar
13983 (lambda (x)
13984 (if (member x org-use-tag-inheritance) x nil))
13985 tags)))))
13987 (defun org-match-sparse-tree (&optional todo-only match)
13988 "Create a sparse tree according to tags string MATCH.
13989 MATCH can contain positive and negative selection of tags, like
13990 \"+WORK+URGENT-WITHBOSS\".
13991 If optional argument TODO-ONLY is non-nil, only select lines that are
13992 also TODO lines."
13993 (interactive "P")
13994 (org-agenda-prepare-buffers (list (current-buffer)))
13995 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13997 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13999 (defvar org-cached-props nil)
14000 (defun org-cached-entry-get (pom property)
14001 (if (or (eq t org-use-property-inheritance)
14002 (and (stringp org-use-property-inheritance)
14003 (string-match org-use-property-inheritance property))
14004 (and (listp org-use-property-inheritance)
14005 (member property org-use-property-inheritance)))
14006 ;; Caching is not possible, check it directly
14007 (org-entry-get pom property 'inherit)
14008 ;; Get all properties, so that we can do complicated checks easily
14009 (cdr (assoc property (or org-cached-props
14010 (setq org-cached-props
14011 (org-entry-properties pom)))))))
14013 (defun org-global-tags-completion-table (&optional files)
14014 "Return the list of all tags in all agenda buffer/files.
14015 Optional FILES argument is a list of files which can be used
14016 instead of the agenda files."
14017 (save-excursion
14018 (org-uniquify
14019 (delq nil
14020 (apply 'append
14021 (mapcar
14022 (lambda (file)
14023 (set-buffer (find-file-noselect file))
14024 (append (org-get-buffer-tags)
14025 (mapcar (lambda (x) (if (stringp (car-safe x))
14026 (list (car-safe x)) nil))
14027 org-tag-alist)))
14028 (if (and files (car files))
14029 files
14030 (org-agenda-files))))))))
14032 (defun org-make-tags-matcher (match)
14033 "Create the TAGS/TODO matcher form for the selection string MATCH.
14035 The variable `todo-only' is scoped dynamically into this function.
14036 It will be set to t if the matcher restricts matching to TODO entries,
14037 otherwise will not be touched.
14039 Returns a cons of the selection string MATCH and the constructed
14040 lisp form implementing the matcher. The matcher is to be evaluated
14041 at an Org entry, with point on the headline, and returns t if the
14042 entry matches the selection string MATCH. The returned lisp form
14043 references two variables with information about the entry, which
14044 must be bound around the form's evaluation: todo, the TODO keyword
14045 at the entry (or nil of none); and tags-list, the list of all tags
14046 at the entry including inherited ones. Additionally, the category
14047 of the entry (if any) must be specified as the text property
14048 'org-category on the headline.
14050 See also `org-scan-tags'.
14052 (declare (special todo-only))
14053 (unless (boundp 'todo-only)
14054 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14055 (unless match
14056 ;; Get a new match request, with completion against the global
14057 ;; tags table and the local tags in current buffer
14058 (let ((org-last-tags-completion-table
14059 (org-uniquify
14060 (delq nil (append (org-get-buffer-tags)
14061 (org-global-tags-completion-table))))))
14062 (setq match (org-completing-read-no-i
14063 "Match: " 'org-tags-completion-function nil nil nil
14064 'org-tags-history))))
14066 ;; Parse the string and create a lisp form
14067 (let ((match0 match)
14068 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14069 minus tag mm
14070 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14071 orterms term orlist re-p str-p level-p level-op time-p
14072 prop-p pn pv po gv rest (start 0) (ss 0))
14073 ;; Expand group tags
14074 (setq match (org-tags-expand match))
14076 ;; Check if there is a TODO part of this match, which would be the
14077 ;; part after a "/". TO make sure that this slash is not part of
14078 ;; a property value to be matched against, we also check that there
14079 ;; is no " after that slash.
14080 ;; First, find the last slash
14081 (while (string-match "/+" match ss)
14082 (setq start (match-beginning 0) ss (match-end 0)))
14083 (if (and (string-match "/+" match start)
14084 (not (save-match-data (string-match "\"" match start))))
14085 ;; match contains also a todo-matching request
14086 (progn
14087 (setq tagsmatch (substring match 0 (match-beginning 0))
14088 todomatch (substring match (match-end 0)))
14089 (if (string-match "^!" todomatch)
14090 (setq todo-only t todomatch (substring todomatch 1)))
14091 (if (string-match "^\\s-*$" todomatch)
14092 (setq todomatch nil)))
14093 ;; only matching tags
14094 (setq tagsmatch match todomatch nil))
14096 ;; Make the tags matcher
14097 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14098 (setq tagsmatcher t)
14099 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14100 (while (setq term (pop orterms))
14101 (while (and (equal (substring term -1) "\\") orterms)
14102 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14103 (while (string-match re term)
14104 (setq rest (substring term (match-end 0))
14105 minus (and (match-end 1)
14106 (equal (match-string 1 term) "-"))
14107 tag (save-match-data (replace-regexp-in-string
14108 "\\\\-" "-"
14109 (match-string 2 term)))
14110 re-p (equal (string-to-char tag) ?{)
14111 level-p (match-end 4)
14112 prop-p (match-end 5)
14113 mm (cond
14114 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14115 (level-p
14116 (setq level-op (org-op-to-function (match-string 3 term)))
14117 `(,level-op level ,(string-to-number
14118 (match-string 4 term))))
14119 (prop-p
14120 (setq pn (match-string 5 term)
14121 po (match-string 6 term)
14122 pv (match-string 7 term)
14123 re-p (equal (string-to-char pv) ?{)
14124 str-p (equal (string-to-char pv) ?\")
14125 time-p (save-match-data
14126 (string-match "^\"[[<].*[]>]\"$" pv))
14127 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14128 (if time-p (setq pv (org-matcher-time pv)))
14129 (setq po (org-op-to-function po (if time-p 'time str-p)))
14130 (cond
14131 ((equal pn "CATEGORY")
14132 (setq gv '(get-text-property (point) 'org-category)))
14133 ((equal pn "TODO")
14134 (setq gv 'todo))
14136 (setq gv `(org-cached-entry-get nil ,pn))))
14137 (if re-p
14138 (if (eq po 'org<>)
14139 `(not (string-match ,pv (or ,gv "")))
14140 `(string-match ,pv (or ,gv "")))
14141 (if str-p
14142 `(,po (or ,gv "") ,pv)
14143 `(,po (string-to-number (or ,gv ""))
14144 ,(string-to-number pv) ))))
14145 (t `(member ,tag tags-list)))
14146 mm (if minus (list 'not mm) mm)
14147 term rest)
14148 (push mm tagsmatcher))
14149 (push (if (> (length tagsmatcher) 1)
14150 (cons 'and tagsmatcher)
14151 (car tagsmatcher))
14152 orlist)
14153 (setq tagsmatcher nil))
14154 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14155 (setq tagsmatcher
14156 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14157 ;; Make the todo matcher
14158 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14159 (setq todomatcher t)
14160 (setq orterms (org-split-string todomatch "|") orlist nil)
14161 (while (setq term (pop orterms))
14162 (while (string-match re term)
14163 (setq minus (and (match-end 1)
14164 (equal (match-string 1 term) "-"))
14165 kwd (match-string 2 term)
14166 re-p (equal (string-to-char kwd) ?{)
14167 term (substring term (match-end 0))
14168 mm (if re-p
14169 `(string-match ,(substring kwd 1 -1) todo)
14170 (list 'equal 'todo kwd))
14171 mm (if minus (list 'not mm) mm))
14172 (push mm todomatcher))
14173 (push (if (> (length todomatcher) 1)
14174 (cons 'and todomatcher)
14175 (car todomatcher))
14176 orlist)
14177 (setq todomatcher nil))
14178 (setq todomatcher (if (> (length orlist) 1)
14179 (cons 'or orlist) (car orlist))))
14181 ;; Return the string and lisp forms of the matcher
14182 (setq matcher (if todomatcher
14183 (list 'and tagsmatcher todomatcher)
14184 tagsmatcher))
14185 (when todo-only
14186 (setq matcher (list 'and '(member todo org-not-done-keywords)
14187 matcher)))
14188 (cons match0 matcher)))
14190 (defun org-tags-expand (match &optional single-as-list downcased)
14191 "Expand group tags in MATCH.
14193 This replaces every group tag in MATCH with a regexp tag search.
14194 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14195 will be replaced like this:
14197 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14198 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14199 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14201 Replacing by a regexp preserves the structure of the match.
14202 E.g., this expansion
14204 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14206 will match anything tagged with \"Lab\" and \"Home\", or tagged
14207 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14209 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14210 assumed to be a single group tag, and the function will return
14211 the list of tags in this group.
14213 When DOWNCASE is non-nil, expand downcased TAGS."
14214 (if org-group-tags
14215 (let* ((case-fold-search t)
14216 (stable org-mode-syntax-table)
14217 (tal (or org-tag-groups-alist-for-agenda
14218 org-tag-groups-alist))
14219 (tal (if downcased
14220 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14221 (tml (mapcar 'car tal))
14222 (rtnmatch match) rpl)
14223 ;; @ and _ are allowed as word-components in tags
14224 (modify-syntax-entry ?@ "w" stable)
14225 (modify-syntax-entry ?_ "w" stable)
14226 (while (and tml
14227 (with-syntax-table stable
14228 (string-match
14229 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14230 (regexp-opt tml) "\\>\\)") rtnmatch)))
14231 (let* ((dir (match-string 1 rtnmatch))
14232 (tag (match-string 2 rtnmatch))
14233 (tag (if downcased (downcase tag) tag)))
14234 (setq tml (delete tag tml))
14235 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14236 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14237 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14238 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14239 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14240 (if single-as-list
14241 (or (reverse rpl) (list rtnmatch))
14242 rtnmatch))
14243 (if single-as-list (list (if downcased (downcase match) match))
14244 match)))
14246 (defun org-op-to-function (op &optional stringp)
14247 "Turn an operator into the appropriate function."
14248 (setq op
14249 (cond
14250 ((equal op "<" ) '(< string< org-time<))
14251 ((equal op ">" ) '(> org-string> org-time>))
14252 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14253 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14254 ((member op '("=" "==")) '(= string= org-time=))
14255 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14256 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14258 (defun org<> (a b) (not (= a b)))
14259 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14260 (defun org-string>= (a b) (not (string< a b)))
14261 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14262 (defun org-string<> (a b) (not (string= a b)))
14263 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14264 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14265 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14266 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14267 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14268 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14269 (defun org-2ft (s)
14270 "Convert S to a floating point time.
14271 If S is already a number, just return it. If it is a string, parse
14272 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14273 (cond
14274 ((numberp s) s)
14275 ((stringp s)
14276 (condition-case nil
14277 (float-time (apply 'encode-time (org-parse-time-string s)))
14278 (error 0.)))
14279 (t 0.)))
14281 (defun org-time-today ()
14282 "Time in seconds today at 0:00.
14283 Returns the float number of seconds since the beginning of the
14284 epoch to the beginning of today (00:00)."
14285 (float-time (apply 'encode-time
14286 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14288 (defun org-matcher-time (s)
14289 "Interpret a time comparison value."
14290 (save-match-data
14291 (cond
14292 ((string= s "<now>") (float-time))
14293 ((string= s "<today>") (org-time-today))
14294 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14295 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14296 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14297 (+ (org-time-today)
14298 (* (string-to-number (match-string 1 s))
14299 (cdr (assoc (match-string 2 s)
14300 '(("d" . 86400.0) ("w" . 604800.0)
14301 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14302 (t (org-2ft s)))))
14304 (defun org-match-any-p (re list)
14305 "Does re match any element of list?"
14306 (setq list (mapcar (lambda (x) (string-match re x)) list))
14307 (delq nil list))
14309 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14310 (defvar org-tags-overlay (make-overlay 1 1))
14311 (org-detach-overlay org-tags-overlay)
14313 (defun org-get-local-tags-at (&optional pos)
14314 "Get a list of tags defined in the current headline."
14315 (org-get-tags-at pos 'local))
14317 (defun org-get-local-tags ()
14318 "Get a list of tags defined in the current headline."
14319 (org-get-tags-at nil 'local))
14321 (defun org-get-tags-at (&optional pos local)
14322 "Get a list of all headline tags applicable at POS.
14323 POS defaults to point. If tags are inherited, the list contains
14324 the targets in the same sequence as the headlines appear, i.e.
14325 the tags of the current headline come last.
14326 When LOCAL is non-nil, only return tags from the current headline,
14327 ignore inherited ones."
14328 (interactive)
14329 (if (and org-trust-scanner-tags
14330 (or (not pos) (equal pos (point)))
14331 (not local))
14332 org-scanner-tags
14333 (let (tags ltags lastpos parent)
14334 (save-excursion
14335 (save-restriction
14336 (widen)
14337 (goto-char (or pos (point)))
14338 (save-match-data
14339 (catch 'done
14340 (condition-case nil
14341 (progn
14342 (org-back-to-heading t)
14343 (while (not (equal lastpos (point)))
14344 (setq lastpos (point))
14345 (when (looking-at
14346 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14347 (setq ltags (org-split-string
14348 (org-match-string-no-properties 1) ":"))
14349 (when parent
14350 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14351 (setq tags (append
14352 (if parent
14353 (org-remove-uninherited-tags ltags)
14354 ltags)
14355 tags)))
14356 (or org-use-tag-inheritance (throw 'done t))
14357 (if local (throw 'done t))
14358 (or (org-up-heading-safe) (error nil))
14359 (setq parent t)))
14360 (error nil)))))
14361 (if local
14362 tags
14363 (reverse (delete-dups
14364 (reverse (append
14365 (org-remove-uninherited-tags
14366 org-file-tags) tags)))))))))
14368 (defun org-add-prop-inherited (s)
14369 (add-text-properties 0 (length s) '(inherited t) s)
14372 (defun org-toggle-tag (tag &optional onoff)
14373 "Toggle the tag TAG for the current line.
14374 If ONOFF is `on' or `off', don't toggle but set to this state."
14375 (let (res current)
14376 (save-excursion
14377 (org-back-to-heading t)
14378 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14379 (point-at-eol) t)
14380 (progn
14381 (setq current (match-string 1))
14382 (replace-match ""))
14383 (setq current ""))
14384 (setq current (nreverse (org-split-string current ":")))
14385 (cond
14386 ((eq onoff 'on)
14387 (setq res t)
14388 (or (member tag current) (push tag current)))
14389 ((eq onoff 'off)
14390 (or (not (member tag current)) (setq current (delete tag current))))
14391 (t (if (member tag current)
14392 (setq current (delete tag current))
14393 (setq res t)
14394 (push tag current))))
14395 (end-of-line 1)
14396 (if current
14397 (progn
14398 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14399 (org-set-tags nil t))
14400 (delete-horizontal-space))
14401 (run-hooks 'org-after-tags-change-hook))
14402 res))
14404 (defun org-align-tags-here (to-col)
14405 ;; Assumes that this is a headline
14406 "Align tags on the current headline to TO-COL."
14407 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14408 (beginning-of-line 1)
14409 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14410 (< pos (match-beginning 2)))
14411 (progn
14412 (setq tags-l (- (match-end 2) (match-beginning 2)))
14413 (goto-char (match-beginning 1))
14414 (insert " ")
14415 (delete-region (point) (1+ (match-beginning 2)))
14416 (setq ncol (max (current-column)
14417 (1+ col)
14418 (if (> to-col 0)
14419 to-col
14420 (- (abs to-col) tags-l))))
14421 (setq p (point))
14422 (insert (make-string (- ncol (current-column)) ?\ ))
14423 (setq ncol (current-column))
14424 (when indent-tabs-mode (tabify p (point-at-eol)))
14425 (org-move-to-column (min ncol col)))
14426 (goto-char pos))))
14428 (defun org-set-tags-command (&optional arg just-align)
14429 "Call the set-tags command for the current entry."
14430 (interactive "P")
14431 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14432 (org-set-tags arg just-align)
14433 (save-excursion
14434 (unless (and (org-region-active-p)
14435 org-loop-over-headlines-in-active-region)
14436 (org-back-to-heading t))
14437 (org-set-tags arg just-align))))
14439 (defun org-set-tags-to (data)
14440 "Set the tags of the current entry to DATA, replacing the current tags.
14441 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14442 If DATA is nil or the empty string, any tags will be removed."
14443 (interactive "sTags: ")
14444 (setq data
14445 (cond
14446 ((eq data nil) "")
14447 ((equal data "") "")
14448 ((stringp data)
14449 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14450 ":"))
14451 ((listp data)
14452 (concat ":" (mapconcat 'identity data ":") ":"))))
14453 (when data
14454 (save-excursion
14455 (org-back-to-heading t)
14456 (when (looking-at org-complex-heading-regexp)
14457 (if (match-end 5)
14458 (progn
14459 (goto-char (match-beginning 5))
14460 (insert data)
14461 (delete-region (point) (point-at-eol))
14462 (org-set-tags nil 'align))
14463 (goto-char (point-at-eol))
14464 (insert " " data)
14465 (org-set-tags nil 'align)))
14466 (beginning-of-line 1)
14467 (if (looking-at ".*?\\([ \t]+\\)$")
14468 (delete-region (match-beginning 1) (match-end 1))))))
14470 (defun org-align-all-tags ()
14471 "Align the tags i all headings."
14472 (interactive)
14473 (save-excursion
14474 (or (ignore-errors (org-back-to-heading t))
14475 (outline-next-heading))
14476 (if (org-at-heading-p)
14477 (org-set-tags t)
14478 (message "No headings"))))
14480 (defvar org-indent-indentation-per-level)
14481 (defun org-set-tags (&optional arg just-align)
14482 "Set the tags for the current headline.
14483 With prefix ARG, realign all tags in headings in the current buffer.
14484 When JUST-ALIGN is non-nil, only align tags."
14485 (interactive "P")
14486 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14487 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14488 'region-start-level 'region))
14489 org-loop-over-headlines-in-active-region)
14490 (org-map-entries
14491 ;; We don't use ARG and JUST-ALIGN here because these args
14492 ;; are not useful when looping over headlines.
14493 `(org-set-tags)
14494 org-loop-over-headlines-in-active-region
14495 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14496 (let* ((re org-outline-regexp-bol)
14497 (current (unless arg (org-get-tags-string)))
14498 (col (current-column))
14499 (org-setting-tags t)
14500 table current-tags inherited-tags ; computed below when needed
14501 tags p0 c0 c1 rpl di tc level)
14502 (if arg
14503 (save-excursion
14504 (goto-char (point-min))
14505 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14506 (while (re-search-forward re nil t)
14507 (org-set-tags nil t)
14508 (end-of-line 1)))
14509 (message "All tags realigned to column %d" org-tags-column))
14510 (if just-align
14511 (setq tags current)
14512 ;; Get a new set of tags from the user
14513 (save-excursion
14514 (setq table (append org-tag-persistent-alist
14515 (or org-tag-alist (org-get-buffer-tags))
14516 (and
14517 org-complete-tags-always-offer-all-agenda-tags
14518 (org-global-tags-completion-table
14519 (org-agenda-files))))
14520 org-last-tags-completion-table table
14521 current-tags (org-split-string current ":")
14522 inherited-tags (nreverse
14523 (nthcdr (length current-tags)
14524 (nreverse (org-get-tags-at))))
14525 tags
14526 (if (or (eq t org-use-fast-tag-selection)
14527 (and org-use-fast-tag-selection
14528 (delq nil (mapcar 'cdr table))))
14529 (org-fast-tag-selection
14530 current-tags inherited-tags table
14531 (if org-fast-tag-selection-include-todo
14532 org-todo-key-alist))
14533 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14534 (org-trim
14535 (org-icompleting-read "Tags: "
14536 'org-tags-completion-function
14537 nil nil current 'org-tags-history))))))
14538 (while (string-match "[-+&]+" tags)
14539 ;; No boolean logic, just a list
14540 (setq tags (replace-match ":" t t tags))))
14542 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14544 (if org-tags-sort-function
14545 (setq tags (mapconcat 'identity
14546 (sort (org-split-string
14547 tags (org-re "[^[:alnum:]_@#%]+"))
14548 org-tags-sort-function) ":")))
14550 (if (string-match "\\`[\t ]*\\'" tags)
14551 (setq tags "")
14552 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14553 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14555 ;; Insert new tags at the correct column
14556 (beginning-of-line 1)
14557 (setq level (or (and (looking-at org-outline-regexp)
14558 (- (match-end 0) (point) 1))
14560 (cond
14561 ((and (equal current "") (equal tags "")))
14562 ((re-search-forward
14563 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14564 (point-at-eol) t)
14565 (if (equal tags "")
14566 (setq rpl "")
14567 (goto-char (match-beginning 0))
14568 (setq c0 (current-column)
14569 ;; compute offset for the case of org-indent-mode active
14570 di (if (org-bound-and-true-p org-indent-mode)
14571 (* (1- org-indent-indentation-per-level) (1- level))
14573 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14574 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14575 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14576 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14577 (replace-match rpl t t)
14578 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14579 tags)
14580 (t (error "Tags alignment failed")))
14581 (org-move-to-column col)
14582 (unless just-align
14583 (run-hooks 'org-after-tags-change-hook))))))
14585 (defun org-change-tag-in-region (beg end tag off)
14586 "Add or remove TAG for each entry in the region.
14587 This works in the agenda, and also in an org-mode buffer."
14588 (interactive
14589 (list (region-beginning) (region-end)
14590 (let ((org-last-tags-completion-table
14591 (if (derived-mode-p 'org-mode)
14592 (org-uniquify
14593 (delq nil (append (org-get-buffer-tags)
14594 (org-global-tags-completion-table))))
14595 (org-global-tags-completion-table))))
14596 (org-icompleting-read
14597 "Tag: " 'org-tags-completion-function nil nil nil
14598 'org-tags-history))
14599 (progn
14600 (message "[s]et or [r]emove? ")
14601 (equal (read-char-exclusive) ?r))))
14602 (if (fboundp 'deactivate-mark) (deactivate-mark))
14603 (let ((agendap (equal major-mode 'org-agenda-mode))
14604 l1 l2 m buf pos newhead (cnt 0))
14605 (goto-char end)
14606 (setq l2 (1- (org-current-line)))
14607 (goto-char beg)
14608 (setq l1 (org-current-line))
14609 (loop for l from l1 to l2 do
14610 (org-goto-line l)
14611 (setq m (get-text-property (point) 'org-hd-marker))
14612 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14613 (and agendap m))
14614 (setq buf (if agendap (marker-buffer m) (current-buffer))
14615 pos (if agendap m (point)))
14616 (with-current-buffer buf
14617 (save-excursion
14618 (save-restriction
14619 (goto-char pos)
14620 (setq cnt (1+ cnt))
14621 (org-toggle-tag tag (if off 'off 'on))
14622 (setq newhead (org-get-heading)))))
14623 (and agendap (org-agenda-change-all-lines newhead m))))
14624 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14626 (defun org-tags-completion-function (string predicate &optional flag)
14627 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14628 (confirm (lambda (x) (stringp (car x)))))
14629 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14630 (setq s1 (match-string 1 string)
14631 s2 (match-string 2 string))
14632 (setq s1 "" s2 string))
14633 (cond
14634 ((eq flag nil)
14635 ;; try completion
14636 (setq rtn (try-completion s2 ctable confirm))
14637 (if (stringp rtn)
14638 (setq rtn
14639 (concat s1 s2 (substring rtn (length s2))
14640 (if (and org-add-colon-after-tag-completion
14641 (assoc rtn ctable))
14642 ":" ""))))
14643 rtn)
14644 ((eq flag t)
14645 ;; all-completions
14646 (all-completions s2 ctable confirm))
14647 ((eq flag 'lambda)
14648 ;; exact match?
14649 (assoc s2 ctable)))))
14651 (defun org-fast-tag-insert (kwd tags face &optional end)
14652 "Insert KDW, and the TAGS, the latter with face FACE.
14653 Also insert END."
14654 (insert (format "%-12s" (concat kwd ":"))
14655 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14656 (or end "")))
14658 (defun org-fast-tag-show-exit (flag)
14659 (save-excursion
14660 (org-goto-line 3)
14661 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14662 (replace-match ""))
14663 (when flag
14664 (end-of-line 1)
14665 (org-move-to-column (- (window-width) 19) t)
14666 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14668 (defun org-set-current-tags-overlay (current prefix)
14669 "Add an overlay to CURRENT tag with PREFIX."
14670 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14671 (if (featurep 'xemacs)
14672 (org-overlay-display org-tags-overlay (concat prefix s)
14673 'secondary-selection)
14674 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14675 (org-overlay-display org-tags-overlay (concat prefix s)))))
14677 (defvar org-last-tag-selection-key nil)
14678 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14679 "Fast tag selection with single keys.
14680 CURRENT is the current list of tags in the headline, INHERITED is the
14681 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14682 possibly with grouping information. TODO-TABLE is a similar table with
14683 TODO keywords, should these have keys assigned to them.
14684 If the keys are nil, a-z are automatically assigned.
14685 Returns the new tags string, or nil to not change the current settings."
14686 (let* ((fulltable (append table todo-table))
14687 (maxlen (apply 'max (mapcar
14688 (lambda (x)
14689 (if (stringp (car x)) (string-width (car x)) 0))
14690 fulltable)))
14691 (buf (current-buffer))
14692 (expert (eq org-fast-tag-selection-single-key 'expert))
14693 (buffer-tags nil)
14694 (fwidth (+ maxlen 3 1 3))
14695 (ncol (/ (- (window-width) 4) fwidth))
14696 (i-face 'org-done)
14697 (c-face 'org-todo)
14698 tg cnt e c char c1 c2 ntable tbl rtn
14699 ov-start ov-end ov-prefix
14700 (exit-after-next org-fast-tag-selection-single-key)
14701 (done-keywords org-done-keywords)
14702 groups ingroup)
14703 (save-excursion
14704 (beginning-of-line 1)
14705 (if (looking-at
14706 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14707 (setq ov-start (match-beginning 1)
14708 ov-end (match-end 1)
14709 ov-prefix "")
14710 (setq ov-start (1- (point-at-eol))
14711 ov-end (1+ ov-start))
14712 (skip-chars-forward "^\n\r")
14713 (setq ov-prefix
14714 (concat
14715 (buffer-substring (1- (point)) (point))
14716 (if (> (current-column) org-tags-column)
14718 (make-string (- org-tags-column (current-column)) ?\ ))))))
14719 (move-overlay org-tags-overlay ov-start ov-end)
14720 (save-window-excursion
14721 (if expert
14722 (set-buffer (get-buffer-create " *Org tags*"))
14723 (delete-other-windows)
14724 (split-window-vertically)
14725 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14726 (erase-buffer)
14727 (org-set-local 'org-done-keywords done-keywords)
14728 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14729 (org-fast-tag-insert "Current" current c-face "\n\n")
14730 (org-fast-tag-show-exit exit-after-next)
14731 (org-set-current-tags-overlay current ov-prefix)
14732 (setq tbl fulltable char ?a cnt 0)
14733 (while (setq e (pop tbl))
14734 (cond
14735 ((equal (car e) :startgroup)
14736 (push '() groups) (setq ingroup t)
14737 (when (not (= cnt 0))
14738 (setq cnt 0)
14739 (insert "\n"))
14740 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14741 ((equal (car e) :endgroup)
14742 (setq ingroup nil cnt 0)
14743 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14744 ((equal e '(:newline))
14745 (when (not (= cnt 0))
14746 (setq cnt 0)
14747 (insert "\n")
14748 (setq e (car tbl))
14749 (while (equal (car tbl) '(:newline))
14750 (insert "\n")
14751 (setq tbl (cdr tbl)))))
14752 ((equal e '(:grouptags)) nil)
14754 (setq tg (copy-sequence (car e)) c2 nil)
14755 (if (cdr e)
14756 (setq c (cdr e))
14757 ;; automatically assign a character.
14758 (setq c1 (string-to-char
14759 (downcase (substring
14760 tg (if (= (string-to-char tg) ?@) 1 0)))))
14761 (if (or (rassoc c1 ntable) (rassoc c1 table))
14762 (while (or (rassoc char ntable) (rassoc char table))
14763 (setq char (1+ char)))
14764 (setq c2 c1))
14765 (setq c (or c2 char)))
14766 (if ingroup (push tg (car groups)))
14767 (setq tg (org-add-props tg nil 'face
14768 (cond
14769 ((not (assoc tg table))
14770 (org-get-todo-face tg))
14771 ((member tg current) c-face)
14772 ((member tg inherited) i-face))))
14773 (if (equal (caar tbl) :grouptags)
14774 (org-add-props tg nil 'face 'org-tag-group))
14775 (if (and (= cnt 0) (not ingroup)) (insert " "))
14776 (insert "[" c "] " tg (make-string
14777 (- fwidth 4 (length tg)) ?\ ))
14778 (push (cons tg c) ntable)
14779 (when (= (setq cnt (1+ cnt)) ncol)
14780 (insert "\n")
14781 (if ingroup (insert " "))
14782 (setq cnt 0)))))
14783 (setq ntable (nreverse ntable))
14784 (insert "\n")
14785 (goto-char (point-min))
14786 (if (not expert) (org-fit-window-to-buffer))
14787 (setq rtn
14788 (catch 'exit
14789 (while t
14790 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14791 (if (not groups) "no " "")
14792 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14793 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14794 (setq org-last-tag-selection-key c)
14795 (cond
14796 ((= c ?\r) (throw 'exit t))
14797 ((= c ?!)
14798 (setq groups (not groups))
14799 (goto-char (point-min))
14800 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14801 ((= c ?\C-c)
14802 (if (not expert)
14803 (org-fast-tag-show-exit
14804 (setq exit-after-next (not exit-after-next)))
14805 (setq expert nil)
14806 (delete-other-windows)
14807 (set-window-buffer (split-window-vertically) " *Org tags*")
14808 (org-switch-to-buffer-other-window " *Org tags*")
14809 (org-fit-window-to-buffer)))
14810 ((or (= c ?\C-g)
14811 (and (= c ?q) (not (rassoc c ntable))))
14812 (org-detach-overlay org-tags-overlay)
14813 (setq quit-flag t))
14814 ((= c ?\ )
14815 (setq current nil)
14816 (if exit-after-next (setq exit-after-next 'now)))
14817 ((= c ?\t)
14818 (condition-case nil
14819 (setq tg (org-icompleting-read
14820 "Tag: "
14821 (or buffer-tags
14822 (with-current-buffer buf
14823 (org-get-buffer-tags)))))
14824 (quit (setq tg "")))
14825 (when (string-match "\\S-" tg)
14826 (add-to-list 'buffer-tags (list tg))
14827 (if (member tg current)
14828 (setq current (delete tg current))
14829 (push tg current)))
14830 (if exit-after-next (setq exit-after-next 'now)))
14831 ((setq e (rassoc c todo-table) tg (car e))
14832 (with-current-buffer buf
14833 (save-excursion (org-todo tg)))
14834 (if exit-after-next (setq exit-after-next 'now)))
14835 ((setq e (rassoc c ntable) tg (car e))
14836 (if (member tg current)
14837 (setq current (delete tg current))
14838 (loop for g in groups do
14839 (if (member tg g)
14840 (mapc (lambda (x)
14841 (setq current (delete x current)))
14842 g)))
14843 (push tg current))
14844 (if exit-after-next (setq exit-after-next 'now))))
14846 ;; Create a sorted list
14847 (setq current
14848 (sort current
14849 (lambda (a b)
14850 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14851 (if (eq exit-after-next 'now) (throw 'exit t))
14852 (goto-char (point-min))
14853 (beginning-of-line 2)
14854 (delete-region (point) (point-at-eol))
14855 (org-fast-tag-insert "Current" current c-face)
14856 (org-set-current-tags-overlay current ov-prefix)
14857 (while (re-search-forward
14858 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14859 (setq tg (match-string 1))
14860 (add-text-properties
14861 (match-beginning 1) (match-end 1)
14862 (list 'face
14863 (cond
14864 ((member tg current) c-face)
14865 ((member tg inherited) i-face)
14866 (t (get-text-property (match-beginning 1) 'face))))))
14867 (goto-char (point-min)))))
14868 (org-detach-overlay org-tags-overlay)
14869 (if rtn
14870 (mapconcat 'identity current ":")
14871 nil))))
14873 (defun org-get-tags-string ()
14874 "Get the TAGS string in the current headline."
14875 (unless (org-at-heading-p t)
14876 (user-error "Not on a heading"))
14877 (save-excursion
14878 (beginning-of-line 1)
14879 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14880 (org-match-string-no-properties 1)
14881 "")))
14883 (defun org-get-tags ()
14884 "Get the list of tags specified in the current headline."
14885 (org-split-string (org-get-tags-string) ":"))
14887 (defun org-get-buffer-tags ()
14888 "Get a table of all tags used in the buffer, for completion."
14889 (let (tags)
14890 (save-excursion
14891 (goto-char (point-min))
14892 (while (re-search-forward
14893 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14894 (when (equal (char-after (point-at-bol 0)) ?*)
14895 (mapc (lambda (x) (add-to-list 'tags x))
14896 (org-split-string (org-match-string-no-properties 1) ":")))))
14897 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14898 (mapcar 'list tags)))
14900 ;;;; The mapping API
14902 (defun org-map-entries (func &optional match scope &rest skip)
14903 "Call FUNC at each headline selected by MATCH in SCOPE.
14905 FUNC is a function or a lisp form. The function will be called without
14906 arguments, with the cursor positioned at the beginning of the headline.
14907 The return values of all calls to the function will be collected and
14908 returned as a list.
14910 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14911 does not need to preserve point. After evaluation, the cursor will be
14912 moved to the end of the line (presumably of the headline of the
14913 processed entry) and search continues from there. Under some
14914 circumstances, this may not produce the wanted results. For example,
14915 if you have removed (e.g. archived) the current (sub)tree it could
14916 mean that the next entry will be skipped entirely. In such cases, you
14917 can specify the position from where search should continue by making
14918 FUNC set the variable `org-map-continue-from' to the desired buffer
14919 position.
14921 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14922 Only headlines that are matched by this query will be considered during
14923 the iteration. When MATCH is nil or t, all headlines will be
14924 visited by the iteration.
14926 SCOPE determines the scope of this command. It can be any of:
14928 nil The current buffer, respecting the restriction if any
14929 tree The subtree started with the entry at point
14930 region The entries within the active region, if any
14931 region-start-level
14932 The entries within the active region, but only those at
14933 the same level than the first one.
14934 file The current buffer, without restriction
14935 file-with-archives
14936 The current buffer, and any archives associated with it
14937 agenda All agenda files
14938 agenda-with-archives
14939 All agenda files with any archive files associated with them
14940 \(file1 file2 ...)
14941 If this is a list, all files in the list will be scanned
14943 The remaining args are treated as settings for the skipping facilities of
14944 the scanner. The following items can be given here:
14946 archive skip trees with the archive tag
14947 comment skip trees with the COMMENT keyword
14948 function or Emacs Lisp form:
14949 will be used as value for `org-agenda-skip-function', so
14950 whenever the function returns a position, FUNC will not be
14951 called for that entry and search will continue from the
14952 position returned
14954 If your function needs to retrieve the tags including inherited tags
14955 at the *current* entry, you can use the value of the variable
14956 `org-scanner-tags' which will be much faster than getting the value
14957 with `org-get-tags-at'. If your function gets properties with
14958 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14959 to t around the call to `org-entry-properties' to get the same speedup.
14960 Note that if your function moves around to retrieve tags and properties at
14961 a *different* entry, you cannot use these techniques."
14962 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14963 (not (org-region-active-p)))
14964 (let* ((org-agenda-archives-mode nil) ; just to make sure
14965 (org-agenda-skip-archived-trees (memq 'archive skip))
14966 (org-agenda-skip-comment-trees (memq 'comment skip))
14967 (org-agenda-skip-function
14968 (car (org-delete-all '(comment archive) skip)))
14969 (org-tags-match-list-sublevels t)
14970 (start-level (eq scope 'region-start-level))
14971 matcher file res
14972 org-todo-keywords-for-agenda
14973 org-done-keywords-for-agenda
14974 org-todo-keyword-alist-for-agenda
14975 org-drawers-for-agenda
14976 org-tag-alist-for-agenda
14977 todo-only)
14979 (cond
14980 ((eq match t) (setq matcher t))
14981 ((eq match nil) (setq matcher t))
14982 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14984 (save-excursion
14985 (save-restriction
14986 (cond ((eq scope 'tree)
14987 (org-back-to-heading t)
14988 (org-narrow-to-subtree)
14989 (setq scope nil))
14990 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14991 (org-region-active-p))
14992 ;; If needed, set start-level to a string like "2"
14993 (when start-level
14994 (save-excursion
14995 (goto-char (region-beginning))
14996 (unless (org-at-heading-p) (outline-next-heading))
14997 (setq start-level (org-current-level))))
14998 (narrow-to-region (region-beginning)
14999 (save-excursion
15000 (goto-char (region-end))
15001 (unless (and (bolp) (org-at-heading-p))
15002 (outline-next-heading))
15003 (point)))
15004 (setq scope nil)))
15006 (if (not scope)
15007 (progn
15008 (org-agenda-prepare-buffers
15009 (list (buffer-file-name (current-buffer))))
15010 (setq res (org-scan-tags func matcher todo-only start-level)))
15011 ;; Get the right scope
15012 (cond
15013 ((and scope (listp scope) (symbolp (car scope)))
15014 (setq scope (eval scope)))
15015 ((eq scope 'agenda)
15016 (setq scope (org-agenda-files t)))
15017 ((eq scope 'agenda-with-archives)
15018 (setq scope (org-agenda-files t))
15019 (setq scope (org-add-archive-files scope)))
15020 ((eq scope 'file)
15021 (setq scope (list (buffer-file-name))))
15022 ((eq scope 'file-with-archives)
15023 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15024 (org-agenda-prepare-buffers scope)
15025 (while (setq file (pop scope))
15026 (with-current-buffer (org-find-base-buffer-visiting file)
15027 (save-excursion
15028 (save-restriction
15029 (widen)
15030 (goto-char (point-min))
15031 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
15032 res)))
15034 ;;;; Properties
15036 ;;; Setting and retrieving properties
15038 (defconst org-special-properties
15039 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
15040 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
15041 "The special properties valid in Org-mode.
15043 These are properties that are not defined in the property drawer,
15044 but in some other way.")
15046 (defconst org-default-properties
15047 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15048 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15049 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15050 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15051 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
15052 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15053 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15054 "Some properties that are used by Org-mode for various purposes.
15055 Being in this list makes sure that they are offered for completion.")
15057 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
15058 "Regular expression matching the first line of a property drawer.")
15060 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
15061 "Regular expression matching the last line of a property drawer.")
15063 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
15064 "Regular expression matching the first line of a property drawer.")
15066 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
15067 "Regular expression matching the first line of a property drawer.")
15069 (defconst org-property-drawer-re
15070 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
15071 org-property-end-re "\\)\n?")
15072 "Matches an entire property drawer.")
15074 (defconst org-clock-drawer-re
15075 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
15076 org-property-end-re "\\)\n?")
15077 "Matches an entire clock drawer.")
15079 (defun org-property-action ()
15080 "Do an action on properties."
15081 (interactive)
15082 (let (c)
15083 (org-at-property-p)
15084 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15085 (setq c (read-char-exclusive))
15086 (cond
15087 ((equal c ?s)
15088 (call-interactively 'org-set-property))
15089 ((equal c ?d)
15090 (call-interactively 'org-delete-property))
15091 ((equal c ?D)
15092 (call-interactively 'org-delete-property-globally))
15093 ((equal c ?c)
15094 (call-interactively 'org-compute-property-at-point))
15095 (t (user-error "No such property action %c" c)))))
15097 (defun org-inc-effort ()
15098 "Increment the value of the effort property in the current entry."
15099 (interactive)
15100 (org-set-effort nil t))
15102 (defvar org-clock-effort) ;; Defined in org-clock.el
15103 (defvar org-clock-current-task) ;; Defined in org-clock.el
15104 (defun org-set-effort (&optional value increment)
15105 "Set the effort property of the current entry.
15106 With numerical prefix arg, use the nth allowed value, 0 stands for the
15107 10th allowed value.
15109 When INCREMENT is non-nil, set the property to the next allowed value."
15110 (interactive "P")
15111 (if (equal value 0) (setq value 10))
15112 (let* ((completion-ignore-case t)
15113 (prop org-effort-property)
15114 (cur (org-entry-get nil prop))
15115 (allowed (org-property-get-allowed-values nil prop 'table))
15116 (existing (mapcar 'list (org-property-values prop)))
15117 (heading (nth 4 (org-heading-components)))
15119 (val (cond
15120 ((stringp value) value)
15121 ((and allowed (integerp value))
15122 (or (car (nth (1- value) allowed))
15123 (car (org-last allowed))))
15124 ((and allowed increment)
15125 (or (caadr (member (list cur) allowed))
15126 (user-error "Allowed effort values are not set")))
15127 (allowed
15128 (message "Select 1-9,0, [RET%s]: %s"
15129 (if cur (concat "=" cur) "")
15130 (mapconcat 'car allowed " "))
15131 (setq rpl (read-char-exclusive))
15132 (if (equal rpl ?\r)
15134 (setq rpl (- rpl ?0))
15135 (if (equal rpl 0) (setq rpl 10))
15136 (if (and (> rpl 0) (<= rpl (length allowed)))
15137 (car (nth (1- rpl) allowed))
15138 (org-completing-read "Effort: " allowed nil))))
15140 (let (org-completion-use-ido org-completion-use-iswitchb)
15141 (org-completing-read
15142 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15143 (concat "[" cur "]") "")
15144 ": ")
15145 existing nil nil "" nil cur))))))
15146 (unless (equal (org-entry-get nil prop) val)
15147 (org-entry-put nil prop val))
15148 (save-excursion
15149 (org-back-to-heading t)
15150 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
15151 (when (string= heading org-clock-current-task)
15152 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
15153 (org-clock-update-mode-line))
15154 (message "%s is now %s" prop val)))
15156 (defun org-at-property-p ()
15157 "Is cursor inside a property drawer?"
15158 (save-excursion
15159 (when (equal 'node-property (car (org-element-at-point)))
15160 (beginning-of-line 1)
15161 (looking-at org-property-re))))
15163 (defun org-get-property-block (&optional beg end force)
15164 "Return the (beg . end) range of the body of the property drawer.
15165 BEG and END are the beginning and end of the current subtree, or of
15166 the part before the first headline. If they are not given, they will
15167 be found. If the drawer does not exist and FORCE is non-nil, create
15168 the drawer."
15169 (catch 'exit
15170 (save-excursion
15171 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15172 (progn (org-back-to-heading t) (point))))
15173 (end (or end (and (not (outline-next-heading)) (point-max))
15174 (point))))
15175 (goto-char beg)
15176 (if (re-search-forward org-property-start-re end t)
15177 (setq beg (1+ (match-end 0)))
15178 (if force
15179 (save-excursion
15180 (org-insert-property-drawer)
15181 (setq end (progn (outline-next-heading) (point))))
15182 (throw 'exit nil))
15183 (goto-char beg)
15184 (if (re-search-forward org-property-start-re end t)
15185 (setq beg (1+ (match-end 0)))))
15186 (if (re-search-forward org-property-end-re end t)
15187 (setq end (match-beginning 0))
15188 (or force (throw 'exit nil))
15189 (goto-char beg)
15190 (setq end beg)
15191 (org-indent-line)
15192 (insert ":END:\n"))
15193 (cons beg end)))))
15195 (defun org-entry-properties (&optional pom which specific)
15196 "Get all properties of the entry at point-or-marker POM.
15197 This includes the TODO keyword, the tags, time strings for deadline,
15198 scheduled, and clocking, and any additional properties defined in the
15199 entry. The return value is an alist, keys may occur multiple times
15200 if the property key was used several times.
15201 POM may also be nil, in which case the current entry is used.
15202 If WHICH is nil or `all', get all properties. If WHICH is
15203 `special' or `standard', only get that subclass. If WHICH
15204 is a string only get exactly this property. SPECIFIC can be a string, the
15205 specific property we are interested in. Specifying it can speed
15206 things up because then unnecessary parsing is avoided."
15207 (setq which (or which 'all))
15208 (org-with-wide-buffer
15209 (org-with-point-at pom
15210 (let ((clockstr (substring org-clock-string 0 -1))
15211 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15212 (case-fold-search nil)
15213 beg end range props sum-props key key1 value string clocksum clocksumt)
15214 (when (and (derived-mode-p 'org-mode)
15215 (ignore-errors (org-back-to-heading t)))
15216 (setq beg (point))
15217 (setq sum-props (get-text-property (point) 'org-summaries))
15218 (setq clocksum (get-text-property (point) :org-clock-minutes)
15219 clocksumt (get-text-property (point) :org-clock-minutes-today))
15220 (outline-next-heading)
15221 (setq end (point))
15222 (when (memq which '(all special))
15223 ;; Get the special properties, like TODO and tags
15224 (goto-char beg)
15225 (when (and (or (not specific) (string= specific "TODO"))
15226 (looking-at org-todo-line-regexp) (match-end 2))
15227 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15228 (when (and (or (not specific) (string= specific "PRIORITY"))
15229 (looking-at org-priority-regexp))
15230 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15231 (when (or (not specific) (string= specific "FILE"))
15232 (push (cons "FILE" buffer-file-name) props))
15233 (when (and (or (not specific) (string= specific "TAGS"))
15234 (setq value (org-get-tags-string))
15235 (string-match "\\S-" value))
15236 (push (cons "TAGS" value) props))
15237 (when (and (or (not specific) (string= specific "ALLTAGS"))
15238 (setq value (org-get-tags-at)))
15239 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15240 ":"))
15241 props))
15242 (when (or (not specific) (string= specific "BLOCKED"))
15243 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15244 (when (or (not specific)
15245 (member specific
15246 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15247 "TIMESTAMP" "TIMESTAMP_IA")))
15248 (catch 'match
15249 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15250 (setq key (if (match-end 1)
15251 (substring (org-match-string-no-properties 1)
15252 0 -1))
15253 string (if (equal key clockstr)
15254 (org-trim
15255 (buffer-substring-no-properties
15256 (match-beginning 3) (goto-char
15257 (point-at-eol))))
15258 (substring (org-match-string-no-properties 3)
15259 1 -1)))
15260 ;; Get the correct property name from the key. This is
15261 ;; necessary if the user has configured time keywords.
15262 (setq key1 (concat key ":"))
15263 (cond
15264 ((not key)
15265 (setq key
15266 (if (= (char-after (match-beginning 3)) ?\[)
15267 "TIMESTAMP_IA" "TIMESTAMP")))
15268 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15269 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15270 ((equal key1 org-closed-string) (setq key "CLOSED"))
15271 ((equal key1 org-clock-string) (setq key "CLOCK")))
15272 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15273 (progn
15274 (push (cons key string) props)
15275 ;; no need to search further if match is found
15276 (throw 'match t))
15277 (when (or (equal key "CLOCK") (not (assoc key props)))
15278 (push (cons key string) props)))))))
15280 (when (memq which '(all standard))
15281 ;; Get the standard properties, like :PROP: ...
15282 (setq range (org-get-property-block beg end))
15283 (when range
15284 (goto-char (car range))
15285 (while (re-search-forward org-property-re
15286 (cdr range) t)
15287 (setq key (org-match-string-no-properties 2)
15288 value (org-trim (or (org-match-string-no-properties 3) "")))
15289 (unless (member key excluded)
15290 (push (cons key (or value "")) props)))))
15291 (if clocksum
15292 (push (cons "CLOCKSUM"
15293 (org-columns-number-to-string (/ (float clocksum) 60.)
15294 'add_times))
15295 props))
15296 (if clocksumt
15297 (push (cons "CLOCKSUM_T"
15298 (org-columns-number-to-string (/ (float clocksumt) 60.)
15299 'add_times))
15300 props))
15301 (unless (assoc "CATEGORY" props)
15302 (push (cons "CATEGORY" (org-get-category)) props))
15303 (append sum-props (nreverse props)))))))
15305 (defun org-entry-get (pom property &optional inherit literal-nil)
15306 "Get value of PROPERTY for entry or content at point-or-marker POM.
15307 If INHERIT is non-nil and the entry does not have the property,
15308 then also check higher levels of the hierarchy.
15309 If INHERIT is the symbol `selective', use inheritance only if the setting
15310 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15311 If the property is present but empty, the return value is the empty string.
15312 If the property is not present at all, nil is returned.
15314 Return the value as a string.
15316 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15317 do not interpret it as the list atom nil. This is used for inheritance
15318 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15319 (org-with-point-at pom
15320 (if (and inherit (if (eq inherit 'selective)
15321 (org-property-inherit-p property)
15323 (org-entry-get-with-inheritance property literal-nil)
15324 (if (member property org-special-properties)
15325 ;; We need a special property. Use `org-entry-properties'
15326 ;; to retrieve it, but specify the wanted property
15327 (cdr (assoc property (org-entry-properties nil 'special property)))
15328 (org-with-wide-buffer
15329 (let ((range (org-get-property-block)))
15330 (when (and range (not (eq (car range) (cdr range)))
15331 (save-excursion
15332 (goto-char (car range))
15333 (re-search-forward
15334 (concat (org-re-property property) "\\|"
15335 (org-re-property (concat property "+")))
15336 (cdr range) t)))
15337 (let* ((props
15338 (list (or (assoc property org-file-properties)
15339 (assoc property org-global-properties)
15340 (assoc property org-global-properties-fixed))))
15341 (ap (lambda (key)
15342 (when (re-search-forward
15343 (org-re-property key) (cdr range) t)
15344 (setq props
15345 (org-update-property-plist
15347 (if (match-end 3)
15348 (org-match-string-no-properties 3) "")
15349 props)))))
15350 val)
15351 (goto-char (car range))
15352 (funcall ap property)
15353 (goto-char (car range))
15354 (while (funcall ap (concat property "+")))
15355 (setq val (cdr (assoc property props)))
15356 (when val (if literal-nil val (org-not-nil val)))))))))))
15358 (defun org-property-or-variable-value (var &optional inherit)
15359 "Check if there is a property fixing the value of VAR.
15360 If yes, return this value. If not, return the current value of the variable."
15361 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15362 (if (and prop (stringp prop) (string-match "\\S-" prop))
15363 (read prop)
15364 (symbol-value var))))
15366 (defun org-entry-delete (pom property &optional delete-empty-drawer)
15367 "Delete the property PROPERTY from entry at point-or-marker POM.
15368 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15369 an empty drawer to delete."
15370 (org-with-point-at pom
15371 (if (member property org-special-properties)
15372 nil ; cannot delete these properties.
15373 (let ((range (org-get-property-block)))
15374 (if (and range
15375 (goto-char (car range))
15376 (re-search-forward
15377 (org-re-property property)
15378 (cdr range) t))
15379 (progn
15380 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15381 (and delete-empty-drawer
15382 (org-remove-empty-drawer-at
15383 delete-empty-drawer (car range)))
15385 nil)))))
15387 ;; Multi-values properties are properties that contain multiple values
15388 ;; These values are assumed to be single words, separated by whitespace.
15389 (defun org-entry-add-to-multivalued-property (pom property value)
15390 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15391 (let* ((old (org-entry-get pom property))
15392 (values (and old (org-split-string old "[ \t]"))))
15393 (setq value (org-entry-protect-space value))
15394 (unless (member value values)
15395 (setq values (append values (list value)))
15396 (org-entry-put pom property
15397 (mapconcat 'identity values " ")))))
15399 (defun org-entry-remove-from-multivalued-property (pom property value)
15400 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15401 (let* ((old (org-entry-get pom property))
15402 (values (and old (org-split-string old "[ \t]"))))
15403 (setq value (org-entry-protect-space value))
15404 (when (member value values)
15405 (setq values (delete value values))
15406 (org-entry-put pom property
15407 (mapconcat 'identity values " ")))))
15409 (defun org-entry-member-in-multivalued-property (pom property value)
15410 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15411 (let* ((old (org-entry-get pom property))
15412 (values (and old (org-split-string old "[ \t]"))))
15413 (setq value (org-entry-protect-space value))
15414 (member value values)))
15416 (defun org-entry-get-multivalued-property (pom property)
15417 "Return a list of values in a multivalued property."
15418 (let* ((value (org-entry-get pom property))
15419 (values (and value (org-split-string value "[ \t]"))))
15420 (mapcar 'org-entry-restore-space values)))
15422 (defun org-entry-put-multivalued-property (pom property &rest values)
15423 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15424 VALUES should be a list of strings. Spaces will be protected."
15425 (org-entry-put pom property
15426 (mapconcat 'org-entry-protect-space values " "))
15427 (let* ((value (org-entry-get pom property))
15428 (values (and value (org-split-string value "[ \t]"))))
15429 (mapcar 'org-entry-restore-space values)))
15431 (defun org-entry-protect-space (s)
15432 "Protect spaces and newline in string S."
15433 (while (string-match " " s)
15434 (setq s (replace-match "%20" t t s)))
15435 (while (string-match "\n" s)
15436 (setq s (replace-match "%0A" t t s)))
15439 (defun org-entry-restore-space (s)
15440 "Restore spaces and newline in string S."
15441 (while (string-match "%20" s)
15442 (setq s (replace-match " " t t s)))
15443 (while (string-match "%0A" s)
15444 (setq s (replace-match "\n" t t s)))
15447 (defvar org-entry-property-inherited-from (make-marker)
15448 "Marker pointing to the entry from where a property was inherited.
15449 Each call to `org-entry-get-with-inheritance' will set this marker to the
15450 location of the entry where the inheritance search matched. If there was
15451 no match, the marker will point nowhere.
15452 Note that also `org-entry-get' calls this function, if the INHERIT flag
15453 is set.")
15455 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15456 "Get PROPERTY of entry or content at point, search higher levels if needed.
15457 The search will stop at the first ancestor which has the property defined.
15458 If the value found is \"nil\", return nil to show that the property
15459 should be considered as undefined (this is the meaning of nil here).
15460 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15461 (move-marker org-entry-property-inherited-from nil)
15462 (let (tmp)
15463 (save-excursion
15464 (save-restriction
15465 (widen)
15466 (catch 'ex
15467 (while t
15468 (when (setq tmp (org-entry-get nil property nil literal-nil))
15469 (or (ignore-errors (org-back-to-heading t))
15470 (goto-char (point-min)))
15471 (move-marker org-entry-property-inherited-from (point))
15472 (throw 'ex tmp))
15473 (or (ignore-errors (org-up-heading-safe))
15474 (throw 'ex nil))))))
15475 (setq tmp (or tmp
15476 (cdr (assoc property org-file-properties))
15477 (cdr (assoc property org-global-properties))
15478 (cdr (assoc property org-global-properties-fixed))))
15479 (if literal-nil tmp (org-not-nil tmp))))
15481 (defvar org-property-changed-functions nil
15482 "Hook called when the value of a property has changed.
15483 Each hook function should accept two arguments, the name of the property
15484 and the new value.")
15486 (defun org-entry-put (pom property value)
15487 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15488 If the value is `nil', it is converted to the empty string.
15489 If it is not a string, an error is raised."
15490 (cond ((null value) (setq value ""))
15491 ((not (stringp value))
15492 (error "Properties values should be strings.")))
15493 (org-with-point-at pom
15494 (org-back-to-heading t)
15495 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15496 range)
15497 (cond
15498 ((equal property "TODO")
15499 (when (and (string-match "\\S-" value)
15500 (not (member value org-todo-keywords-1)))
15501 (user-error "\"%s\" is not a valid TODO state" value))
15502 (if (or (not value)
15503 (not (string-match "\\S-" value)))
15504 (setq value 'none))
15505 (org-todo value)
15506 (org-set-tags nil 'align))
15507 ((equal property "PRIORITY")
15508 (org-priority (if (and value (string-match "\\S-" value))
15509 (string-to-char value) ?\ ))
15510 (org-set-tags nil 'align))
15511 ((equal property "CLOCKSUM")
15512 (if (not (re-search-forward
15513 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15514 (error "Cannot find a clock log")
15515 (goto-char (- (match-end 1) 2))
15516 (cond
15517 ((eq value 'earlier) (org-timestamp-down))
15518 ((eq value 'later) (org-timestamp-up)))
15519 (org-clock-sum-current-item)))
15520 ((equal property "SCHEDULED")
15521 (if (re-search-forward org-scheduled-time-regexp end t)
15522 (cond
15523 ((eq value 'earlier) (org-timestamp-change -1 'day))
15524 ((eq value 'later) (org-timestamp-change 1 'day))
15525 (t (call-interactively 'org-schedule)))
15526 (call-interactively 'org-schedule)))
15527 ((equal property "DEADLINE")
15528 (if (re-search-forward org-deadline-time-regexp end t)
15529 (cond
15530 ((eq value 'earlier) (org-timestamp-change -1 'day))
15531 ((eq value 'later) (org-timestamp-change 1 'day))
15532 (t (call-interactively 'org-deadline)))
15533 (call-interactively 'org-deadline)))
15534 ((member property org-special-properties)
15535 (error "The %s property can not yet be set with `org-entry-put'"
15536 property))
15537 (t ; a non-special property
15538 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15539 (setq range (org-get-property-block beg end 'force))
15540 (goto-char (car range))
15541 (if (re-search-forward
15542 (org-re-property property) (cdr range) t)
15543 (progn
15544 (delete-region (match-beginning 0) (match-end 0))
15545 (goto-char (match-beginning 0)))
15546 (goto-char (cdr range))
15547 (insert "\n")
15548 (backward-char 1)
15549 (org-indent-line))
15550 (insert ":" property ":")
15551 (and value (insert " " value))
15552 (org-indent-line)))))
15553 (run-hook-with-args 'org-property-changed-functions property value)))
15555 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15556 "Get all property keys in the current buffer.
15557 With INCLUDE-SPECIALS, also list the special properties that reflect things
15558 like tags and TODO state.
15559 With INCLUDE-DEFAULTS, also include properties that has special meaning
15560 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15561 and others.
15562 With INCLUDE-COLUMNS, also include property names given in COLUMN
15563 formats in the current buffer."
15564 (let (rtn range cfmt s p)
15565 (save-excursion
15566 (save-restriction
15567 (widen)
15568 (goto-char (point-min))
15569 (while (re-search-forward org-property-start-re nil t)
15570 (setq range (org-get-property-block))
15571 (goto-char (car range))
15572 (while (re-search-forward org-property-re
15573 (cdr range) t)
15574 (add-to-list 'rtn (org-match-string-no-properties 2)))
15575 (outline-next-heading))))
15577 (when include-specials
15578 (setq rtn (append org-special-properties rtn)))
15580 (when include-defaults
15581 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15582 (add-to-list 'rtn org-effort-property))
15584 (when include-columns
15585 (save-excursion
15586 (save-restriction
15587 (widen)
15588 (goto-char (point-min))
15589 (while (re-search-forward
15590 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15591 nil t)
15592 (setq cfmt (match-string 2) s 0)
15593 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15594 cfmt s)
15595 (setq s (match-end 0)
15596 p (match-string 1 cfmt))
15597 (unless (or (equal p "ITEM")
15598 (member p org-special-properties))
15599 (add-to-list 'rtn (match-string 1 cfmt))))))))
15601 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15603 (defun org-property-values (key)
15604 "Return a list of all values of property KEY in the current buffer."
15605 (save-excursion
15606 (save-restriction
15607 (widen)
15608 (goto-char (point-min))
15609 (let ((re (org-re-property key))
15610 values)
15611 (while (re-search-forward re nil t)
15612 (add-to-list 'values (org-trim (match-string 3))))
15613 (delete "" values)))))
15615 (defun org-insert-property-drawer ()
15616 "Insert a property drawer into the current entry."
15617 (org-back-to-heading t)
15618 (looking-at org-outline-regexp)
15619 (let ((indent (if org-adapt-indentation
15620 (- (match-end 0) (match-beginning 0))
15622 (beg (point))
15623 (re (concat "^[ \t]*" org-keyword-time-regexp))
15624 end hiddenp)
15625 (outline-next-heading)
15626 (setq end (point))
15627 (goto-char beg)
15628 (while (re-search-forward re end t))
15629 (setq hiddenp (outline-invisible-p))
15630 (end-of-line 1)
15631 (and (equal (char-after) ?\n) (forward-char 1))
15632 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15633 (if (member (match-string 1) '("CLOCK:" ":END:"))
15634 ;; just skip this line
15635 (beginning-of-line 2)
15636 ;; Drawer start, find the end
15637 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15638 (beginning-of-line 1)))
15639 (org-skip-over-state-notes)
15640 (skip-chars-backward " \t\n\r")
15641 (if (and (eq (char-before) ?*) (not (eq (char-after) ?\n)))
15642 (forward-char 1))
15643 (goto-char (point-at-eol))
15644 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15645 (beginning-of-line 0)
15646 (org-indent-to-column indent)
15647 (beginning-of-line 2)
15648 (org-indent-to-column indent)
15649 (beginning-of-line 0)
15650 (if hiddenp
15651 (save-excursion
15652 (org-back-to-heading t)
15653 (hide-entry))
15654 (org-flag-drawer t))))
15656 (defun org-insert-drawer (&optional arg drawer)
15657 "Insert a drawer at point.
15659 Optional argument DRAWER, when non-nil, is a string representing
15660 drawer's name. Otherwise, the user is prompted for a name.
15662 If a region is active, insert the drawer around that region
15663 instead.
15665 Point is left between drawer's boundaries."
15666 (interactive "P")
15667 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15668 "LOGBOOK"))
15669 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15670 ;; internally by Org. They are meant to be inserted
15671 ;; automatically.
15672 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15673 ;; Remove system drawers from list. Note: For some reason,
15674 ;; `org-completing-read' ignores the predicate while
15675 ;; `completing-read' handles it fine.
15676 (drawer (if arg "PROPERTIES"
15677 (or drawer
15678 (completing-read
15679 "Drawer: " org-drawers
15680 (lambda (d) (not (member d system-drawers))))))))
15681 (cond
15682 ;; With C-u, fall back on `org-insert-property-drawer'
15683 (arg (org-insert-property-drawer))
15684 ;; With an active region, insert a drawer at point.
15685 ((not (org-region-active-p))
15686 (progn
15687 (unless (bolp) (insert "\n"))
15688 (insert (format ":%s:\n\n:END:\n" drawer))
15689 (forward-line -2)))
15690 ;; Otherwise, insert the drawer at point
15692 (let ((rbeg (region-beginning))
15693 (rend (copy-marker (region-end))))
15694 (unwind-protect
15695 (progn
15696 (goto-char rbeg)
15697 (beginning-of-line)
15698 (when (save-excursion
15699 (re-search-forward org-outline-regexp-bol rend t))
15700 (user-error "Drawers cannot contain headlines"))
15701 ;; Position point at the beginning of the first
15702 ;; non-blank line in region. Insert drawer's opening
15703 ;; there, then indent it.
15704 (org-skip-whitespace)
15705 (beginning-of-line)
15706 (insert ":" drawer ":\n")
15707 (forward-line -1)
15708 (indent-for-tab-command)
15709 ;; Move point to the beginning of the first blank line
15710 ;; after the last non-blank line in region. Insert
15711 ;; drawer's closing, then indent it.
15712 (goto-char rend)
15713 (skip-chars-backward " \r\t\n")
15714 (insert "\n:END:")
15715 (deactivate-mark t)
15716 (indent-for-tab-command)
15717 (unless (eolp) (insert "\n")))
15718 ;; Clear marker, whatever the outcome of insertion is.
15719 (set-marker rend nil)))))))
15721 (defvar org-property-set-functions-alist nil
15722 "Property set function alist.
15723 Each entry should have the following format:
15725 (PROPERTY . READ-FUNCTION)
15727 The read function will be called with the same argument as
15728 `org-completing-read'.")
15730 (defun org-set-property-function (property)
15731 "Get the function that should be used to set PROPERTY.
15732 This is computed according to `org-property-set-functions-alist'."
15733 (or (cdr (assoc property org-property-set-functions-alist))
15734 'org-completing-read))
15736 (defun org-read-property-value (property)
15737 "Read PROPERTY value from user."
15738 (let* ((completion-ignore-case t)
15739 (allowed (org-property-get-allowed-values nil property 'table))
15740 (cur (org-entry-get nil property))
15741 (prompt (concat property " value"
15742 (if (and cur (string-match "\\S-" cur))
15743 (concat " [" cur "]") "") ": "))
15744 (set-function (org-set-property-function property))
15745 (val (if allowed
15746 (funcall set-function prompt allowed nil
15747 (not (get-text-property 0 'org-unrestricted
15748 (caar allowed))))
15749 (let (org-completion-use-ido org-completion-use-iswitchb)
15750 (funcall set-function prompt
15751 (mapcar 'list (org-property-values property))
15752 nil nil "" nil cur)))))
15753 (if (equal val "")
15755 val)))
15757 (defvar org-last-set-property nil)
15758 (defvar org-last-set-property-value nil)
15759 (defun org-read-property-name ()
15760 "Read a property name."
15761 (let* ((completion-ignore-case t)
15762 (keys (org-buffer-property-keys nil t t))
15763 (default-prop (or (save-excursion
15764 (save-match-data
15765 (beginning-of-line)
15766 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15767 (null (string= (match-string 1) "END"))
15768 (match-string 1))))
15769 org-last-set-property))
15770 (property (org-icompleting-read
15771 (concat "Property"
15772 (if default-prop (concat " [" default-prop "]") "")
15773 ": ")
15774 (mapcar 'list keys)
15775 nil nil nil nil
15776 default-prop)))
15777 (if (member property keys)
15778 property
15779 (or (cdr (assoc (downcase property)
15780 (mapcar (lambda (x) (cons (downcase x) x))
15781 keys)))
15782 property))))
15784 (defun org-set-property-and-value (use-last)
15785 "Allow to set [PROPERTY]: [value] direction from prompt.
15786 When use-default, don't even ask, just use the last
15787 \"[PROPERTY]: [value]\" string from the history."
15788 (interactive "P")
15789 (let* ((completion-ignore-case t)
15790 (pv (or (and use-last org-last-set-property-value)
15791 (org-completing-read
15792 "Enter a \"[Property]: [value]\" pair: "
15793 nil nil nil nil nil
15794 org-last-set-property-value)))
15795 prop val)
15796 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15797 (setq prop (match-string 1 pv)
15798 val (match-string 2 pv))
15799 (org-set-property prop val))))
15801 (defun org-set-property (property value)
15802 "In the current entry, set PROPERTY to VALUE.
15803 When called interactively, this will prompt for a property name, offering
15804 completion on existing and default properties. And then it will prompt
15805 for a value, offering completion either on allowed values (via an inherited
15806 xxx_ALL property) or on existing values in other instances of this property
15807 in the current file."
15808 (interactive (list nil nil))
15809 (let* ((property (or property (org-read-property-name)))
15810 (value (or value (org-read-property-value property)))
15811 (fn (cdr (assoc property org-properties-postprocess-alist))))
15812 (setq org-last-set-property property)
15813 (setq org-last-set-property-value (concat property ": " value))
15814 ;; Possibly postprocess the inserted value:
15815 (when fn (setq value (funcall fn value)))
15816 (unless (equal (org-entry-get nil property) value)
15817 (org-entry-put nil property value))))
15819 (defun org-delete-property (property &optional delete-empty-drawer)
15820 "In the current entry, delete PROPERTY.
15821 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15822 an empty drawer to delete."
15823 (interactive
15824 (let* ((completion-ignore-case t)
15825 (cat (org-entry-get (point) "CATEGORY"))
15826 (props0 (org-entry-properties nil 'standard))
15827 (props (if cat props0
15828 (delete `("CATEGORY" . ,(org-get-category)) props0)))
15829 (prop (if (< 1 (length props))
15830 (org-icompleting-read "Property: " props nil t)
15831 (caar props))))
15832 (list prop)))
15833 (if (org-entry-delete nil property delete-empty-drawer)
15834 (message "Property %s deleted" property)))
15836 (defun org-delete-property-globally (property)
15837 "Remove PROPERTY globally, from all entries."
15838 (interactive
15839 (let* ((completion-ignore-case t)
15840 (prop (org-icompleting-read
15841 "Globally remove property: "
15842 (mapcar 'list (org-buffer-property-keys)))))
15843 (list prop)))
15844 (save-excursion
15845 (save-restriction
15846 (widen)
15847 (goto-char (point-min))
15848 (let ((cnt 0))
15849 (while (re-search-forward
15850 (org-re-property property)
15851 nil t)
15852 (setq cnt (1+ cnt))
15853 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15854 (message "Property \"%s\" removed from %d entries" property cnt)))))
15856 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15858 (defun org-compute-property-at-point ()
15859 "Compute the property at point.
15860 This looks for an enclosing column format, extracts the operator and
15861 then applies it to the property in the column format's scope."
15862 (interactive)
15863 (unless (org-at-property-p)
15864 (user-error "Not at a property"))
15865 (let ((prop (org-match-string-no-properties 2)))
15866 (org-columns-get-format-and-top-level)
15867 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15868 (user-error "No operator defined for property %s" prop))
15869 (org-columns-compute prop)))
15871 (defvar org-property-allowed-value-functions nil
15872 "Hook for functions supplying allowed values for a specific property.
15873 The functions must take a single argument, the name of the property, and
15874 return a flat list of allowed values. If \":ETC\" is one of
15875 the values, this means that these values are intended as defaults for
15876 completion, but that other values should be allowed too.
15877 The functions must return nil if they are not responsible for this
15878 property.")
15880 (defun org-property-get-allowed-values (pom property &optional table)
15881 "Get allowed values for the property PROPERTY.
15882 When TABLE is non-nil, return an alist that can directly be used for
15883 completion."
15884 (let (vals)
15885 (cond
15886 ((equal property "TODO")
15887 (setq vals (org-with-point-at pom
15888 (append org-todo-keywords-1 '("")))))
15889 ((equal property "PRIORITY")
15890 (let ((n org-lowest-priority))
15891 (while (>= n org-highest-priority)
15892 (push (char-to-string n) vals)
15893 (setq n (1- n)))))
15894 ((member property org-special-properties))
15895 ((setq vals (run-hook-with-args-until-success
15896 'org-property-allowed-value-functions property)))
15898 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15899 (when (and vals (string-match "\\S-" vals))
15900 (setq vals (car (read-from-string (concat "(" vals ")"))))
15901 (setq vals (mapcar (lambda (x)
15902 (cond ((stringp x) x)
15903 ((numberp x) (number-to-string x))
15904 ((symbolp x) (symbol-name x))
15905 (t "???")))
15906 vals)))))
15907 (when (member ":ETC" vals)
15908 (setq vals (remove ":ETC" vals))
15909 (org-add-props (car vals) '(org-unrestricted t)))
15910 (if table (mapcar 'list vals) vals)))
15912 (defun org-property-previous-allowed-value (&optional previous)
15913 "Switch to the next allowed value for this property."
15914 (interactive)
15915 (org-property-next-allowed-value t))
15917 (defun org-property-next-allowed-value (&optional previous)
15918 "Switch to the next allowed value for this property."
15919 (interactive)
15920 (unless (org-at-property-p)
15921 (user-error "Not at a property"))
15922 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15923 (key (match-string 2))
15924 (value (match-string 3))
15925 (allowed (or (org-property-get-allowed-values (point) key)
15926 (and (member value '("[ ]" "[-]" "[X]"))
15927 '("[ ]" "[X]"))))
15928 (heading (save-match-data (nth 4 (org-heading-components))))
15929 nval)
15930 (unless allowed
15931 (user-error "Allowed values for this property have not been defined"))
15932 (if previous (setq allowed (reverse allowed)))
15933 (if (member value allowed)
15934 (setq nval (car (cdr (member value allowed)))))
15935 (setq nval (or nval (car allowed)))
15936 (if (equal nval value)
15937 (user-error "Only one allowed value for this property"))
15938 (org-at-property-p)
15939 (replace-match (concat " :" key ": " nval) t t)
15940 (org-indent-line)
15941 (beginning-of-line 1)
15942 (skip-chars-forward " \t")
15943 (when (equal prop org-effort-property)
15944 (save-excursion
15945 (org-back-to-heading t)
15946 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
15947 (when (string= org-clock-current-task heading)
15948 (setq org-clock-effort nval)
15949 (org-clock-update-mode-line)))
15950 (run-hook-with-args 'org-property-changed-functions key nval)))
15952 (defun org-find-olp (path &optional this-buffer)
15953 "Return a marker pointing to the entry at outline path OLP.
15954 If anything goes wrong, throw an error.
15955 You can wrap this call to catch the error like this:
15957 (condition-case msg
15958 (org-mobile-locate-entry (match-string 4))
15959 (error (nth 1 msg)))
15961 The return value will then be either a string with the error message,
15962 or a marker if everything is OK.
15964 If THIS-BUFFER is set, the outline path does not contain a file,
15965 only headings."
15966 (let* ((file (if this-buffer buffer-file-name (pop path)))
15967 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15968 (level 1)
15969 (lmin 1)
15970 (lmax 1)
15971 limit re end found pos heading cnt flevel)
15972 (unless buffer (error "File not found :%s" file))
15973 (with-current-buffer buffer
15974 (save-excursion
15975 (save-restriction
15976 (widen)
15977 (setq limit (point-max))
15978 (goto-char (point-min))
15979 (while (setq heading (pop path))
15980 (setq re (format org-complex-heading-regexp-format
15981 (regexp-quote heading)))
15982 (setq cnt 0 pos (point))
15983 (while (re-search-forward re end t)
15984 (setq level (- (match-end 1) (match-beginning 1)))
15985 (if (and (>= level lmin) (<= level lmax))
15986 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15987 (when (= cnt 0) (error "Heading not found on level %d: %s"
15988 lmax heading))
15989 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15990 lmax heading))
15991 (goto-char found)
15992 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15993 (setq end (save-excursion (org-end-of-subtree t t))))
15994 (when (org-at-heading-p)
15995 (point-marker)))))))
15997 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15998 "Find node HEADING in BUFFER.
15999 Return a marker to the heading if it was found, or nil if not.
16000 If POS-ONLY is set, return just the position instead of a marker.
16002 The heading text must match exact, but it may have a TODO keyword,
16003 a priority cookie and tags in the standard locations."
16004 (with-current-buffer (or buffer (current-buffer))
16005 (save-excursion
16006 (save-restriction
16007 (widen)
16008 (goto-char (point-min))
16009 (let (case-fold-search)
16010 (if (re-search-forward
16011 (format org-complex-heading-regexp-format
16012 (regexp-quote heading)) nil t)
16013 (if pos-only
16014 (match-beginning 0)
16015 (move-marker (make-marker) (match-beginning 0)))))))))
16017 (defun org-find-exact-heading-in-directory (heading &optional dir)
16018 "Find Org node headline HEADING in all .org files in directory DIR.
16019 When the target headline is found, return a marker to this location."
16020 (let ((files (directory-files (or dir default-directory)
16021 nil "\\`[^.#].*\\.org\\'"))
16022 file visiting m buffer)
16023 (catch 'found
16024 (while (setq file (pop files))
16025 (message "trying %s" file)
16026 (setq visiting (org-find-base-buffer-visiting file))
16027 (setq buffer (or visiting (find-file-noselect file)))
16028 (setq m (org-find-exact-headline-in-buffer
16029 heading buffer))
16030 (when (and (not m) (not visiting)) (kill-buffer buffer))
16031 (and m (throw 'found m))))))
16033 (defun org-find-entry-with-id (ident)
16034 "Locate the entry that contains the ID property with exact value IDENT.
16035 IDENT can be a string, a symbol or a number, this function will search for
16036 the string representation of it.
16037 Return the position where this entry starts, or nil if there is no such entry."
16038 (interactive "sID: ")
16039 (let ((id (cond
16040 ((stringp ident) ident)
16041 ((symbol-name ident) (symbol-name ident))
16042 ((numberp ident) (number-to-string ident))
16043 (t (error "IDENT %s must be a string, symbol or number" ident))))
16044 (case-fold-search nil))
16045 (save-excursion
16046 (save-restriction
16047 (widen)
16048 (goto-char (point-min))
16049 (when (re-search-forward
16050 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16051 nil t)
16052 (org-back-to-heading t)
16053 (point))))))
16055 ;;;; Timestamps
16057 (defvar org-last-changed-timestamp nil)
16058 (defvar org-last-inserted-timestamp nil
16059 "The last time stamp inserted with `org-insert-time-stamp'.")
16060 (defvar org-ts-what) ; dynamically scoped parameter
16062 (defun org-time-stamp (arg &optional inactive)
16063 "Prompt for a date/time and insert a time stamp.
16064 If the user specifies a time like HH:MM or if this command is
16065 called with at least one prefix argument, the time stamp contains
16066 the date and the time. Otherwise, only the date is be included.
16068 All parts of a date not specified by the user is filled in from
16069 the current date/time. So if you just press return without
16070 typing anything, the time stamp will represent the current
16071 date/time.
16073 If there is already a timestamp at the cursor, it will be
16074 modified.
16076 With two universal prefix arguments, insert an active timestamp
16077 with the current time without prompting the user.
16079 When called from lisp, the timestamp is inactive if INACTIVE is
16080 non-nil."
16081 (interactive "P")
16082 (let* ((ts nil)
16083 (default-time
16084 ;; Default time is either today, or, when entering a range,
16085 ;; the range start.
16086 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16087 (save-excursion
16088 (re-search-backward
16089 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16090 (- (point) 20) t)))
16091 (apply 'encode-time (org-parse-time-string (match-string 1)))
16092 (current-time)))
16093 (default-input (and ts (org-get-compact-tod ts)))
16094 (repeater (save-excursion
16095 (save-match-data
16096 (beginning-of-line)
16097 (when (re-search-forward
16098 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16099 (save-excursion (progn (end-of-line) (point))) t)
16100 (match-string 0)))))
16101 org-time-was-given org-end-time-was-given time)
16102 (cond
16103 ((and (org-at-timestamp-p t)
16104 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16105 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16106 (insert "--")
16107 (setq time (let ((this-command this-command))
16108 (org-read-date arg 'totime nil nil
16109 default-time default-input inactive)))
16110 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16111 ((org-at-timestamp-p t)
16112 (setq time (let ((this-command this-command))
16113 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16114 (when (org-at-timestamp-p t) ; just to get the match data
16115 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16116 (replace-match "")
16117 (setq org-last-changed-timestamp
16118 (org-insert-time-stamp
16119 time (or org-time-was-given arg)
16120 inactive nil nil (list org-end-time-was-given)))
16121 (when repeater (goto-char (1- (point))) (insert " " repeater)
16122 (setq org-last-changed-timestamp
16123 (concat (substring org-last-inserted-timestamp 0 -1)
16124 " " repeater ">"))))
16125 (message "Timestamp updated"))
16126 ((equal arg '(16))
16127 (org-insert-time-stamp (current-time) t inactive))
16129 (setq time (let ((this-command this-command))
16130 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16131 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16132 nil nil (list org-end-time-was-given))))))
16134 ;; FIXME: can we use this for something else, like computing time differences?
16135 (defun org-get-compact-tod (s)
16136 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16137 (let* ((t1 (match-string 1 s))
16138 (h1 (string-to-number (match-string 2 s)))
16139 (m1 (string-to-number (match-string 3 s)))
16140 (t2 (and (match-end 4) (match-string 5 s)))
16141 (h2 (and t2 (string-to-number (match-string 6 s))))
16142 (m2 (and t2 (string-to-number (match-string 7 s))))
16143 dh dm)
16144 (if (not t2)
16146 (setq dh (- h2 h1) dm (- m2 m1))
16147 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16148 (concat t1 "+" (number-to-string dh)
16149 (and (/= 0 dm) (format ":%02d" dm)))))))
16151 (defun org-time-stamp-inactive (&optional arg)
16152 "Insert an inactive time stamp.
16153 An inactive time stamp is enclosed in square brackets instead of angle
16154 brackets. It is inactive in the sense that it does not trigger agenda entries,
16155 does not link to the calendar and cannot be changed with the S-cursor keys.
16156 So these are more for recording a certain time/date."
16157 (interactive "P")
16158 (org-time-stamp arg 'inactive))
16160 (defvar org-date-ovl (make-overlay 1 1))
16161 (overlay-put org-date-ovl 'face 'org-date-selected)
16162 (org-detach-overlay org-date-ovl)
16164 (defvar org-ans1) ; dynamically scoped parameter
16165 (defvar org-ans2) ; dynamically scoped parameter
16167 (defvar org-plain-time-of-day-regexp) ; defined below
16169 (defvar org-overriding-default-time nil) ; dynamically scoped
16170 (defvar org-read-date-overlay nil)
16171 (defvar org-dcst nil) ; dynamically scoped
16172 (defvar org-read-date-history nil)
16173 (defvar org-read-date-final-answer nil)
16174 (defvar org-read-date-analyze-futurep nil)
16175 (defvar org-read-date-analyze-forced-year nil)
16176 (defvar org-read-date-inactive)
16178 (defvar org-read-date-minibuffer-local-map
16179 (let* ((org-replace-disputed-keys nil)
16180 (map (make-sparse-keymap)))
16181 (set-keymap-parent map minibuffer-local-map)
16182 (org-defkey map (kbd ".")
16183 (lambda () (interactive)
16184 ;; Are we at the beginning of the prompt?
16185 (if (looking-back "^[^:]+: ")
16186 (org-eval-in-calendar '(calendar-goto-today))
16187 (insert "."))))
16188 (org-defkey map (kbd "C-.")
16189 (lambda () (interactive)
16190 (org-eval-in-calendar '(calendar-goto-today))))
16191 (org-defkey map [(meta shift left)]
16192 (lambda () (interactive)
16193 (org-eval-in-calendar '(calendar-backward-month 1))))
16194 (org-defkey map [(meta shift right)]
16195 (lambda () (interactive)
16196 (org-eval-in-calendar '(calendar-forward-month 1))))
16197 (org-defkey map [(meta shift up)]
16198 (lambda () (interactive)
16199 (org-eval-in-calendar '(calendar-backward-year 1))))
16200 (org-defkey map [(meta shift down)]
16201 (lambda () (interactive)
16202 (org-eval-in-calendar '(calendar-forward-year 1))))
16203 (org-defkey map [?\e (shift left)]
16204 (lambda () (interactive)
16205 (org-eval-in-calendar '(calendar-backward-month 1))))
16206 (org-defkey map [?\e (shift right)]
16207 (lambda () (interactive)
16208 (org-eval-in-calendar '(calendar-forward-month 1))))
16209 (org-defkey map [?\e (shift up)]
16210 (lambda () (interactive)
16211 (org-eval-in-calendar '(calendar-backward-year 1))))
16212 (org-defkey map [?\e (shift down)]
16213 (lambda () (interactive)
16214 (org-eval-in-calendar '(calendar-forward-year 1))))
16215 (org-defkey map [(shift up)]
16216 (lambda () (interactive)
16217 (org-eval-in-calendar '(calendar-backward-week 1))))
16218 (org-defkey map [(shift down)]
16219 (lambda () (interactive)
16220 (org-eval-in-calendar '(calendar-forward-week 1))))
16221 (org-defkey map [(shift left)]
16222 (lambda () (interactive)
16223 (org-eval-in-calendar '(calendar-backward-day 1))))
16224 (org-defkey map [(shift right)]
16225 (lambda () (interactive)
16226 (org-eval-in-calendar '(calendar-forward-day 1))))
16227 (org-defkey map "!"
16228 (lambda () (interactive)
16229 (org-eval-in-calendar '(diary-view-entries))
16230 (message "")))
16231 (org-defkey map ">"
16232 (lambda () (interactive)
16233 (org-eval-in-calendar '(scroll-calendar-left 1))))
16234 (org-defkey map "<"
16235 (lambda () (interactive)
16236 (org-eval-in-calendar '(scroll-calendar-right 1))))
16237 (org-defkey map "\C-v"
16238 (lambda () (interactive)
16239 (org-eval-in-calendar
16240 '(calendar-scroll-left-three-months 1))))
16241 (org-defkey map "\M-v"
16242 (lambda () (interactive)
16243 (org-eval-in-calendar
16244 '(calendar-scroll-right-three-months 1))))
16245 map)
16246 "Keymap for minibuffer commands when using `org-read-date'.")
16248 (defvar org-def)
16249 (defvar org-defdecode)
16250 (defvar org-with-time)
16252 (defun org-read-date (&optional org-with-time to-time from-string prompt
16253 default-time default-input inactive)
16254 "Read a date, possibly a time, and make things smooth for the user.
16255 The prompt will suggest to enter an ISO date, but you can also enter anything
16256 which will at least partially be understood by `parse-time-string'.
16257 Unrecognized parts of the date will default to the current day, month, year,
16258 hour and minute. If this command is called to replace a timestamp at point,
16259 or to enter the second timestamp of a range, the default time is taken
16260 from the existing stamp. Furthermore, the command prefers the future,
16261 so if you are giving a date where the year is not given, and the day-month
16262 combination is already past in the current year, it will assume you
16263 mean next year. For details, see the manual. A few examples:
16265 3-2-5 --> 2003-02-05
16266 feb 15 --> currentyear-02-15
16267 2/15 --> currentyear-02-15
16268 sep 12 9 --> 2009-09-12
16269 12:45 --> today 12:45
16270 22 sept 0:34 --> currentyear-09-22 0:34
16271 12 --> currentyear-currentmonth-12
16272 Fri --> nearest Friday after today
16273 -Tue --> last Tuesday
16274 etc.
16276 Furthermore you can specify a relative date by giving, as the *first* thing
16277 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16278 change in days weeks, months, years.
16279 With a single plus or minus, the date is relative to today. With a double
16280 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16281 +4d --> four days from today
16282 +4 --> same as above
16283 +2w --> two weeks from today
16284 ++5 --> five days from default date
16286 The function understands only English month and weekday abbreviations.
16288 While prompting, a calendar is popped up - you can also select the
16289 date with the mouse (button 1). The calendar shows a period of three
16290 months. To scroll it to other months, use the keys `>' and `<'.
16291 If you don't like the calendar, turn it off with
16292 \(setq org-read-date-popup-calendar nil)
16294 With optional argument TO-TIME, the date will immediately be converted
16295 to an internal time.
16296 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16297 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16298 still enter a time, and this function will inform the calling routine
16299 about this change. The calling routine may then choose to change the
16300 format used to insert the time stamp into the buffer to include the time.
16301 With optional argument FROM-STRING, read from this string instead from
16302 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16303 the time/date that is used for everything that is not specified by the
16304 user."
16305 (require 'parse-time)
16306 (let* ((org-time-stamp-rounding-minutes
16307 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16308 (org-dcst org-display-custom-times)
16309 (ct (org-current-time))
16310 (org-def (or org-overriding-default-time default-time ct))
16311 (org-defdecode (decode-time org-def))
16312 (dummy (progn
16313 (when (< (nth 2 org-defdecode) org-extend-today-until)
16314 (setcar (nthcdr 2 org-defdecode) -1)
16315 (setcar (nthcdr 1 org-defdecode) 59)
16316 (setq org-def (apply 'encode-time org-defdecode)
16317 org-defdecode (decode-time org-def)))))
16318 (mouse-autoselect-window nil) ; Don't let the mouse jump
16319 (calendar-frame-setup nil)
16320 (calendar-setup nil)
16321 (calendar-move-hook nil)
16322 (calendar-view-diary-initially-flag nil)
16323 (calendar-view-holidays-initially-flag nil)
16324 (timestr (format-time-string
16325 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16326 (prompt (concat (if prompt (concat prompt " ") "")
16327 (format "Date+time [%s]: " timestr)))
16328 ans (org-ans0 "") org-ans1 org-ans2 final)
16330 (cond
16331 (from-string (setq ans from-string))
16332 (org-read-date-popup-calendar
16333 (save-excursion
16334 (save-window-excursion
16335 (calendar)
16336 (org-eval-in-calendar '(setq cursor-type nil) t)
16337 (unwind-protect
16338 (progn
16339 (calendar-forward-day (- (time-to-days org-def)
16340 (calendar-absolute-from-gregorian
16341 (calendar-current-date))))
16342 (org-eval-in-calendar nil t)
16343 (let* ((old-map (current-local-map))
16344 (map (copy-keymap calendar-mode-map))
16345 (minibuffer-local-map
16346 (copy-keymap org-read-date-minibuffer-local-map)))
16347 (org-defkey map (kbd "RET") 'org-calendar-select)
16348 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16349 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16350 (unwind-protect
16351 (progn
16352 (use-local-map map)
16353 (setq org-read-date-inactive inactive)
16354 (add-hook 'post-command-hook 'org-read-date-display)
16355 (setq org-ans0 (read-string prompt default-input
16356 'org-read-date-history nil))
16357 ;; org-ans0: from prompt
16358 ;; org-ans1: from mouse click
16359 ;; org-ans2: from calendar motion
16360 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16361 (remove-hook 'post-command-hook 'org-read-date-display)
16362 (use-local-map old-map)
16363 (when org-read-date-overlay
16364 (delete-overlay org-read-date-overlay)
16365 (setq org-read-date-overlay nil)))))
16366 (bury-buffer "*Calendar*")))))
16368 (t ; Naked prompt only
16369 (unwind-protect
16370 (setq ans (read-string prompt default-input
16371 'org-read-date-history timestr))
16372 (when org-read-date-overlay
16373 (delete-overlay org-read-date-overlay)
16374 (setq org-read-date-overlay nil)))))
16376 (setq final (org-read-date-analyze ans org-def org-defdecode))
16378 (when org-read-date-analyze-forced-year
16379 (message "Year was forced into %s"
16380 (if org-read-date-force-compatible-dates
16381 "compatible range (1970-2037)"
16382 "range representable on this machine"))
16383 (ding))
16385 ;; One round trip to get rid of 34th of August and stuff like that....
16386 (setq final (decode-time (apply 'encode-time final)))
16388 (setq org-read-date-final-answer ans)
16390 (if to-time
16391 (apply 'encode-time final)
16392 (if (and (boundp 'org-time-was-given) org-time-was-given)
16393 (format "%04d-%02d-%02d %02d:%02d"
16394 (nth 5 final) (nth 4 final) (nth 3 final)
16395 (nth 2 final) (nth 1 final))
16396 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16398 (defun org-read-date-display ()
16399 "Display the current date prompt interpretation in the minibuffer."
16400 (when org-read-date-display-live
16401 (when org-read-date-overlay
16402 (delete-overlay org-read-date-overlay))
16403 (when (minibufferp (current-buffer))
16404 (save-excursion
16405 (end-of-line 1)
16406 (while (not (equal (buffer-substring
16407 (max (point-min) (- (point) 4)) (point))
16408 " "))
16409 (insert " ")))
16410 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16411 " " (or org-ans1 org-ans2)))
16412 (org-end-time-was-given nil)
16413 (f (org-read-date-analyze ans org-def org-defdecode))
16414 (fmts (if org-dcst
16415 org-time-stamp-custom-formats
16416 org-time-stamp-formats))
16417 (fmt (if (or org-with-time
16418 (and (boundp 'org-time-was-given) org-time-was-given))
16419 (cdr fmts)
16420 (car fmts)))
16421 (txt (format-time-string fmt (apply 'encode-time f)))
16422 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16423 (txt (concat "=> " txt)))
16424 (when (and org-end-time-was-given
16425 (string-match org-plain-time-of-day-regexp txt))
16426 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16427 org-end-time-was-given
16428 (substring txt (match-end 0)))))
16429 (when org-read-date-analyze-futurep
16430 (setq txt (concat txt " (=>F)")))
16431 (setq org-read-date-overlay
16432 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16433 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16435 (defun org-read-date-analyze (ans org-def org-defdecode)
16436 "Analyze the combined answer of the date prompt."
16437 ;; FIXME: cleanup and comment
16438 (let ((nowdecode (decode-time (current-time)))
16439 delta deltan deltaw deltadef year month day
16440 hour minute second wday pm h2 m2 tl wday1
16441 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16442 (setq org-read-date-analyze-futurep nil
16443 org-read-date-analyze-forced-year nil)
16444 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16445 (setq ans "+0"))
16447 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16448 (setq ans (replace-match "" t t ans)
16449 deltan (car delta)
16450 deltaw (nth 1 delta)
16451 deltadef (nth 2 delta)))
16453 ;; Check if there is an iso week date in there. If yes, store the
16454 ;; info and postpone interpreting it until the rest of the parsing
16455 ;; is done.
16456 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16457 (setq iso-year (if (match-end 1)
16458 (org-small-year-to-year
16459 (string-to-number (match-string 1 ans))))
16460 iso-weekday (if (match-end 3)
16461 (string-to-number (match-string 3 ans)))
16462 iso-week (string-to-number (match-string 2 ans)))
16463 (setq ans (replace-match "" t t ans)))
16465 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16466 (when (string-match
16467 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16468 (setq year (if (match-end 2)
16469 (string-to-number (match-string 2 ans))
16470 (progn (setq kill-year t)
16471 (string-to-number (format-time-string "%Y"))))
16472 month (string-to-number (match-string 3 ans))
16473 day (string-to-number (match-string 4 ans)))
16474 (if (< year 100) (setq year (+ 2000 year)))
16475 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16476 t nil ans)))
16478 ;; Help matching dotted european dates
16479 (when (string-match
16480 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16481 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16482 (setq kill-year t)
16483 (string-to-number (format-time-string "%Y")))
16484 day (string-to-number (match-string 1 ans))
16485 month (string-to-number (match-string 2 ans))
16486 ans (replace-match (format "%04d-%02d-%02d" year month day)
16487 t nil ans)))
16489 ;; Help matching american dates, like 5/30 or 5/30/7
16490 (when (string-match
16491 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16492 (setq year (if (match-end 4)
16493 (string-to-number (match-string 4 ans))
16494 (progn (setq kill-year t)
16495 (string-to-number (format-time-string "%Y"))))
16496 month (string-to-number (match-string 1 ans))
16497 day (string-to-number (match-string 2 ans)))
16498 (if (< year 100) (setq year (+ 2000 year)))
16499 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16500 t nil ans)))
16501 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16502 ;; If there is a time with am/pm, and *no* time without it, we convert
16503 ;; so that matching will be successful.
16504 (loop for i from 1 to 2 do ; twice, for end time as well
16505 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16506 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16507 (setq hour (string-to-number (match-string 1 ans))
16508 minute (if (match-end 3)
16509 (string-to-number (match-string 3 ans))
16511 pm (equal ?p
16512 (string-to-char (downcase (match-string 4 ans)))))
16513 (if (and (= hour 12) (not pm))
16514 (setq hour 0)
16515 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16516 (setq ans (replace-match (format "%02d:%02d" hour minute)
16517 t t ans))))
16519 ;; Check if a time range is given as a duration
16520 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16521 (setq hour (string-to-number (match-string 1 ans))
16522 h2 (+ hour (string-to-number (match-string 3 ans)))
16523 minute (string-to-number (match-string 2 ans))
16524 m2 (+ minute (if (match-end 5) (string-to-number
16525 (match-string 5 ans))0)))
16526 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16527 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16528 t t ans)))
16530 ;; Check if there is a time range
16531 (when (boundp 'org-end-time-was-given)
16532 (setq org-time-was-given nil)
16533 (when (and (string-match org-plain-time-of-day-regexp ans)
16534 (match-end 8))
16535 (setq org-end-time-was-given (match-string 8 ans))
16536 (setq ans (concat (substring ans 0 (match-beginning 7))
16537 (substring ans (match-end 7))))))
16539 (setq tl (parse-time-string ans)
16540 day (or (nth 3 tl) (nth 3 org-defdecode))
16541 month (or (nth 4 tl)
16542 (if (and org-read-date-prefer-future
16543 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16544 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16545 (nth 4 org-defdecode)))
16546 year (or (and (not kill-year) (nth 5 tl))
16547 (if (and org-read-date-prefer-future
16548 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16549 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16550 (nth 5 org-defdecode)))
16551 hour (or (nth 2 tl) (nth 2 org-defdecode))
16552 minute (or (nth 1 tl) (nth 1 org-defdecode))
16553 second (or (nth 0 tl) 0)
16554 wday (nth 6 tl))
16556 (when (and (eq org-read-date-prefer-future 'time)
16557 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16558 (equal day (nth 3 nowdecode))
16559 (equal month (nth 4 nowdecode))
16560 (equal year (nth 5 nowdecode))
16561 (nth 2 tl)
16562 (or (< (nth 2 tl) (nth 2 nowdecode))
16563 (and (= (nth 2 tl) (nth 2 nowdecode))
16564 (nth 1 tl)
16565 (< (nth 1 tl) (nth 1 nowdecode)))))
16566 (setq day (1+ day)
16567 futurep t))
16569 ;; Special date definitions below
16570 (cond
16571 (iso-week
16572 ;; There was an iso week
16573 (require 'cal-iso)
16574 (setq futurep nil)
16575 (setq year (or iso-year year)
16576 day (or iso-weekday wday 1)
16577 wday nil ; to make sure that the trigger below does not match
16578 iso-date (calendar-gregorian-from-absolute
16579 (calendar-absolute-from-iso
16580 (list iso-week day year))))
16581 ; FIXME: Should we also push ISO weeks into the future?
16582 ; (when (and org-read-date-prefer-future
16583 ; (not iso-year)
16584 ; (< (calendar-absolute-from-gregorian iso-date)
16585 ; (time-to-days (current-time))))
16586 ; (setq year (1+ year)
16587 ; iso-date (calendar-gregorian-from-absolute
16588 ; (calendar-absolute-from-iso
16589 ; (list iso-week day year)))))
16590 (setq month (car iso-date)
16591 year (nth 2 iso-date)
16592 day (nth 1 iso-date)))
16593 (deltan
16594 (setq futurep nil)
16595 (unless deltadef
16596 (let ((now (decode-time (current-time))))
16597 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16598 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16599 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16600 ((equal deltaw "m") (setq month (+ month deltan)))
16601 ((equal deltaw "y") (setq year (+ year deltan)))))
16602 ((and wday (not (nth 3 tl)))
16603 ;; Weekday was given, but no day, so pick that day in the week
16604 ;; on or after the derived date.
16605 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16606 (unless (equal wday wday1)
16607 (setq day (+ day (% (- wday wday1 -7) 7))))))
16608 (if (and (boundp 'org-time-was-given)
16609 (nth 2 tl))
16610 (setq org-time-was-given t))
16611 (if (< year 100) (setq year (+ 2000 year)))
16612 ;; Check of the date is representable
16613 (if org-read-date-force-compatible-dates
16614 (progn
16615 (if (< year 1970)
16616 (setq year 1970 org-read-date-analyze-forced-year t))
16617 (if (> year 2037)
16618 (setq year 2037 org-read-date-analyze-forced-year t)))
16619 (condition-case nil
16620 (ignore (encode-time second minute hour day month year))
16621 (error
16622 (setq year (nth 5 org-defdecode))
16623 (setq org-read-date-analyze-forced-year t))))
16624 (setq org-read-date-analyze-futurep futurep)
16625 (list second minute hour day month year)))
16627 (defvar parse-time-weekdays)
16628 (defun org-read-date-get-relative (s today default)
16629 "Check string S for special relative date string.
16630 TODAY and DEFAULT are internal times, for today and for a default.
16631 Return shift list (N what def-flag)
16632 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16633 N is the number of WHATs to shift.
16634 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16635 the DEFAULT date rather than TODAY."
16636 (require 'parse-time)
16637 (when (and
16638 (string-match
16639 (concat
16640 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16641 "\\([0-9]+\\)?"
16642 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16643 "\\([ \t]\\|$\\)") s)
16644 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16645 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16646 (string-to-char (substring (match-string 1 s) -1))
16647 ?+))
16648 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16649 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16650 (what (if (match-end 3) (match-string 3 s) "d"))
16651 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16652 (date (if rel default today))
16653 (wday (nth 6 (decode-time date)))
16654 delta)
16655 (if wday1
16656 (progn
16657 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16658 (if (= delta 0) (setq delta 7))
16659 (if (= dir ?-)
16660 (progn
16661 (setq delta (- delta 7))
16662 (if (= delta 0) (setq delta -7))))
16663 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16664 (list delta "d" rel))
16665 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16667 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16668 "Turn a user-specified date into the internal representation.
16669 The internal representation needed by the calendar is (month day year).
16670 This is a wrapper to handle the brain-dead convention in calendar that
16671 user function argument order change dependent on argument order."
16672 (if (boundp 'calendar-date-style)
16673 (cond
16674 ((eq calendar-date-style 'american)
16675 (list arg1 arg2 arg3))
16676 ((eq calendar-date-style 'european)
16677 (list arg2 arg1 arg3))
16678 ((eq calendar-date-style 'iso)
16679 (list arg2 arg3 arg1)))
16680 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16681 (if (org-bound-and-true-p european-calendar-style)
16682 (list arg2 arg1 arg3)
16683 (list arg1 arg2 arg3)))))
16685 (defun org-eval-in-calendar (form &optional keepdate)
16686 "Eval FORM in the calendar window and return to current window.
16687 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16688 otherwise stick to the current value of `org-ans2'."
16689 (let ((sf (selected-frame))
16690 (sw (selected-window)))
16691 (select-window (get-buffer-window "*Calendar*" t))
16692 (eval form)
16693 (when (and (not keepdate) (calendar-cursor-to-date))
16694 (let* ((date (calendar-cursor-to-date))
16695 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16696 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16697 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16698 (select-window sw)
16699 (org-select-frame-set-input-focus sf)))
16701 (defun org-calendar-select ()
16702 "Return to `org-read-date' with the date currently selected.
16703 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16704 (interactive)
16705 (when (calendar-cursor-to-date)
16706 (let* ((date (calendar-cursor-to-date))
16707 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16708 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16709 (if (active-minibuffer-window) (exit-minibuffer))))
16711 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16712 "Insert a date stamp for the date given by the internal TIME.
16713 WITH-HM means use the stamp format that includes the time of the day.
16714 INACTIVE means use square brackets instead of angular ones, so that the
16715 stamp will not contribute to the agenda.
16716 PRE and POST are optional strings to be inserted before and after the
16717 stamp.
16718 The command returns the inserted time stamp."
16719 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16720 stamp)
16721 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16722 (insert-before-markers (or pre ""))
16723 (when (listp extra)
16724 (setq extra (car extra))
16725 (if (and (stringp extra)
16726 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16727 (setq extra (format "-%02d:%02d"
16728 (string-to-number (match-string 1 extra))
16729 (string-to-number (match-string 2 extra))))
16730 (setq extra nil)))
16731 (when extra
16732 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16733 (insert-before-markers (setq stamp (format-time-string fmt time)))
16734 (insert-before-markers (or post ""))
16735 (setq org-last-inserted-timestamp stamp)))
16737 (defun org-toggle-time-stamp-overlays ()
16738 "Toggle the use of custom time stamp formats."
16739 (interactive)
16740 (setq org-display-custom-times (not org-display-custom-times))
16741 (unless org-display-custom-times
16742 (let ((p (point-min)) (bmp (buffer-modified-p)))
16743 (while (setq p (next-single-property-change p 'display))
16744 (if (and (get-text-property p 'display)
16745 (eq (get-text-property p 'face) 'org-date))
16746 (remove-text-properties
16747 p (setq p (next-single-property-change p 'display))
16748 '(display t))))
16749 (set-buffer-modified-p bmp)))
16750 (if (featurep 'xemacs)
16751 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16752 (org-restart-font-lock)
16753 (setq org-table-may-need-update t)
16754 (if org-display-custom-times
16755 (message "Time stamps are overlaid with custom format")
16756 (message "Time stamp overlays removed")))
16758 (defun org-display-custom-time (beg end)
16759 "Overlay modified time stamp format over timestamp between BEG and END."
16760 (let* ((ts (buffer-substring beg end))
16761 t1 w1 with-hm tf time str w2 (off 0))
16762 (save-match-data
16763 (setq t1 (org-parse-time-string ts t))
16764 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16765 (setq off (- (match-end 0) (match-beginning 0)))))
16766 (setq end (- end off))
16767 (setq w1 (- end beg)
16768 with-hm (and (nth 1 t1) (nth 2 t1))
16769 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16770 time (org-fix-decoded-time t1)
16771 str (org-add-props
16772 (format-time-string
16773 (substring tf 1 -1) (apply 'encode-time time))
16774 nil 'mouse-face 'highlight)
16775 w2 (length str))
16776 (if (not (= w2 w1))
16777 (add-text-properties (1+ beg) (+ 2 beg)
16778 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16779 (if (featurep 'xemacs)
16780 (progn
16781 (put-text-property beg end 'invisible t)
16782 (put-text-property beg end 'end-glyph (make-glyph str)))
16783 (put-text-property beg end 'display str))))
16785 (defun org-translate-time (string)
16786 "Translate all timestamps in STRING to custom format.
16787 But do this only if the variable `org-display-custom-times' is set."
16788 (when org-display-custom-times
16789 (save-match-data
16790 (let* ((start 0)
16791 (re org-ts-regexp-both)
16792 t1 with-hm inactive tf time str beg end)
16793 (while (setq start (string-match re string start))
16794 (setq beg (match-beginning 0)
16795 end (match-end 0)
16796 t1 (save-match-data
16797 (org-parse-time-string (substring string beg end) t))
16798 with-hm (and (nth 1 t1) (nth 2 t1))
16799 inactive (equal (substring string beg (1+ beg)) "[")
16800 tf (funcall (if with-hm 'cdr 'car)
16801 org-time-stamp-custom-formats)
16802 time (org-fix-decoded-time t1)
16803 str (format-time-string
16804 (concat
16805 (if inactive "[" "<") (substring tf 1 -1)
16806 (if inactive "]" ">"))
16807 (apply 'encode-time time))
16808 string (replace-match str t t string)
16809 start (+ start (length str)))))))
16810 string)
16812 (defun org-fix-decoded-time (time)
16813 "Set 0 instead of nil for the first 6 elements of time.
16814 Don't touch the rest."
16815 (let ((n 0))
16816 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16818 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16820 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16821 "Difference between TIMESTAMP-STRING and now in days.
16822 If SECONDS is non-nil, return the difference in seconds."
16823 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16824 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16825 (funcall fdiff (current-time)))))
16827 (defun org-deadline-close (timestamp-string &optional ndays)
16828 "Is the time in TIMESTAMP-STRING close to the current date?"
16829 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16830 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16831 (not (org-entry-is-done-p))))
16833 (defun org-get-wdays (ts &optional delay zero-delay)
16834 "Get the deadline lead time appropriate for timestring TS.
16835 When DELAY is non-nil, get the delay time for scheduled items
16836 instead of the deadline lead time. When ZERO-DELAY is non-nil
16837 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16838 don't try to find the delay cookie in the scheduled timestamp."
16839 (let ((tv (if delay org-scheduled-delay-days
16840 org-deadline-warning-days)))
16841 (cond
16842 ((or (and delay (< tv 0))
16843 (and delay zero-delay (<= tv 0))
16844 (and (not delay) (<= tv 0)))
16845 ;; Enforce this value no matter what
16846 (- tv))
16847 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16848 ;; lead time is specified.
16849 (floor (* (string-to-number (match-string 1 ts))
16850 (cdr (assoc (match-string 2 ts)
16851 '(("d" . 1) ("w" . 7)
16852 ("m" . 30.4) ("y" . 365.25)
16853 ("h" . 0.041667)))))))
16854 ;; go for the default.
16855 (t tv))))
16857 (defun org-calendar-select-mouse (ev)
16858 "Return to `org-read-date' with the date currently selected.
16859 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16860 (interactive "e")
16861 (mouse-set-point ev)
16862 (when (calendar-cursor-to-date)
16863 (let* ((date (calendar-cursor-to-date))
16864 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16865 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16866 (if (active-minibuffer-window) (exit-minibuffer))))
16868 (defun org-check-deadlines (ndays)
16869 "Check if there are any deadlines due or past due.
16870 A deadline is considered due if it happens within `org-deadline-warning-days'
16871 days from today's date. If the deadline appears in an entry marked DONE,
16872 it is not shown. The prefix arg NDAYS can be used to test that many
16873 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16874 (interactive "P")
16875 (let* ((org-warn-days
16876 (cond
16877 ((equal ndays '(4)) 100000)
16878 (ndays (prefix-numeric-value ndays))
16879 (t (abs org-deadline-warning-days))))
16880 (case-fold-search nil)
16881 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16882 (callback
16883 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16885 (message "%d deadlines past-due or due within %d days"
16886 (org-occur regexp nil callback)
16887 org-warn-days)))
16889 (defsubst org-re-timestamp (type)
16890 "Return a regexp for timestamp TYPE.
16891 Allowed values for TYPE are:
16893 all: all timestamps
16894 active: only active timestamps (<...>)
16895 inactive: only inactive timestamps ([...])
16896 scheduled: only scheduled timestamps
16897 deadline: only deadline timestamps
16898 closed: only closed time-stamps
16900 When TYPE is nil, fall back on returning a regexp that matches
16901 both scheduled and deadline timestamps."
16902 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16903 ((eq type 'active) org-ts-regexp)
16904 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16905 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16906 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16907 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
16908 ((eq type 'scheduled-or-deadline)
16909 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16911 (defun org-check-before-date (date)
16912 "Check if there are deadlines or scheduled entries before DATE."
16913 (interactive (list (org-read-date)))
16914 (let ((case-fold-search nil)
16915 (regexp (org-re-timestamp org-ts-type))
16916 (callback
16917 (lambda () (time-less-p
16918 (org-time-string-to-time (match-string 1))
16919 (org-time-string-to-time date)))))
16920 (message "%d entries before %s"
16921 (org-occur regexp nil callback) date)))
16923 (defun org-check-after-date (date)
16924 "Check if there are deadlines or scheduled entries after DATE."
16925 (interactive (list (org-read-date)))
16926 (let ((case-fold-search nil)
16927 (regexp (org-re-timestamp org-ts-type))
16928 (callback
16929 (lambda () (not
16930 (time-less-p
16931 (org-time-string-to-time (match-string 1))
16932 (org-time-string-to-time date))))))
16933 (message "%d entries after %s"
16934 (org-occur regexp nil callback) date)))
16936 (defun org-check-dates-range (start-date end-date)
16937 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16938 (interactive (list (org-read-date nil nil nil "Range starts")
16939 (org-read-date nil nil nil "Range end")))
16940 (let ((case-fold-search nil)
16941 (regexp (org-re-timestamp org-ts-type))
16942 (callback
16943 (lambda ()
16944 (let ((match (match-string 1)))
16945 (and
16946 (not (time-less-p
16947 (org-time-string-to-time match)
16948 (org-time-string-to-time start-date)))
16949 (time-less-p
16950 (org-time-string-to-time match)
16951 (org-time-string-to-time end-date)))))))
16952 (message "%d entries between %s and %s"
16953 (org-occur regexp nil callback) start-date end-date)))
16955 (defun org-evaluate-time-range (&optional to-buffer)
16956 "Evaluate a time range by computing the difference between start and end.
16957 Normally the result is just printed in the echo area, but with prefix arg
16958 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16959 If the time range is actually in a table, the result is inserted into the
16960 next column.
16961 For time difference computation, a year is assumed to be exactly 365
16962 days in order to avoid rounding problems."
16963 (interactive "P")
16965 (org-clock-update-time-maybe)
16966 (save-excursion
16967 (unless (org-at-date-range-p t)
16968 (goto-char (point-at-bol))
16969 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16970 (if (not (org-at-date-range-p t))
16971 (user-error "Not at a time-stamp range, and none found in current line")))
16972 (let* ((ts1 (match-string 1))
16973 (ts2 (match-string 2))
16974 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16975 (match-end (match-end 0))
16976 (time1 (org-time-string-to-time ts1))
16977 (time2 (org-time-string-to-time ts2))
16978 (t1 (org-float-time time1))
16979 (t2 (org-float-time time2))
16980 (diff (abs (- t2 t1)))
16981 (negative (< (- t2 t1) 0))
16982 ;; (ys (floor (* 365 24 60 60)))
16983 (ds (* 24 60 60))
16984 (hs (* 60 60))
16985 (fy "%dy %dd %02d:%02d")
16986 (fy1 "%dy %dd")
16987 (fd "%dd %02d:%02d")
16988 (fd1 "%dd")
16989 (fh "%02d:%02d")
16990 y d h m align)
16991 (if havetime
16992 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16994 d (floor (/ diff ds)) diff (mod diff ds)
16995 h (floor (/ diff hs)) diff (mod diff hs)
16996 m (floor (/ diff 60)))
16997 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16999 d (floor (+ (/ diff ds) 0.5))
17000 h 0 m 0))
17001 (if (not to-buffer)
17002 (message "%s" (org-make-tdiff-string y d h m))
17003 (if (org-at-table-p)
17004 (progn
17005 (goto-char match-end)
17006 (setq align t)
17007 (and (looking-at " *|") (goto-char (match-end 0))))
17008 (goto-char match-end))
17009 (if (looking-at
17010 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17011 (replace-match ""))
17012 (if negative (insert " -"))
17013 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17014 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17015 (insert " " (format fh h m))))
17016 (if align (org-table-align))
17017 (message "Time difference inserted")))))
17019 (defun org-make-tdiff-string (y d h m)
17020 (let ((fmt "")
17021 (l nil))
17022 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
17023 l (push y l)))
17024 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
17025 l (push d l)))
17026 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
17027 l (push h l)))
17028 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
17029 l (push m l)))
17030 (apply 'format fmt (nreverse l))))
17032 (defun org-time-string-to-time (s &optional buffer pos)
17033 "Convert a timestamp string into internal time."
17034 (condition-case errdata
17035 (apply 'encode-time (org-parse-time-string s))
17036 (error (error "Bad timestamp `%s'%s\nError was: %s"
17037 s (if (not (and buffer pos))
17039 (format " at %d in buffer `%s'" pos buffer))
17040 (cdr errdata)))))
17042 (defun org-time-string-to-seconds (s)
17043 "Convert a timestamp string to a number of seconds."
17044 (org-float-time (org-time-string-to-time s)))
17046 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17047 "Convert a time stamp to an absolute day number.
17048 If there is a specifier for a cyclic time stamp, get the closest
17049 date to DAYNR.
17050 PREFER and SHOW-ALL are passed through to `org-closest-date'.
17051 The variable `date' is bound by the calendar when this is called."
17052 (cond
17053 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17054 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17055 daynr
17056 (+ daynr 1000)))
17057 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
17058 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17059 (time-to-days (current-time))) (match-string 0 s)
17060 prefer show-all))
17061 (t (time-to-days
17062 (condition-case errdata
17063 (apply 'encode-time (org-parse-time-string s))
17064 (error (error "Bad timestamp `%s'%s\nError was: %s"
17065 s (if (not (and buffer pos))
17067 (format " at %d in buffer `%s'" pos buffer))
17068 (cdr errdata))))))))
17070 (defun org-days-to-iso-week (days)
17071 "Return the iso week number."
17072 (require 'cal-iso)
17073 (car (calendar-iso-from-absolute days)))
17075 (defun org-small-year-to-year (year)
17076 "Convert 2-digit years into 4-digit years.
17077 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
17078 The year 2000 cannot be abbreviated. Any year larger than 99
17079 is returned unchanged."
17080 (if (< year 38)
17081 (setq year (+ 2000 year))
17082 (if (< year 100)
17083 (setq year (+ 1900 year))))
17084 year)
17086 (defun org-time-from-absolute (d)
17087 "Return the time corresponding to date D.
17088 D may be an absolute day number, or a calendar-type list (month day year)."
17089 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17090 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17092 (defun org-calendar-holiday ()
17093 "List of holidays, for Diary display in Org-mode."
17094 (require 'holidays)
17095 (let ((hl (funcall
17096 (if (fboundp 'calendar-check-holidays)
17097 'calendar-check-holidays 'check-calendar-holidays) date)))
17098 (if hl (mapconcat 'identity hl "; "))))
17100 (defun org-diary-sexp-entry (sexp entry date)
17101 "Process a SEXP diary ENTRY for DATE."
17102 (require 'diary-lib)
17103 (let ((result (if calendar-debug-sexp
17104 (let ((stack-trace-on-error t))
17105 (eval (car (read-from-string sexp))))
17106 (condition-case nil
17107 (eval (car (read-from-string sexp)))
17108 (error
17109 (beep)
17110 (message "Bad sexp at line %d in %s: %s"
17111 (org-current-line)
17112 (buffer-file-name) sexp)
17113 (sleep-for 2))))))
17114 (cond ((stringp result) (split-string result "; "))
17115 ((and (consp result)
17116 (not (consp (cdr result)))
17117 (stringp (cdr result))) (cdr result))
17118 ((and (consp result)
17119 (stringp (car result))) result)
17120 (result entry))))
17122 (defun org-diary-to-ical-string (frombuf)
17123 "Get iCalendar entries from diary entries in buffer FROMBUF.
17124 This uses the icalendar.el library."
17125 (let* ((tmpdir (if (featurep 'xemacs)
17126 (temp-directory)
17127 temporary-file-directory))
17128 (tmpfile (make-temp-name
17129 (expand-file-name "orgics" tmpdir)))
17130 buf rtn b e)
17131 (with-current-buffer frombuf
17132 (icalendar-export-region (point-min) (point-max) tmpfile)
17133 (setq buf (find-buffer-visiting tmpfile))
17134 (set-buffer buf)
17135 (goto-char (point-min))
17136 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17137 (setq b (match-beginning 0)))
17138 (goto-char (point-max))
17139 (if (re-search-backward "^END:VEVENT" nil t)
17140 (setq e (match-end 0)))
17141 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17142 (kill-buffer buf)
17143 (delete-file tmpfile)
17144 rtn))
17146 (defun org-closest-date (start current change prefer show-all)
17147 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17148 When PREFER is `past', return a date that is either CURRENT or past.
17149 When PREFER is `future', return a date that is either CURRENT or future.
17150 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17151 ;; Make the proper lists from the dates
17152 (catch 'exit
17153 (let ((a1 '(("h" . hour)
17154 ("d" . day)
17155 ("w" . week)
17156 ("m" . month)
17157 ("y" . year)))
17158 (shour (nth 2 (org-parse-time-string start)))
17159 dn dw sday cday n1 n2 n0
17160 d m y y1 y2 date1 date2 nmonths nm ny m2)
17162 (setq start (org-date-to-gregorian start)
17163 current (org-date-to-gregorian
17164 (if show-all
17165 current
17166 (time-to-days (current-time))))
17167 sday (calendar-absolute-from-gregorian start)
17168 cday (calendar-absolute-from-gregorian current))
17170 (if (<= cday sday) (throw 'exit sday))
17172 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17173 (setq dn (string-to-number (match-string 1 change))
17174 dw (cdr (assoc (match-string 2 change) a1)))
17175 (user-error "Invalid change specifier: %s" change))
17176 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17177 (cond
17178 ((eq dw 'hour)
17179 (let ((missing-hours
17180 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17181 dn)))
17182 (setq n1 (if (zerop missing-hours) cday
17183 (- cday (1+ (floor (/ missing-hours 24)))))
17184 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17185 ((eq dw 'day)
17186 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17187 n2 (+ n1 dn)))
17188 ((eq dw 'year)
17189 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17190 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17191 (setq date1 (list m d y1)
17192 n1 (calendar-absolute-from-gregorian date1)
17193 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17194 n2 (calendar-absolute-from-gregorian date2)))
17195 ((eq dw 'month)
17196 ;; approx number of month between the two dates
17197 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17198 ;; How often does dn fit in there?
17199 (setq d (nth 1 start) m (car start) y (nth 2 start)
17200 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17201 m (+ m nm)
17202 ny (floor (/ m 12))
17203 y (+ y ny)
17204 m (- m (* ny 12)))
17205 (while (> m 12) (setq m (- m 12) y (1+ y)))
17206 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17207 (setq m2 (+ m dn) y2 y)
17208 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17209 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17210 (while (<= n2 cday)
17211 (setq n1 n2 m m2 y y2)
17212 (setq m2 (+ m dn) y2 y)
17213 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17214 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17215 ;; Make sure n1 is the earlier date
17216 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17217 (if show-all
17218 (cond
17219 ((eq prefer 'past) (if (= cday n2) n2 n1))
17220 ((eq prefer 'future) (if (= cday n1) n1 n2))
17221 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17222 (cond
17223 ((eq prefer 'past) (if (= cday n2) n2 n1))
17224 ((eq prefer 'future) (if (= cday n1) n1 n2))
17225 (t (if (= cday n1) n1 n2)))))))
17227 (defun org-date-to-gregorian (date)
17228 "Turn any specification of DATE into a Gregorian date for the calendar."
17229 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17230 ((and (listp date) (= (length date) 3)) date)
17231 ((stringp date)
17232 (setq date (org-parse-time-string date))
17233 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17234 ((listp date)
17235 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17237 (defun org-parse-time-string (s &optional nodefault)
17238 "Parse the standard Org-mode time string.
17239 This should be a lot faster than the normal `parse-time-string'.
17240 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17241 hour and minute fields will be nil if not given."
17242 (cond ((string-match org-ts-regexp0 s)
17243 (list 0
17244 (if (or (match-beginning 8) (not nodefault))
17245 (string-to-number (or (match-string 8 s) "0")))
17246 (if (or (match-beginning 7) (not nodefault))
17247 (string-to-number (or (match-string 7 s) "0")))
17248 (string-to-number (match-string 4 s))
17249 (string-to-number (match-string 3 s))
17250 (string-to-number (match-string 2 s))
17251 nil nil nil))
17252 ((string-match "^<[^>]+>$" s)
17253 (decode-time (seconds-to-time (org-matcher-time s))))
17254 (t (error "Not a standard Org-mode time string: %s" s))))
17256 (defun org-timestamp-up (&optional arg)
17257 "Increase the date item at the cursor by one.
17258 If the cursor is on the year, change the year. If it is on the month,
17259 the day or the time, change that.
17260 With prefix ARG, change by that many units."
17261 (interactive "p")
17262 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17264 (defun org-timestamp-down (&optional arg)
17265 "Decrease the date item at the cursor by one.
17266 If the cursor is on the year, change the year. If it is on the month,
17267 the day or the time, change that.
17268 With prefix ARG, change by that many units."
17269 (interactive "p")
17270 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17272 (defun org-timestamp-up-day (&optional arg)
17273 "Increase the date in the time stamp by one day.
17274 With prefix ARG, change that many days."
17275 (interactive "p")
17276 (if (and (not (org-at-timestamp-p t))
17277 (org-at-heading-p))
17278 (org-todo 'up)
17279 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17281 (defun org-timestamp-down-day (&optional arg)
17282 "Decrease the date in the time stamp by one day.
17283 With prefix ARG, change that many days."
17284 (interactive "p")
17285 (if (and (not (org-at-timestamp-p t))
17286 (org-at-heading-p))
17287 (org-todo 'down)
17288 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17290 (defun org-at-timestamp-p (&optional inactive-ok)
17291 "Determine if the cursor is in or at a timestamp."
17292 (interactive)
17293 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17294 (pos (point))
17295 (ans (or (looking-at tsr)
17296 (save-excursion
17297 (skip-chars-backward "^[<\n\r\t")
17298 (if (> (point) (point-min)) (backward-char 1))
17299 (and (looking-at tsr)
17300 (> (- (match-end 0) pos) -1))))))
17301 (and ans
17302 (boundp 'org-ts-what)
17303 (setq org-ts-what
17304 (cond
17305 ((= pos (match-beginning 0)) 'bracket)
17306 ;; Point is considered to be "on the bracket" whether
17307 ;; it's really on it or right after it.
17308 ((= pos (1- (match-end 0))) 'bracket)
17309 ((= pos (match-end 0)) 'after)
17310 ((org-pos-in-match-range pos 2) 'year)
17311 ((org-pos-in-match-range pos 3) 'month)
17312 ((org-pos-in-match-range pos 7) 'hour)
17313 ((org-pos-in-match-range pos 8) 'minute)
17314 ((or (org-pos-in-match-range pos 4)
17315 (org-pos-in-match-range pos 5)) 'day)
17316 ((and (> pos (or (match-end 8) (match-end 5)))
17317 (< pos (match-end 0)))
17318 (- pos (or (match-end 8) (match-end 5))))
17319 (t 'day))))
17320 ans))
17322 (defun org-toggle-timestamp-type ()
17323 "Toggle the type (<active> or [inactive]) of a time stamp."
17324 (interactive)
17325 (when (org-at-timestamp-p t)
17326 (let ((beg (match-beginning 0)) (end (match-end 0))
17327 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17328 (save-excursion
17329 (goto-char beg)
17330 (while (re-search-forward "[][<>]" end t)
17331 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17332 t t)))
17333 (message "Timestamp is now %sactive"
17334 (if (equal (char-after beg) ?<) "" "in")))))
17336 (defun org-at-clock-log-p nil
17337 "Is the cursor on the clock log line?"
17338 (save-excursion
17339 (move-beginning-of-line 1)
17340 (looking-at "^[ \t]*CLOCK:")))
17342 (defvar org-clock-history) ; defined in org-clock.el
17343 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17344 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17345 "Change the date in the time stamp at point.
17346 The date will be changed by N times WHAT. WHAT can be `day', `month',
17347 `year', `minute', `second'. If WHAT is not given, the cursor position
17348 in the timestamp determines what will be changed.
17349 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17350 (let ((origin (point)) origin-cat
17351 with-hm inactive
17352 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17353 org-ts-what
17354 extra rem
17355 ts time time0 fixnext clrgx)
17356 (if (not (org-at-timestamp-p t))
17357 (user-error "Not at a timestamp"))
17358 (if (and (not what) (eq org-ts-what 'bracket))
17359 (org-toggle-timestamp-type)
17360 ;; Point isn't on brackets. Remember the part of the time-stamp
17361 ;; the point was in. Indeed, size of time-stamps may change,
17362 ;; but point must be kept in the same category nonetheless.
17363 (setq origin-cat org-ts-what)
17364 (if (and (not what) (not (eq org-ts-what 'day))
17365 org-display-custom-times
17366 (get-text-property (point) 'display)
17367 (not (get-text-property (1- (point)) 'display)))
17368 (setq org-ts-what 'day))
17369 (setq org-ts-what (or what org-ts-what)
17370 inactive (= (char-after (match-beginning 0)) ?\[)
17371 ts (match-string 0))
17372 (replace-match "")
17373 (when (string-match
17374 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17376 (setq extra (match-string 1 ts))
17377 (if suppress-tmp-delay
17378 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17379 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17380 (setq with-hm t))
17381 (setq time0 (org-parse-time-string ts))
17382 (when (and updown
17383 (eq org-ts-what 'minute)
17384 (not current-prefix-arg))
17385 ;; This looks like s-up and s-down. Change by one rounding step.
17386 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17387 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17388 (setcar (cdr time0) (+ (nth 1 time0)
17389 (if (> n 0) (- rem) (- dm rem))))))
17390 (setq time
17391 (encode-time (or (car time0) 0)
17392 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17393 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17394 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17395 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17396 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17397 (nthcdr 6 time0)))
17398 (when (and (member org-ts-what '(hour minute))
17399 extra
17400 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17401 (setq extra (org-modify-ts-extra
17402 extra
17403 (if (eq org-ts-what 'hour) 2 5)
17404 n dm)))
17405 (when (integerp org-ts-what)
17406 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17407 (if (eq what 'calendar)
17408 (let ((cal-date (org-get-date-from-calendar)))
17409 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17410 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17411 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17412 (setcar time0 (or (car time0) 0))
17413 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17414 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17415 (setq time (apply 'encode-time time0))))
17416 ;; Insert the new time-stamp, and ensure point stays in the same
17417 ;; category as before (i.e. not after the last position in that
17418 ;; category).
17419 (let ((pos (point)))
17420 ;; Stay before inserted string. `save-excursion' is of no use.
17421 (setq org-last-changed-timestamp
17422 (org-insert-time-stamp time with-hm inactive nil nil extra))
17423 (goto-char pos))
17424 (save-match-data
17425 (looking-at org-ts-regexp3)
17426 (goto-char (cond
17427 ;; `day' category ends before `hour' if any, or at
17428 ;; the end of the day name.
17429 ((eq origin-cat 'day)
17430 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17431 ((eq origin-cat 'hour) (min (match-end 7) origin))
17432 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17433 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17434 ;; `year' and `month' have both fixed size: point
17435 ;; couldn't have moved into another part.
17436 (t origin))))
17437 ;; Update clock if on a CLOCK line.
17438 (org-clock-update-time-maybe)
17439 ;; Maybe adjust the closest clock in `org-clock-history'
17440 (when org-clock-adjust-closest
17441 (if (not (and (org-at-clock-log-p)
17442 (< 1 (length (delq nil (mapcar 'marker-position
17443 org-clock-history))))))
17444 (message "No clock to adjust")
17445 (cond ((save-excursion ; fix previous clock?
17446 (re-search-backward org-ts-regexp0 nil t)
17447 (org-looking-back (concat org-clock-string " \\[")))
17448 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17449 ((save-excursion ; fix next clock?
17450 (re-search-backward org-ts-regexp0 nil t)
17451 (looking-at (concat org-ts-regexp0 "\\] =>")))
17452 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17453 (save-window-excursion
17454 ;; Find closest clock to point, adjust the previous/next one in history
17455 (let* ((p (save-excursion (org-back-to-heading t)))
17456 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17457 (clfixnth
17458 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17459 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17460 (if (not clfixpos)
17461 (message "No clock to adjust")
17462 (save-excursion
17463 (org-goto-marker-or-bmk clfixpos)
17464 (org-show-subtree)
17465 (when (re-search-forward clrgx nil t)
17466 (goto-char (match-beginning 1))
17467 (let (org-clock-adjust-closest)
17468 (org-timestamp-change n org-ts-what updown))
17469 (message "Clock adjusted in %s for heading: %s"
17470 (file-name-nondirectory (buffer-file-name))
17471 (org-get-heading t t)))))))))
17472 ;; Try to recenter the calendar window, if any.
17473 (if (and org-calendar-follow-timestamp-change
17474 (get-buffer-window "*Calendar*" t)
17475 (memq org-ts-what '(day month year)))
17476 (org-recenter-calendar (time-to-days time))))))
17478 (defun org-modify-ts-extra (s pos n dm)
17479 "Change the different parts of the lead-time and repeat fields in timestamp."
17480 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17481 ng h m new rem)
17482 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17483 (cond
17484 ((or (org-pos-in-match-range pos 2)
17485 (org-pos-in-match-range pos 3))
17486 (setq m (string-to-number (match-string 3 s))
17487 h (string-to-number (match-string 2 s)))
17488 (if (org-pos-in-match-range pos 2)
17489 (setq h (+ h n))
17490 (setq n (* dm (org-no-warnings (signum n))))
17491 (when (not (= 0 (setq rem (% m dm))))
17492 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17493 (setq m (+ m n)))
17494 (if (< m 0) (setq m (+ m 60) h (1- h)))
17495 (if (> m 59) (setq m (- m 60) h (1+ h)))
17496 (setq h (min 24 (max 0 h)))
17497 (setq ng 1 new (format "-%02d:%02d" h m)))
17498 ((org-pos-in-match-range pos 6)
17499 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17500 ((org-pos-in-match-range pos 5)
17501 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17503 ((org-pos-in-match-range pos 9)
17504 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17505 ((org-pos-in-match-range pos 8)
17506 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17508 (when ng
17509 (setq s (concat
17510 (substring s 0 (match-beginning ng))
17512 (substring s (match-end ng))))))
17515 (defun org-recenter-calendar (date)
17516 "If the calendar is visible, recenter it to DATE."
17517 (let ((cwin (get-buffer-window "*Calendar*" t)))
17518 (when cwin
17519 (let ((calendar-move-hook nil))
17520 (with-selected-window cwin
17521 (calendar-goto-date (if (listp date) date
17522 (calendar-gregorian-from-absolute date))))))))
17524 (defun org-goto-calendar (&optional arg)
17525 "Go to the Emacs calendar at the current date.
17526 If there is a time stamp in the current line, go to that date.
17527 A prefix ARG can be used to force the current date."
17528 (interactive "P")
17529 (let ((tsr org-ts-regexp) diff
17530 (calendar-move-hook nil)
17531 (calendar-view-holidays-initially-flag nil)
17532 (calendar-view-diary-initially-flag nil))
17533 (if (or (org-at-timestamp-p)
17534 (save-excursion
17535 (beginning-of-line 1)
17536 (looking-at (concat ".*" tsr))))
17537 (let ((d1 (time-to-days (current-time)))
17538 (d2 (time-to-days
17539 (org-time-string-to-time (match-string 1)))))
17540 (setq diff (- d2 d1))))
17541 (calendar)
17542 (calendar-goto-today)
17543 (if (and diff (not arg)) (calendar-forward-day diff))))
17545 (defun org-get-date-from-calendar ()
17546 "Return a list (month day year) of date at point in calendar."
17547 (with-current-buffer "*Calendar*"
17548 (save-match-data
17549 (calendar-cursor-to-date))))
17551 (defun org-date-from-calendar ()
17552 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17553 If there is already a time stamp at the cursor position, update it."
17554 (interactive)
17555 (if (org-at-timestamp-p t)
17556 (org-timestamp-change 0 'calendar)
17557 (let ((cal-date (org-get-date-from-calendar)))
17558 (org-insert-time-stamp
17559 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17561 (defcustom org-effort-durations
17562 `(("h" . 60)
17563 ("d" . ,(* 60 8))
17564 ("w" . ,(* 60 8 5))
17565 ("m" . ,(* 60 8 5 4))
17566 ("y" . ,(* 60 8 5 40)))
17567 "Conversion factor to minutes for an effort modifier.
17569 Each entry has the form (MODIFIER . MINUTES).
17571 In an effort string, a number followed by MODIFIER is multiplied
17572 by the specified number of MINUTES to obtain an effort in
17573 minutes.
17575 For example, if the value of this variable is ((\"hours\" . 60)), then an
17576 effort string \"2hours\" is equivalent to 120 minutes."
17577 :group 'org-agenda
17578 :version "24.1"
17579 :type '(alist :key-type (string :tag "Modifier")
17580 :value-type (number :tag "Minutes")))
17582 (defun org-minutes-to-clocksum-string (m)
17583 "Format number of minutes as a clocksum string.
17584 The format is determined by `org-time-clocksum-format',
17585 `org-time-clocksum-use-fractional' and
17586 `org-time-clocksum-fractional-format' and
17587 `org-time-clocksum-use-effort-durations'."
17588 (let ((clocksum "")
17589 (m (round m)) ; Don't allow fractions of minutes
17590 h d w mo y fmt n)
17591 (setq h (if org-time-clocksum-use-effort-durations
17592 (cdr (assoc "h" org-effort-durations)) 60)
17593 d (if org-time-clocksum-use-effort-durations
17594 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17595 w (if org-time-clocksum-use-effort-durations
17596 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17597 mo (if org-time-clocksum-use-effort-durations
17598 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17599 y (if org-time-clocksum-use-effort-durations
17600 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17601 ;; fractional format
17602 (if org-time-clocksum-use-fractional
17603 (cond
17604 ;; single format string
17605 ((stringp org-time-clocksum-fractional-format)
17606 (format org-time-clocksum-fractional-format (/ m (float h))))
17607 ;; choice of fractional formats for different time units
17608 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17609 (> (/ (truncate m) (* y d h)) 0))
17610 (format fmt (/ m (* y d (float h)))))
17611 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17612 (> (/ (truncate m) (* mo d h)) 0))
17613 (format fmt (/ m (* mo d (float h)))))
17614 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17615 (> (/ (truncate m) (* w d h)) 0))
17616 (format fmt (/ m (* w d (float h)))))
17617 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17618 (> (/ (truncate m) (* d h)) 0))
17619 (format fmt (/ m (* d (float h)))))
17620 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17621 (> (/ (truncate m) h) 0))
17622 (format fmt (/ m (float h))))
17623 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17624 (format fmt m))
17625 ;; fall back to smallest time unit with a format
17626 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17627 (format fmt (/ m (float h))))
17628 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17629 (format fmt (/ m (* d (float h)))))
17630 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17631 (format fmt (/ m (* w d (float h)))))
17632 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17633 (format fmt (/ m (* mo d (float h)))))
17634 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17635 (format fmt (/ m (* y d (float h))))))
17636 ;; standard (non-fractional) format, with single format string
17637 (if (stringp org-time-clocksum-format)
17638 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17639 ;; separate formats components
17640 (and (setq fmt (plist-get org-time-clocksum-format :years))
17641 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17642 (plist-get org-time-clocksum-format :require-years))
17643 (setq clocksum (concat clocksum (format fmt n))
17644 m (- m (* n y d h))))
17645 (and (setq fmt (plist-get org-time-clocksum-format :months))
17646 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17647 (plist-get org-time-clocksum-format :require-months))
17648 (setq clocksum (concat clocksum (format fmt n))
17649 m (- m (* n mo d h))))
17650 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17651 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17652 (plist-get org-time-clocksum-format :require-weeks))
17653 (setq clocksum (concat clocksum (format fmt n))
17654 m (- m (* n w d h))))
17655 (and (setq fmt (plist-get org-time-clocksum-format :days))
17656 (or (> (setq n (/ (truncate m) (* d h))) 0)
17657 (plist-get org-time-clocksum-format :require-days))
17658 (setq clocksum (concat clocksum (format fmt n))
17659 m (- m (* n d h))))
17660 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17661 (or (> (setq n (/ (truncate m) h)) 0)
17662 (plist-get org-time-clocksum-format :require-hours))
17663 (setq clocksum (concat clocksum (format fmt n))
17664 m (- m (* n h))))
17665 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17666 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17667 (setq clocksum (concat clocksum (format fmt m))))
17668 ;; return formatted time duration
17669 clocksum))))
17671 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17672 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17673 "Org mode version 8.0")
17675 (defun org-hours-to-clocksum-string (n)
17676 (org-minutes-to-clocksum-string (* n 60)))
17678 (defun org-hh:mm-string-to-minutes (s)
17679 "Convert a string H:MM to a number of minutes.
17680 If the string is just a number, interpret it as minutes.
17681 In fact, the first hh:mm or number in the string will be taken,
17682 there can be extra stuff in the string.
17683 If no number is found, the return value is 0."
17684 (cond
17685 ((integerp s) s)
17686 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17687 (+ (* (string-to-number (match-string 1 s)) 60)
17688 (string-to-number (match-string 2 s))))
17689 ((string-match "\\([0-9]+\\)" s)
17690 (string-to-number (match-string 1 s)))
17691 (t 0)))
17693 (defcustom org-image-actual-width t
17694 "Should we use the actual width of images when inlining them?
17696 When set to `t', always use the image width.
17698 When set to a number, use imagemagick (when available) to set
17699 the image's width to this value.
17701 When set to a number in a list, try to get the width from any
17702 #+ATTR.* keyword if it matches a width specification like
17704 #+ATTR_HTML: :width 300px
17706 and fall back on that number if none is found.
17708 When set to nil, try to get the width from an #+ATTR.* keyword
17709 and fall back on the original width if none is found.
17711 This requires Emacs >= 24.1, build with imagemagick support."
17712 :group 'org-appearance
17713 :version "24.4"
17714 :package-version '(Org . "8.0")
17715 :type '(choice
17716 (const :tag "Use the image width" t)
17717 (integer :tag "Use a number of pixels")
17718 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17719 (const :tag "Use #+ATTR* or don't resize" nil)))
17721 (defcustom org-agenda-inhibit-startup nil
17722 "Inhibit startup when preparing agenda buffers.
17723 When this variable is `t' (the default), the initialization of
17724 the Org agenda buffers is inhibited: e.g. the visibility state
17725 is not set, the tables are not re-aligned, etc."
17726 :type 'boolean
17727 :version "24.3"
17728 :group 'org-agenda)
17730 (defcustom org-agenda-ignore-drawer-properties nil
17731 "Avoid updating text properties when building the agenda.
17732 Properties are used to prepare buffers for effort estimates, appointments,
17733 and subtree-local categories.
17734 If you don't use these in the agenda, you can add them to this list and
17735 agenda building will be a bit faster.
17736 The value is a list, with zero or more of the symbols `effort', `appt',
17737 or `category'."
17738 :type '(set :greedy t
17739 (const effort)
17740 (const appt)
17741 (const category))
17742 :version "24.3"
17743 :group 'org-agenda)
17745 (defun org-duration-string-to-minutes (s &optional output-to-string)
17746 "Convert a duration string S to minutes.
17748 A bare number is interpreted as minutes, modifiers can be set by
17749 customizing `org-effort-durations' (which see).
17751 Entries containing a colon are interpreted as H:MM by
17752 `org-hh:mm-string-to-minutes'."
17753 (let ((result 0)
17754 (re (concat "\\([0-9.]+\\) *\\("
17755 (regexp-opt (mapcar 'car org-effort-durations))
17756 "\\)")))
17757 (while (string-match re s)
17758 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17759 (string-to-number (match-string 1 s))))
17760 (setq s (replace-match "" nil t s)))
17761 (setq result (floor result))
17762 (incf result (org-hh:mm-string-to-minutes s))
17763 (if output-to-string (number-to-string result) result)))
17765 ;;;; Files
17767 (defun org-save-all-org-buffers ()
17768 "Save all Org-mode buffers without user confirmation."
17769 (interactive)
17770 (message "Saving all Org-mode buffers...")
17771 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17772 (when (featurep 'org-id) (org-id-locations-save))
17773 (message "Saving all Org-mode buffers... done"))
17775 (defun org-revert-all-org-buffers ()
17776 "Revert all Org-mode buffers.
17777 Prompt for confirmation when there are unsaved changes.
17778 Be sure you know what you are doing before letting this function
17779 overwrite your changes.
17781 This function is useful in a setup where one tracks org files
17782 with a version control system, to revert on one machine after pulling
17783 changes from another. I believe the procedure must be like this:
17785 1. M-x org-save-all-org-buffers
17786 2. Pull changes from the other machine, resolve conflicts
17787 3. M-x org-revert-all-org-buffers"
17788 (interactive)
17789 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17790 (user-error "Abort"))
17791 (save-excursion
17792 (save-window-excursion
17793 (mapc
17794 (lambda (b)
17795 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17796 (with-current-buffer b buffer-file-name))
17797 (org-pop-to-buffer-same-window b)
17798 (revert-buffer t 'no-confirm)))
17799 (buffer-list))
17800 (when (and (featurep 'org-id) org-id-track-globally)
17801 (org-id-locations-load)))))
17803 ;;;; Agenda files
17805 ;;;###autoload
17806 (defun org-switchb (&optional arg)
17807 "Switch between Org buffers.
17808 With one prefix argument, restrict available buffers to files.
17809 With two prefix arguments, restrict available buffers to agenda files.
17811 Defaults to `iswitchb' for buffer name completion.
17812 Set `org-completion-use-ido' to make it use ido instead."
17813 (interactive "P")
17814 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17815 ((equal arg '(16)) (org-buffer-list 'agenda))
17816 (t (org-buffer-list))))
17817 (org-completion-use-iswitchb org-completion-use-iswitchb)
17818 (org-completion-use-ido org-completion-use-ido))
17819 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17820 (setq org-completion-use-iswitchb t))
17821 (org-pop-to-buffer-same-window
17822 (org-icompleting-read "Org buffer: "
17823 (mapcar 'list (mapcar 'buffer-name blist))
17824 nil t))))
17826 ;;; Define some older names previously used for this functionality
17827 ;;;###autoload
17828 (defalias 'org-ido-switchb 'org-switchb)
17829 ;;;###autoload
17830 (defalias 'org-iswitchb 'org-switchb)
17832 (defun org-buffer-list (&optional predicate exclude-tmp)
17833 "Return a list of Org buffers.
17834 PREDICATE can be `export', `files' or `agenda'.
17836 export restrict the list to Export buffers.
17837 files restrict the list to buffers visiting Org files.
17838 agenda restrict the list to buffers visiting agenda files.
17840 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17841 (let* ((bfn nil)
17842 (agenda-files (and (eq predicate 'agenda)
17843 (mapcar 'file-truename (org-agenda-files t))))
17844 (filter
17845 (cond
17846 ((eq predicate 'files)
17847 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17848 ((eq predicate 'export)
17849 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17850 ((eq predicate 'agenda)
17851 (lambda (b)
17852 (with-current-buffer b
17853 (and (derived-mode-p 'org-mode)
17854 (setq bfn (buffer-file-name b))
17855 (member (file-truename bfn) agenda-files)))))
17856 (t (lambda (b) (with-current-buffer b
17857 (or (derived-mode-p 'org-mode)
17858 (string-match "\*Org .*Export"
17859 (buffer-name b)))))))))
17860 (delq nil
17861 (mapcar
17862 (lambda(b)
17863 (if (and (funcall filter b)
17864 (or (not exclude-tmp)
17865 (not (string-match "tmp" (buffer-name b)))))
17867 nil))
17868 (buffer-list)))))
17870 (defun org-agenda-files (&optional unrestricted archives)
17871 "Get the list of agenda files.
17872 Optional UNRESTRICTED means return the full list even if a restriction
17873 is currently in place.
17874 When ARCHIVES is t, include all archive files that are really being
17875 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17876 `org-agenda-archives-mode' is t."
17877 (let ((files
17878 (cond
17879 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17880 ((stringp org-agenda-files) (org-read-agenda-file-list))
17881 ((listp org-agenda-files) org-agenda-files)
17882 (t (error "Invalid value of `org-agenda-files'")))))
17883 (setq files (apply 'append
17884 (mapcar (lambda (f)
17885 (if (file-directory-p f)
17886 (directory-files
17887 f t org-agenda-file-regexp)
17888 (list f)))
17889 files)))
17890 (when org-agenda-skip-unavailable-files
17891 (setq files (delq nil
17892 (mapcar (function
17893 (lambda (file)
17894 (and (file-readable-p file) file)))
17895 files))))
17896 (when (or (eq archives t)
17897 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17898 (setq files (org-add-archive-files files)))
17899 files))
17901 (defun org-agenda-file-p (&optional file)
17902 "Return non-nil, if FILE is an agenda file.
17903 If FILE is omitted, use the file associated with the current
17904 buffer."
17905 (member (or file (buffer-file-name))
17906 (org-agenda-files t)))
17908 (defun org-edit-agenda-file-list ()
17909 "Edit the list of agenda files.
17910 Depending on setup, this either uses customize to edit the variable
17911 `org-agenda-files', or it visits the file that is holding the list. In the
17912 latter case, the buffer is set up in a way that saving it automatically kills
17913 the buffer and restores the previous window configuration."
17914 (interactive)
17915 (if (stringp org-agenda-files)
17916 (let ((cw (current-window-configuration)))
17917 (find-file org-agenda-files)
17918 (org-set-local 'org-window-configuration cw)
17919 (org-add-hook 'after-save-hook
17920 (lambda ()
17921 (set-window-configuration
17922 (prog1 org-window-configuration
17923 (kill-buffer (current-buffer))))
17924 (org-install-agenda-files-menu)
17925 (message "New agenda file list installed"))
17926 nil 'local)
17927 (message "%s" (substitute-command-keys
17928 "Edit list and finish with \\[save-buffer]")))
17929 (customize-variable 'org-agenda-files)))
17931 (defun org-store-new-agenda-file-list (list)
17932 "Set new value for the agenda file list and save it correctly."
17933 (if (stringp org-agenda-files)
17934 (let ((fe (org-read-agenda-file-list t)) b u)
17935 (while (setq b (find-buffer-visiting org-agenda-files))
17936 (kill-buffer b))
17937 (with-temp-file org-agenda-files
17938 (insert
17939 (mapconcat
17940 (lambda (f) ;; Keep un-expanded entries.
17941 (if (setq u (assoc f fe))
17942 (cdr u)
17944 list "\n")
17945 "\n")))
17946 (let ((org-mode-hook nil) (org-inhibit-startup t)
17947 (org-insert-mode-line-in-empty-file nil))
17948 (setq org-agenda-files list)
17949 (customize-save-variable 'org-agenda-files org-agenda-files))))
17951 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17952 "Read the list of agenda files from a file.
17953 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17954 filenames, used by `org-store-new-agenda-file-list' to write back
17955 un-expanded file names."
17956 (when (file-directory-p org-agenda-files)
17957 (error "`org-agenda-files' cannot be a single directory"))
17958 (when (stringp org-agenda-files)
17959 (with-temp-buffer
17960 (insert-file-contents org-agenda-files)
17961 (mapcar
17962 (lambda (f)
17963 (let ((e (expand-file-name (substitute-in-file-name f)
17964 org-directory)))
17965 (if pair-with-expansion
17966 (cons e f)
17967 e)))
17968 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17970 ;;;###autoload
17971 (defun org-cycle-agenda-files ()
17972 "Cycle through the files in `org-agenda-files'.
17973 If the current buffer visits an agenda file, find the next one in the list.
17974 If the current buffer does not, find the first agenda file."
17975 (interactive)
17976 (let* ((fs (org-agenda-files t))
17977 (files (append fs (list (car fs))))
17978 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17979 file)
17980 (unless files (user-error "No agenda files"))
17981 (catch 'exit
17982 (while (setq file (pop files))
17983 (if (equal (file-truename file) tcf)
17984 (when (car files)
17985 (find-file (car files))
17986 (throw 'exit t))))
17987 (find-file (car fs)))
17988 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17990 (defun org-agenda-file-to-front (&optional to-end)
17991 "Move/add the current file to the top of the agenda file list.
17992 If the file is not present in the list, it is added to the front. If it is
17993 present, it is moved there. With optional argument TO-END, add/move to the
17994 end of the list."
17995 (interactive "P")
17996 (let ((org-agenda-skip-unavailable-files nil)
17997 (file-alist (mapcar (lambda (x)
17998 (cons (file-truename x) x))
17999 (org-agenda-files t)))
18000 (ctf (file-truename
18001 (or buffer-file-name
18002 (user-error "Please save the current buffer to a file"))))
18003 x had)
18004 (setq x (assoc ctf file-alist) had x)
18006 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18007 (if to-end
18008 (setq file-alist (append (delq x file-alist) (list x)))
18009 (setq file-alist (cons x (delq x file-alist))))
18010 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18011 (org-install-agenda-files-menu)
18012 (message "File %s to %s of agenda file list"
18013 (if had "moved" "added") (if to-end "end" "front"))))
18015 (defun org-remove-file (&optional file)
18016 "Remove current file from the list of files in variable `org-agenda-files'.
18017 These are the files which are being checked for agenda entries.
18018 Optional argument FILE means use this file instead of the current."
18019 (interactive)
18020 (let* ((org-agenda-skip-unavailable-files nil)
18021 (file (or file buffer-file-name
18022 (user-error "Current buffer does not visit a file")))
18023 (true-file (file-truename file))
18024 (afile (abbreviate-file-name file))
18025 (files (delq nil (mapcar
18026 (lambda (x)
18027 (if (equal true-file
18028 (file-truename x))
18029 nil x))
18030 (org-agenda-files t)))))
18031 (if (not (= (length files) (length (org-agenda-files t))))
18032 (progn
18033 (org-store-new-agenda-file-list files)
18034 (org-install-agenda-files-menu)
18035 (message "Removed file: %s" afile))
18036 (message "File was not in list: %s (not removed)" afile))))
18038 (defun org-file-menu-entry (file)
18039 (vector file (list 'find-file file) t))
18041 (defun org-check-agenda-file (file)
18042 "Make sure FILE exists. If not, ask user what to do."
18043 (when (not (file-exists-p file))
18044 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18045 (abbreviate-file-name file))
18046 (let ((r (downcase (read-char-exclusive))))
18047 (cond
18048 ((equal r ?r)
18049 (org-remove-file file)
18050 (throw 'nextfile t))
18051 (t (error "Abort"))))))
18053 (defun org-get-agenda-file-buffer (file)
18054 "Get a buffer visiting FILE. If the buffer needs to be created, add
18055 it to the list of buffers which might be released later."
18056 (let ((buf (org-find-base-buffer-visiting file)))
18057 (if buf
18058 buf ; just return it
18059 ;; Make a new buffer and remember it
18060 (setq buf (find-file-noselect file))
18061 (if buf (push buf org-agenda-new-buffers))
18062 buf)))
18064 (defun org-release-buffers (blist)
18065 "Release all buffers in list, asking the user for confirmation when needed.
18066 When a buffer is unmodified, it is just killed. When modified, it is saved
18067 \(if the user agrees) and then killed."
18068 (let (buf file)
18069 (while (setq buf (pop blist))
18070 (setq file (buffer-file-name buf))
18071 (when (and (buffer-modified-p buf)
18072 file
18073 (y-or-n-p (format "Save file %s? " file)))
18074 (with-current-buffer buf (save-buffer)))
18075 (kill-buffer buf))))
18077 (defun org-agenda-prepare-buffers (files)
18078 "Create buffers for all agenda files, protect archived trees and comments."
18079 (interactive)
18080 (let ((pa '(:org-archived t))
18081 (pc '(:org-comment t))
18082 (pall '(:org-archived t :org-comment t))
18083 (inhibit-read-only t)
18084 (org-inhibit-startup org-agenda-inhibit-startup)
18085 (rea (concat ":" org-archive-tag ":"))
18086 file re pos)
18087 (setq org-tag-alist-for-agenda nil
18088 org-tag-groups-alist-for-agenda nil)
18089 (save-excursion
18090 (save-restriction
18091 (while (setq file (pop files))
18092 (catch 'nextfile
18093 (if (bufferp file)
18094 (set-buffer file)
18095 (org-check-agenda-file file)
18096 (set-buffer (org-get-agenda-file-buffer file)))
18097 (widen)
18098 (org-set-regexps-and-options-for-tags)
18099 (setq pos (point))
18100 (goto-char (point-min))
18101 (let ((case-fold-search t))
18102 (when (search-forward "#+setupfile" nil t)
18103 ;; Don't set all regexps and options systematically as
18104 ;; this is only run for setting agenda tags from setup
18105 ;; file
18106 (org-set-regexps-and-options)))
18107 (or (memq 'category org-agenda-ignore-drawer-properties)
18108 (org-refresh-category-properties))
18109 (or (memq 'effort org-agenda-ignore-drawer-properties)
18110 (org-refresh-properties org-effort-property 'org-effort))
18111 (or (memq 'appt org-agenda-ignore-drawer-properties)
18112 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18113 (setq org-todo-keywords-for-agenda
18114 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18115 (setq org-done-keywords-for-agenda
18116 (append org-done-keywords-for-agenda org-done-keywords))
18117 (setq org-todo-keyword-alist-for-agenda
18118 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18119 (setq org-drawers-for-agenda
18120 (append org-drawers-for-agenda org-drawers))
18121 (setq org-tag-alist-for-agenda
18122 (org-uniquify
18123 (append org-tag-alist-for-agenda
18124 org-tag-alist
18125 org-tag-persistent-alist)))
18126 (if org-group-tags
18127 (setq org-tag-groups-alist-for-agenda
18128 (org-uniquify-alist
18129 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18130 (org-with-silent-modifications
18131 (save-excursion
18132 (remove-text-properties (point-min) (point-max) pall)
18133 (when org-agenda-skip-archived-trees
18134 (goto-char (point-min))
18135 (while (re-search-forward rea nil t)
18136 (if (org-at-heading-p t)
18137 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18138 (goto-char (point-min))
18139 (setq re (format org-heading-keyword-regexp-format
18140 org-comment-string))
18141 (while (re-search-forward re nil t)
18142 (add-text-properties
18143 (match-beginning 0) (org-end-of-subtree t) pc))))
18144 (goto-char pos)))))
18145 (setq org-todo-keywords-for-agenda
18146 (org-uniquify org-todo-keywords-for-agenda))
18147 (setq org-todo-keyword-alist-for-agenda
18148 (org-uniquify org-todo-keyword-alist-for-agenda))))
18151 ;;;; CDLaTeX minor mode
18153 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18154 "Keymap for the minor `org-cdlatex-mode'.")
18156 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18157 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18158 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18159 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18160 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
18162 (defvar org-cdlatex-texmathp-advice-is-done nil
18163 "Flag remembering if we have applied the advice to texmathp already.")
18165 (define-minor-mode org-cdlatex-mode
18166 "Toggle the minor `org-cdlatex-mode'.
18167 This mode supports entering LaTeX environment and math in LaTeX fragments
18168 in Org-mode.
18169 \\{org-cdlatex-mode-map}"
18170 nil " OCDL" nil
18171 (when org-cdlatex-mode
18172 (require 'cdlatex)
18173 (run-hooks 'cdlatex-mode-hook)
18174 (cdlatex-compute-tables))
18175 (unless org-cdlatex-texmathp-advice-is-done
18176 (setq org-cdlatex-texmathp-advice-is-done t)
18177 (defadvice texmathp (around org-math-always-on activate)
18178 "Always return t in org-mode buffers.
18179 This is because we want to insert math symbols without dollars even outside
18180 the LaTeX math segments. If Orgmode thinks that point is actually inside
18181 an embedded LaTeX fragment, let texmathp do its job.
18182 \\[org-cdlatex-mode-map]"
18183 (interactive)
18184 (let (p)
18185 (cond
18186 ((not (derived-mode-p 'org-mode)) ad-do-it)
18187 ((eq this-command 'cdlatex-math-symbol)
18188 (setq ad-return-value t
18189 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18191 (let ((p (org-inside-LaTeX-fragment-p)))
18192 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18193 (setq ad-return-value t
18194 texmathp-why '("Org-mode embedded math" . 0))
18195 (if p ad-do-it)))))))))
18197 (defun turn-on-org-cdlatex ()
18198 "Unconditionally turn on `org-cdlatex-mode'."
18199 (org-cdlatex-mode 1))
18201 (defun org-try-cdlatex-tab ()
18202 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18203 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18204 - inside a LaTeX fragment, or
18205 - after the first word in a line, where an abbreviation expansion could
18206 insert a LaTeX environment."
18207 (when org-cdlatex-mode
18208 (cond
18209 ;; Before any word on the line: No expansion possible.
18210 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18211 ;; Just after first word on the line: Expand it. Make sure it
18212 ;; cannot happen on headlines, though.
18213 ((save-excursion
18214 (skip-chars-backward "a-zA-Z0-9*")
18215 (skip-chars-backward " \t")
18216 (and (bolp) (not (org-at-heading-p))))
18217 (cdlatex-tab) t)
18218 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18220 (defun org-cdlatex-underscore-caret (&optional arg)
18221 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18222 Revert to the normal definition outside of these fragments."
18223 (interactive "P")
18224 (if (org-inside-LaTeX-fragment-p)
18225 (call-interactively 'cdlatex-sub-superscript)
18226 (let (org-cdlatex-mode)
18227 (call-interactively (key-binding (vector last-input-event))))))
18229 (defun org-cdlatex-math-modify (&optional arg)
18230 "Execute `cdlatex-math-modify' in LaTeX fragments.
18231 Revert to the normal definition outside of these fragments."
18232 (interactive "P")
18233 (if (org-inside-LaTeX-fragment-p)
18234 (call-interactively 'cdlatex-math-modify)
18235 (let (org-cdlatex-mode)
18236 (call-interactively (key-binding (vector last-input-event))))))
18240 ;;;; LaTeX fragments
18242 (defvar org-latex-regexps
18243 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
18244 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
18245 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
18246 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18247 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18248 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
18249 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
18250 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
18251 "Regular expressions for matching embedded LaTeX.")
18253 (defun org-inside-LaTeX-fragment-p ()
18254 "Test if point is inside a LaTeX fragment.
18255 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18256 sequence appearing also before point.
18257 Even though the matchers for math are configurable, this function assumes
18258 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18259 delimiters are skipped when they have been removed by customization.
18260 The return value is nil, or a cons cell with the delimiter and the
18261 position of this delimiter.
18263 This function does a reasonably good job, but can locally be fooled by
18264 for example currency specifications. For example it will assume being in
18265 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18266 fragments that are properly closed, but during editing, we have to live
18267 with the uncertainty caused by missing closing delimiters. This function
18268 looks only before point, not after."
18269 (catch 'exit
18270 (let ((pos (point))
18271 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18272 (lim (progn
18273 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18274 (point)))
18275 dd-on str (start 0) m re)
18276 (goto-char pos)
18277 (when dodollar
18278 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18279 re (nth 1 (assoc "$" org-latex-regexps)))
18280 (while (string-match re str start)
18281 (cond
18282 ((= (match-end 0) (length str))
18283 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18284 ((= (match-end 0) (- (length str) 5))
18285 (throw 'exit nil))
18286 (t (setq start (match-end 0))))))
18287 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18288 (goto-char pos)
18289 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18290 (and (match-beginning 2) (throw 'exit nil))
18291 ;; count $$
18292 (while (re-search-backward "\\$\\$" lim t)
18293 (setq dd-on (not dd-on)))
18294 (goto-char pos)
18295 (if dd-on (cons "$$" m))))))
18297 (defun org-inside-latex-macro-p ()
18298 "Is point inside a LaTeX macro or its arguments?"
18299 (save-match-data
18300 (org-in-regexp
18301 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18303 (defvar org-latex-fragment-image-overlays nil
18304 "List of overlays carrying the images of latex fragments.")
18305 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18307 (defun org-remove-latex-fragment-image-overlays ()
18308 "Remove all overlays with LaTeX fragment images in current buffer."
18309 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18310 (setq org-latex-fragment-image-overlays nil))
18312 (defun org-preview-latex-fragment (&optional subtree)
18313 "Preview the LaTeX fragment at point, or all locally or globally.
18314 If the cursor is in a LaTeX fragment, create the image and overlay
18315 it over the source code. If there is no fragment at point, display
18316 all fragments in the current text, from one headline to the next. With
18317 prefix SUBTREE, display all fragments in the current subtree. With a
18318 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18319 the cursor is before the first headline,
18320 display all fragments in the buffer.
18321 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18322 (interactive "P")
18323 (unless buffer-file-name
18324 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18325 (when (display-graphic-p)
18326 (org-remove-latex-fragment-image-overlays)
18327 (save-excursion
18328 (save-restriction
18329 (let (beg end at msg)
18330 (cond
18331 ((or (equal subtree '(16))
18332 (not (save-excursion
18333 (re-search-backward org-outline-regexp-bol nil t))))
18334 (setq beg (point-min) end (point-max)
18335 msg "Creating images for buffer...%s"))
18336 ((equal subtree '(4))
18337 (org-back-to-heading)
18338 (setq beg (point) end (org-end-of-subtree t)
18339 msg "Creating images for subtree...%s"))
18341 (if (setq at (org-inside-LaTeX-fragment-p))
18342 (goto-char (max (point-min) (- (cdr at) 2)))
18343 (org-back-to-heading))
18344 (setq beg (point) end (progn (outline-next-heading) (point))
18345 msg (if at "Creating image...%s"
18346 "Creating images for entry...%s"))))
18347 (message msg "")
18348 (narrow-to-region beg end)
18349 (goto-char beg)
18350 (org-format-latex
18351 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18352 (file-name-nondirectory
18353 buffer-file-name)))
18354 default-directory 'overlays msg at 'forbuffer
18355 org-latex-create-formula-image-program)
18356 (message msg "done. Use `C-c C-c' to remove images."))))))
18358 (defun org-format-latex (prefix &optional dir overlays msg at
18359 forbuffer processing-type)
18360 "Replace LaTeX fragments with links to an image, and produce images.
18361 Some of the options can be changed using the variable
18362 `org-format-latex-options'."
18363 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18364 (let* ((prefixnodir (file-name-nondirectory prefix))
18365 (absprefix (expand-file-name prefix dir))
18366 (todir (file-name-directory absprefix))
18367 (opt org-format-latex-options)
18368 (optnew org-format-latex-options)
18369 (matchers (plist-get opt :matchers))
18370 (re-list org-latex-regexps)
18371 (cnt 0) txt hash link beg end re e checkdir
18372 string
18373 m n block-type block linkfile movefile ov)
18374 ;; Check the different regular expressions
18375 (while (setq e (pop re-list))
18376 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18377 block (if block-type "\n\n" ""))
18378 (when (member m matchers)
18379 (goto-char (point-min))
18380 (while (re-search-forward re nil t)
18381 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18382 (or (not overlays)
18383 (not (eq (get-char-property (match-beginning n)
18384 'org-overlay-type)
18385 'org-latex-overlay))))
18386 (cond
18387 ((eq processing-type 'verbatim))
18388 ((eq processing-type 'mathjax)
18389 ;; Prepare for MathJax processing.
18390 (setq string (match-string n))
18391 (when (member m '("$" "$1"))
18392 (save-excursion
18393 (delete-region (match-beginning n) (match-end n))
18394 (goto-char (match-beginning n))
18395 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18396 ((or (eq processing-type 'dvipng)
18397 (eq processing-type 'imagemagick))
18398 ;; Process to an image.
18399 (setq txt (match-string n)
18400 beg (match-beginning n) end (match-end n)
18401 cnt (1+ cnt))
18402 (let ((face (face-at-point))
18403 (fg (plist-get opt :foreground))
18404 (bg (plist-get opt :background))
18405 ;; Ensure full list is printed.
18406 print-length print-level)
18407 (when forbuffer
18408 ;; Get the colors from the face at point.
18409 (goto-char beg)
18410 (when (eq fg 'auto)
18411 (setq fg (face-attribute face :foreground nil 'default)))
18412 (when (eq bg 'auto)
18413 (setq bg (face-attribute face :background nil 'default)))
18414 (setq optnew (copy-sequence opt))
18415 (plist-put optnew :foreground fg)
18416 (plist-put optnew :background bg))
18417 (setq hash (sha1 (prin1-to-string
18418 (list org-format-latex-header
18419 org-latex-default-packages-alist
18420 org-latex-packages-alist
18421 org-format-latex-options
18422 forbuffer txt fg bg)))
18423 linkfile (format "%s_%s.png" prefix hash)
18424 movefile (format "%s_%s.png" absprefix hash)))
18425 (setq link (concat block "[[file:" linkfile "]]" block))
18426 (if msg (message msg cnt))
18427 (goto-char beg)
18428 (unless checkdir ; Ensure the directory exists.
18429 (setq checkdir t)
18430 (or (file-directory-p todir) (make-directory todir t)))
18431 (unless (file-exists-p movefile)
18432 (org-create-formula-image
18433 txt movefile optnew forbuffer processing-type))
18434 (if overlays
18435 (progn
18436 (mapc (lambda (o)
18437 (if (eq (overlay-get o 'org-overlay-type)
18438 'org-latex-overlay)
18439 (delete-overlay o)))
18440 (overlays-in beg end))
18441 (setq ov (make-overlay beg end))
18442 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18443 (if (featurep 'xemacs)
18444 (progn
18445 (overlay-put ov 'invisible t)
18446 (overlay-put
18447 ov 'end-glyph
18448 (make-glyph (vector 'png :file movefile))))
18449 (overlay-put
18450 ov 'display
18451 (list 'image :type 'png :file movefile :ascent 'center)))
18452 (push ov org-latex-fragment-image-overlays)
18453 (goto-char end))
18454 (delete-region beg end)
18455 (insert (org-add-props link
18456 (list 'org-latex-src
18457 (replace-regexp-in-string
18458 "\"" "" txt)
18459 'org-latex-src-embed-type
18460 (if block-type 'paragraph 'character))))))
18461 ((eq processing-type 'mathml)
18462 ;; Process to MathML
18463 (unless (save-match-data (org-format-latex-mathml-available-p))
18464 (user-error "LaTeX to MathML converter not configured"))
18465 (setq txt (match-string n)
18466 beg (match-beginning n) end (match-end n)
18467 cnt (1+ cnt))
18468 (if msg (message msg cnt))
18469 (goto-char beg)
18470 (delete-region beg end)
18471 (insert (org-format-latex-as-mathml
18472 txt block-type prefix dir)))
18474 (error "Unknown conversion type %s for LaTeX fragments"
18475 processing-type)))))))))
18477 (defun org-create-math-formula (latex-frag &optional mathml-file)
18478 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18479 Use `org-latex-to-mathml-convert-command'. If the conversion is
18480 sucessful, return the portion between \"<math...> </math>\"
18481 elements otherwise return nil. When MATHML-FILE is specified,
18482 write the results in to that file. When invoked as an
18483 interactive command, prompt for LATEX-FRAG, with initial value
18484 set to the current active region and echo the results for user
18485 inspection."
18486 (interactive (list (let ((frag (when (org-region-active-p)
18487 (buffer-substring-no-properties
18488 (region-beginning) (region-end)))))
18489 (read-string "LaTeX Fragment: " frag nil frag))))
18490 (unless latex-frag (error "Invalid LaTeX fragment"))
18491 (let* ((tmp-in-file (file-relative-name
18492 (make-temp-name (expand-file-name "ltxmathml-in"))))
18493 (ignore (write-region latex-frag nil tmp-in-file))
18494 (tmp-out-file (file-relative-name
18495 (make-temp-name (expand-file-name "ltxmathml-out"))))
18496 (cmd (format-spec
18497 org-latex-to-mathml-convert-command
18498 `((?j . ,(shell-quote-argument
18499 (expand-file-name org-latex-to-mathml-jar-file)))
18500 (?I . ,(shell-quote-argument tmp-in-file))
18501 (?o . ,(shell-quote-argument tmp-out-file)))))
18502 mathml shell-command-output)
18503 (when (org-called-interactively-p 'any)
18504 (unless (org-format-latex-mathml-available-p)
18505 (user-error "LaTeX to MathML converter not configured")))
18506 (message "Running %s" cmd)
18507 (setq shell-command-output (shell-command-to-string cmd))
18508 (setq mathml
18509 (when (file-readable-p tmp-out-file)
18510 (with-current-buffer (find-file-noselect tmp-out-file t)
18511 (goto-char (point-min))
18512 (when (re-search-forward
18513 (concat
18514 (regexp-quote
18515 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18516 "\\(.\\|\n\\)*"
18517 (regexp-quote "</math>")) nil t)
18518 (prog1 (match-string 0) (kill-buffer))))))
18519 (cond
18520 (mathml
18521 (setq mathml
18522 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18523 (when mathml-file
18524 (write-region mathml nil mathml-file))
18525 (when (org-called-interactively-p 'any)
18526 (message mathml)))
18527 ((message "LaTeX to MathML conversion failed")
18528 (message shell-command-output)))
18529 (delete-file tmp-in-file)
18530 (when (file-exists-p tmp-out-file)
18531 (delete-file tmp-out-file))
18532 mathml))
18534 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18535 prefix &optional dir)
18536 "Use `org-create-math-formula' but check local cache first."
18537 (let* ((absprefix (expand-file-name prefix dir))
18538 (print-length nil) (print-level nil)
18539 (formula-id (concat
18540 "formula-"
18541 (sha1
18542 (prin1-to-string
18543 (list latex-frag
18544 org-latex-to-mathml-convert-command)))))
18545 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18546 (formula-cache-dir (file-name-directory formula-cache)))
18548 (unless (file-directory-p formula-cache-dir)
18549 (make-directory formula-cache-dir t))
18551 (unless (file-exists-p formula-cache)
18552 (org-create-math-formula latex-frag formula-cache))
18554 (if (file-exists-p formula-cache)
18555 ;; Successful conversion. Return the link to MathML file.
18556 (org-add-props
18557 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18558 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18559 'org-latex-src-embed-type (if latex-frag-type
18560 'paragraph 'character)))
18561 ;; Failed conversion. Return the LaTeX fragment verbatim
18562 latex-frag)))
18564 (defun org-create-formula-image (string tofile options buffer &optional type)
18565 "Create an image from LaTeX source using dvipng or convert.
18566 This function calls either `org-create-formula-image-with-dvipng'
18567 or `org-create-formula-image-with-imagemagick' depending on the
18568 value of `org-latex-create-formula-image-program' or on the value
18569 of the optional TYPE variable.
18571 Note: ultimately these two function should be combined as they
18572 share a good deal of logic."
18573 (org-check-external-command
18574 "latex" "needed to convert LaTeX fragments to images")
18575 (funcall
18576 (case (or type org-latex-create-formula-image-program)
18577 ('dvipng
18578 (org-check-external-command
18579 "dvipng" "needed to convert LaTeX fragments to images")
18580 #'org-create-formula-image-with-dvipng)
18581 ('imagemagick
18582 (org-check-external-command
18583 "convert" "you need to install imagemagick")
18584 #'org-create-formula-image-with-imagemagick)
18585 (t (error
18586 "Invalid value of `org-latex-create-formula-image-program'")))
18587 string tofile options buffer))
18589 (declare-function org-export-get-backend "ox" (name))
18590 (declare-function org-export--get-global-options "ox" (&optional backend))
18591 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18592 (declare-function org-latex-guess-inputenc "ox-latex" (header))
18593 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
18594 (defun org-create-formula--latex-header ()
18595 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18596 (let ((info (org-combine-plists (org-export--get-global-options
18597 (org-export-get-backend 'latex))
18598 (org-export--get-inbuffer-options
18599 (org-export-get-backend 'latex)))))
18600 (org-latex-guess-babel-language
18601 (org-latex-guess-inputenc
18602 (org-splice-latex-header
18603 org-format-latex-header
18604 org-latex-default-packages-alist
18605 org-latex-packages-alist t
18606 (plist-get info :latex-header)))
18607 info)))
18609 ;; This function borrows from Ganesh Swami's latex2png.el
18610 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18611 "This calls dvipng."
18612 (require 'ox-latex)
18613 (let* ((tmpdir (if (featurep 'xemacs)
18614 (temp-directory)
18615 temporary-file-directory))
18616 (texfilebase (make-temp-name
18617 (expand-file-name "orgtex" tmpdir)))
18618 (texfile (concat texfilebase ".tex"))
18619 (dvifile (concat texfilebase ".dvi"))
18620 (pngfile (concat texfilebase ".png"))
18621 (fnh (if (featurep 'xemacs)
18622 (font-height (face-font 'default))
18623 (face-attribute 'default :height nil)))
18624 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18625 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18626 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18627 "Black"))
18628 (bg (or (plist-get options (if buffer :background :html-background))
18629 "Transparent")))
18630 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18631 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18632 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18633 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18634 (let ((latex-header (org-create-formula--latex-header)))
18635 (with-temp-file texfile
18636 (insert latex-header)
18637 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18638 (let ((dir default-directory))
18639 (condition-case nil
18640 (progn
18641 (cd tmpdir)
18642 (call-process "latex" nil nil nil texfile))
18643 (error nil))
18644 (cd dir))
18645 (if (not (file-exists-p dvifile))
18646 (progn (message "Failed to create dvi file from %s" texfile) nil)
18647 (condition-case nil
18648 (if (featurep 'xemacs)
18649 (call-process "dvipng" nil nil nil
18650 "-fg" fg "-bg" bg
18651 "-T" "tight"
18652 "-o" pngfile
18653 dvifile)
18654 (call-process "dvipng" nil nil nil
18655 "-fg" fg "-bg" bg
18656 "-D" dpi
18657 ;;"-x" scale "-y" scale
18658 "-T" "tight"
18659 "-o" pngfile
18660 dvifile))
18661 (error nil))
18662 (if (not (file-exists-p pngfile))
18663 (if org-format-latex-signal-error
18664 (error "Failed to create png file from %s" texfile)
18665 (message "Failed to create png file from %s" texfile)
18666 nil)
18667 ;; Use the requested file name and clean up
18668 (copy-file pngfile tofile 'replace)
18669 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18670 (if (file-exists-p (concat texfilebase e))
18671 (delete-file (concat texfilebase e))))
18672 pngfile))))
18674 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18675 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18676 "This calls convert, which is included into imagemagick."
18677 (require 'ox-latex)
18678 (let* ((tmpdir (if (featurep 'xemacs)
18679 (temp-directory)
18680 temporary-file-directory))
18681 (texfilebase (make-temp-name
18682 (expand-file-name "orgtex" tmpdir)))
18683 (texfile (concat texfilebase ".tex"))
18684 (pdffile (concat texfilebase ".pdf"))
18685 (pngfile (concat texfilebase ".png"))
18686 (fnh (if (featurep 'xemacs)
18687 (font-height (face-font 'default))
18688 (face-attribute 'default :height nil)))
18689 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18690 (dpi (number-to-string (* scale (floor (if buffer fnh 120.)))))
18691 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18692 "black"))
18693 (bg (or (plist-get options (if buffer :background :html-background))
18694 "white")))
18695 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18696 (setq fg (org-latex-color-format fg)))
18697 (if (eq bg 'default) (setq bg (org-latex-color :background))
18698 (setq bg (org-latex-color-format
18699 (if (string= bg "Transparent") "white" bg))))
18700 (let ((latex-header (org-create-formula--latex-header)))
18701 (with-temp-file texfile
18702 (insert latex-header)
18703 (insert "\n\\begin{document}\n"
18704 "\\definecolor{fg}{rgb}{" fg "}\n"
18705 "\\definecolor{bg}{rgb}{" bg "}\n"
18706 "\n\\pagecolor{bg}\n"
18707 "\n{\\color{fg}\n"
18708 string
18709 "\n}\n"
18710 "\n\\end{document}\n")))
18711 (org-latex-compile texfile t)
18712 (if (not (file-exists-p pdffile))
18713 (progn (message "Failed to create pdf file from %s" texfile) nil)
18714 (condition-case nil
18715 (if (featurep 'xemacs)
18716 (call-process "convert" nil nil nil
18717 "-density" "96"
18718 "-trim"
18719 "-antialias"
18720 pdffile
18721 "-quality" "100"
18722 ;; "-sharpen" "0x1.0"
18723 pngfile)
18724 (call-process "convert" nil nil nil
18725 "-density" dpi
18726 "-trim"
18727 "-antialias"
18728 pdffile
18729 "-quality" "100"
18730 ;; "-sharpen" "0x1.0"
18731 pngfile))
18732 (error nil))
18733 (if (not (file-exists-p pngfile))
18734 (if org-format-latex-signal-error
18735 (error "Failed to create png file from %s" texfile)
18736 (message "Failed to create png file from %s" texfile)
18737 nil)
18738 ;; Use the requested file name and clean up
18739 (copy-file pngfile tofile 'replace)
18740 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18741 (if (file-exists-p (concat texfilebase e))
18742 (delete-file (concat texfilebase e))))
18743 pngfile))))
18745 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18746 "Fill a LaTeX header template TPL.
18747 In the template, the following place holders will be recognized:
18749 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18750 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18751 [PACKAGES] \\usepackage statements for PKG
18752 [NO-PACKAGES] do not include PKG
18753 [EXTRA] the string EXTRA
18754 [NO-EXTRA] do not include EXTRA
18756 For backward compatibility, if both the positive and the negative place
18757 holder is missing, the positive one (without the \"NO-\") will be
18758 assumed to be present at the end of the template.
18759 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18760 EXTRA is a string.
18761 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18762 (let (rpl (end ""))
18763 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18764 (setq rpl (if (or (match-end 1) (not def-pkg))
18765 "" (org-latex-packages-to-string def-pkg snippets-p t))
18766 tpl (replace-match rpl t t tpl))
18767 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18769 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18770 (setq rpl (if (or (match-end 1) (not pkg))
18771 "" (org-latex-packages-to-string pkg snippets-p t))
18772 tpl (replace-match rpl t t tpl))
18773 (if pkg (setq end
18774 (concat end "\n"
18775 (org-latex-packages-to-string pkg snippets-p)))))
18777 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18778 (setq rpl (if (or (match-end 1) (not extra))
18779 "" (concat extra "\n"))
18780 tpl (replace-match rpl t t tpl))
18781 (if (and extra (string-match "\\S-" extra))
18782 (setq end (concat end "\n" extra))))
18784 (if (string-match "\\S-" end)
18785 (concat tpl "\n" end)
18786 tpl)))
18788 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18789 "Turn an alist of packages into a string with the \\usepackage macros."
18790 (setq pkg (mapconcat (lambda(p)
18791 (cond
18792 ((stringp p) p)
18793 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18794 (format "%% Package %s omitted" (cadr p)))
18795 ((equal "" (car p))
18796 (format "\\usepackage{%s}" (cadr p)))
18798 (format "\\usepackage[%s]{%s}"
18799 (car p) (cadr p)))))
18801 "\n"))
18802 (if newline (concat pkg "\n") pkg))
18804 (defun org-dvipng-color (attr)
18805 "Return a RGB color specification for dvipng."
18806 (apply 'format "rgb %s %s %s"
18807 (mapcar 'org-normalize-color
18808 (if (featurep 'xemacs)
18809 (color-rgb-components
18810 (face-property 'default
18811 (cond ((eq attr :foreground) 'foreground)
18812 ((eq attr :background) 'background))))
18813 (color-values (face-attribute 'default attr nil))))))
18815 (defun org-dvipng-color-format (color-name)
18816 "Convert COLOR-NAME to a RGB color value for dvipng."
18817 (apply 'format "rgb %s %s %s"
18818 (mapcar 'org-normalize-color
18819 (color-values color-name))))
18821 (defun org-latex-color (attr)
18822 "Return a RGB color for the LaTeX color package."
18823 (apply 'format "%s,%s,%s"
18824 (mapcar 'org-normalize-color
18825 (if (featurep 'xemacs)
18826 (color-rgb-components
18827 (face-property 'default
18828 (cond ((eq attr :foreground) 'foreground)
18829 ((eq attr :background) 'background))))
18830 (color-values (face-attribute 'default attr nil))))))
18832 (defun org-latex-color-format (color-name)
18833 "Convert COLOR-NAME to a RGB color value."
18834 (apply 'format "%s,%s,%s"
18835 (mapcar 'org-normalize-color
18836 (color-values color-name))))
18838 (defun org-normalize-color (value)
18839 "Return string to be used as color value for an RGB component."
18840 (format "%g" (/ value 65535.0)))
18844 ;; Image display
18846 (defvar org-inline-image-overlays nil)
18847 (make-variable-buffer-local 'org-inline-image-overlays)
18849 (defun org-toggle-inline-images (&optional include-linked)
18850 "Toggle the display of inline images.
18851 INCLUDE-LINKED is passed to `org-display-inline-images'."
18852 (interactive "P")
18853 (if org-inline-image-overlays
18854 (progn
18855 (org-remove-inline-images)
18856 (message "Inline image display turned off"))
18857 (org-display-inline-images include-linked)
18858 (if (and (org-called-interactively-p)
18859 org-inline-image-overlays)
18860 (message "%d images displayed inline"
18861 (length org-inline-image-overlays))
18862 (message "No images to display inline"))))
18864 (defun org-redisplay-inline-images ()
18865 "Refresh the display of inline images."
18866 (interactive)
18867 (if (not org-inline-image-overlays)
18868 (org-toggle-inline-images)
18869 (org-toggle-inline-images)
18870 (org-toggle-inline-images)))
18872 (defun org-display-inline-images (&optional include-linked refresh beg end)
18873 "Display inline images.
18874 Normally only links without a description part are inlined, because this
18875 is how it will work for export. When INCLUDE-LINKED is set, also links
18876 with a description part will be inlined. This can be nice for a quick
18877 look at those images, but it does not reflect what exported files will look
18878 like.
18879 When REFRESH is set, refresh existing images between BEG and END.
18880 This will create new image displays only if necessary.
18881 BEG and END default to the buffer boundaries."
18882 (interactive "P")
18883 (when (display-graphic-p)
18884 (unless refresh
18885 (org-remove-inline-images)
18886 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18887 (save-excursion
18888 (save-restriction
18889 (widen)
18890 (setq beg (or beg (point-min)) end (or end (point-max)))
18891 (goto-char beg)
18892 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18893 (substring (org-image-file-name-regexp) 0 -2)
18894 "\\)\\]" (if include-linked "" "\\]")))
18895 (case-fold-search t)
18896 old file ov img type attrwidth width)
18897 (while (re-search-forward re end t)
18898 (setq old (get-char-property-and-overlay (match-beginning 1)
18899 'org-image-overlay)
18900 file (expand-file-name
18901 (concat (or (match-string 3) "") (match-string 4))))
18902 (when (image-type-available-p 'imagemagick)
18903 (setq attrwidth (if (or (listp org-image-actual-width)
18904 (null org-image-actual-width))
18905 (save-excursion
18906 (save-match-data
18907 (when (re-search-backward
18908 "#\\+attr.*:width[ \t]+\\([^ ]+\\)"
18909 (save-excursion
18910 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18911 (string-to-number (match-string 1))))))
18912 width (cond ((eq org-image-actual-width t) nil)
18913 ((null org-image-actual-width) attrwidth)
18914 ((numberp org-image-actual-width)
18915 org-image-actual-width)
18916 ((listp org-image-actual-width)
18917 (or attrwidth (car org-image-actual-width))))
18918 type (if width 'imagemagick)))
18919 (when (file-exists-p file)
18920 (if (and (car-safe old) refresh)
18921 (image-refresh (overlay-get (cdr old) 'display))
18922 (setq img (save-match-data (create-image file type nil :width width)))
18923 (when img
18924 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18925 (overlay-put ov 'display img)
18926 (overlay-put ov 'face 'default)
18927 (overlay-put ov 'org-image-overlay t)
18928 (overlay-put ov 'modification-hooks
18929 (list 'org-display-inline-remove-overlay))
18930 (push ov org-inline-image-overlays))))))))))
18932 (define-obsolete-function-alias
18933 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18935 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18936 "Remove inline-display overlay if a corresponding region is modified."
18937 (let ((inhibit-modification-hooks t))
18938 (when (and ov after)
18939 (delete ov org-inline-image-overlays)
18940 (delete-overlay ov))))
18942 (defun org-remove-inline-images ()
18943 "Remove inline display of images."
18944 (interactive)
18945 (mapc 'delete-overlay org-inline-image-overlays)
18946 (setq org-inline-image-overlays nil))
18948 ;;;; Key bindings
18950 ;; Outline functions from `outline-mode-prefix-map'
18951 ;; that can be remapped in Org:
18952 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18953 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18954 (define-key org-mode-map [remap outline-forward-same-level]
18955 'org-forward-heading-same-level)
18956 (define-key org-mode-map [remap outline-backward-same-level]
18957 'org-backward-heading-same-level)
18958 (define-key org-mode-map [remap show-branches]
18959 'org-kill-note-or-show-branches)
18960 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18961 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18962 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18964 ;; Outline functions from `outline-mode-prefix-map' that can not
18965 ;; be remapped in Org:
18967 ;; - the column "key binding" shows whether the Outline function is still
18968 ;; available in Org mode on the same key that it has been bound to in
18969 ;; Outline mode:
18970 ;; - "overridden": key used for a different functionality in Org mode
18971 ;; - else: key still bound to the same Outline function in Org mode
18973 ;; | Outline function | key binding | Org replacement |
18974 ;; |------------------------------------+-------------+-----------------------|
18975 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18976 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18977 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18978 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18979 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18980 ;; | `show-entry' | overridden | no replacement |
18981 ;; | `show-children' | `C-c C-i' | visibility cycling |
18982 ;; | `show-branches' | `C-c C-k' | still same function |
18983 ;; | `show-subtree' | overridden | visibility cycling |
18984 ;; | `show-all' | overridden | no replacement |
18985 ;; | `hide-subtree' | overridden | visibility cycling |
18986 ;; | `hide-body' | overridden | no replacement |
18987 ;; | `hide-entry' | overridden | visibility cycling |
18988 ;; | `hide-leaves' | overridden | no replacement |
18989 ;; | `hide-sublevels' | overridden | no replacement |
18990 ;; | `hide-other' | overridden | no replacement |
18992 ;; Make `C-c C-x' a prefix key
18993 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18995 ;; TAB key with modifiers
18996 (org-defkey org-mode-map "\C-i" 'org-cycle)
18997 (org-defkey org-mode-map [(tab)] 'org-cycle)
18998 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18999 (org-defkey org-mode-map "\M-\t" 'pcomplete)
19000 ;; The following line is necessary under Suse GNU/Linux
19001 (unless (featurep 'xemacs)
19002 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
19003 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19004 (define-key org-mode-map [backtab] 'org-shifttab)
19006 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19007 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19008 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19010 ;; Cursor keys with modifiers
19011 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19012 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19013 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19014 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19016 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19017 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19018 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19019 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19021 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19022 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19023 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19024 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19026 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19027 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19028 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19029 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19031 ;; Babel keys
19032 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19033 (mapc (lambda (pair)
19034 (define-key org-babel-map (car pair) (cdr pair)))
19035 org-babel-key-bindings)
19037 ;;; Extra keys for tty access.
19038 ;; We only set them when really needed because otherwise the
19039 ;; menus don't show the simple keys
19041 (when (or org-use-extra-keys
19042 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19043 (not window-system))
19044 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19045 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19046 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19047 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19048 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19049 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19050 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19051 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19052 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19053 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19054 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19055 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19056 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19057 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19058 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19059 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19060 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19061 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19062 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19063 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19064 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19065 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19066 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
19067 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19068 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19069 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19070 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19071 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19073 ;; All the other keys
19075 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
19076 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19077 (if (boundp 'narrow-map)
19078 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19079 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19080 (if (boundp 'narrow-map)
19081 (org-defkey narrow-map "b" 'org-narrow-to-block)
19082 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19083 (if (boundp 'narrow-map)
19084 (org-defkey narrow-map "e" 'org-narrow-to-element)
19085 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19086 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19087 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19088 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19089 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19090 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19091 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19092 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19093 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19094 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19095 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19096 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
19097 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19098 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19099 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19100 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19101 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19102 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19103 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19104 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19105 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19106 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19107 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19108 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19109 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19110 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19111 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19112 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19113 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19114 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19115 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19116 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19117 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19118 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19119 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19120 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19121 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19122 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19123 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19124 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19125 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19126 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19127 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19128 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19129 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19130 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19131 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19132 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19133 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19134 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19135 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19136 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19137 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19138 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19139 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19140 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19141 (org-defkey org-mode-map "\C-c^" 'org-sort)
19142 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19143 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19144 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19145 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19146 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19147 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19148 (org-defkey org-mode-map "\C-m" 'org-return)
19149 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19150 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19151 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19152 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19153 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19154 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19155 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19156 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19157 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19158 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19159 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19160 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19161 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19162 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19163 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
19164 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19165 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19166 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19167 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19168 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19169 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19170 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19171 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19173 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19174 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19175 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19177 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19178 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19179 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19180 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19181 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19182 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19183 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19184 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19185 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19186 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19187 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
19188 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19189 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19190 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19191 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19192 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19193 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19194 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19195 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19196 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19197 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19198 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19199 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19201 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19202 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19203 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19204 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19205 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19207 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19209 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19211 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19212 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19214 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19217 (when (featurep 'xemacs)
19218 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19221 (defconst org-speed-commands-default
19223 ("Outline Navigation")
19224 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19225 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19226 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19227 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19228 ("F" . org-next-block)
19229 ("B" . org-previous-block)
19230 ("u" . (org-speed-move-safe 'outline-up-heading))
19231 ("j" . org-goto)
19232 ("g" . (org-refile t))
19233 ("Outline Visibility")
19234 ("c" . org-cycle)
19235 ("C" . org-shifttab)
19236 (" " . org-display-outline-path)
19237 ("s" . org-narrow-to-subtree)
19238 ("=" . org-columns)
19239 ("Outline Structure Editing")
19240 ("U" . org-shiftmetaup)
19241 ("D" . org-shiftmetadown)
19242 ("r" . org-metaright)
19243 ("l" . org-metaleft)
19244 ("R" . org-shiftmetaright)
19245 ("L" . org-shiftmetaleft)
19246 ("i" . (progn (forward-char 1) (call-interactively
19247 'org-insert-heading-respect-content)))
19248 ("^" . org-sort)
19249 ("w" . org-refile)
19250 ("a" . org-archive-subtree-default-with-confirmation)
19251 ("@" . org-mark-subtree)
19252 ("#" . org-toggle-comment)
19253 ("Clock Commands")
19254 ("I" . org-clock-in)
19255 ("O" . org-clock-out)
19256 ("Meta Data Editing")
19257 ("t" . org-todo)
19258 ("," . (org-priority))
19259 ("0" . (org-priority ?\ ))
19260 ("1" . (org-priority ?A))
19261 ("2" . (org-priority ?B))
19262 ("3" . (org-priority ?C))
19263 (":" . org-set-tags-command)
19264 ("e" . org-set-effort)
19265 ("E" . org-inc-effort)
19266 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19267 (org-entry-put (point) "APPT_WARNTIME" m)))
19268 ("Agenda Views etc")
19269 ("v" . org-agenda)
19270 ("/" . org-sparse-tree)
19271 ("Misc")
19272 ("o" . org-open-at-point)
19273 ("?" . org-speed-command-help)
19274 ("<" . (org-agenda-set-restriction-lock 'subtree))
19275 (">" . (org-agenda-remove-restriction-lock))
19277 "The default speed commands.")
19279 (defun org-print-speed-command (e)
19280 (if (> (length (car e)) 1)
19281 (progn
19282 (princ "\n")
19283 (princ (car e))
19284 (princ "\n")
19285 (princ (make-string (length (car e)) ?-))
19286 (princ "\n"))
19287 (princ (car e))
19288 (princ " ")
19289 (if (symbolp (cdr e))
19290 (princ (symbol-name (cdr e)))
19291 (prin1 (cdr e)))
19292 (princ "\n")))
19294 (defun org-speed-command-help ()
19295 "Show the available speed commands."
19296 (interactive)
19297 (if (not org-use-speed-commands)
19298 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19299 (with-output-to-temp-buffer "*Help*"
19300 (princ "User-defined Speed commands\n===========================\n")
19301 (mapc 'org-print-speed-command org-speed-commands-user)
19302 (princ "\n")
19303 (princ "Built-in Speed commands\n=======================\n")
19304 (mapc 'org-print-speed-command org-speed-commands-default))
19305 (with-current-buffer "*Help*"
19306 (setq truncate-lines t))))
19308 (defun org-speed-move-safe (cmd)
19309 "Execute CMD, but make sure that the cursor always ends up in a headline.
19310 If not, return to the original position and throw an error."
19311 (interactive)
19312 (let ((pos (point)))
19313 (call-interactively cmd)
19314 (unless (and (bolp) (org-at-heading-p))
19315 (goto-char pos)
19316 (error "Boundary reached while executing %s" cmd))))
19318 (defvar org-self-insert-command-undo-counter 0)
19320 (defvar org-table-auto-blank-field) ; defined in org-table.el
19321 (defvar org-speed-command nil)
19323 (define-obsolete-function-alias
19324 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19326 (defun org-speed-command-activate (keys)
19327 "Hook for activating single-letter speed commands.
19328 `org-speed-commands-default' specifies a minimal command set.
19329 Use `org-speed-commands-user' for further customization."
19330 (when (or (and (bolp) (looking-at org-outline-regexp))
19331 (and (functionp org-use-speed-commands)
19332 (funcall org-use-speed-commands)))
19333 (cdr (assoc keys (append org-speed-commands-user
19334 org-speed-commands-default)))))
19336 (define-obsolete-function-alias
19337 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19339 (defun org-babel-speed-command-activate (keys)
19340 "Hook for activating single-letter code block commands."
19341 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19342 (cdr (assoc keys org-babel-key-bindings))))
19344 (defcustom org-speed-command-hook
19345 '(org-speed-command-default-hook org-babel-speed-command-hook)
19346 "Hook for activating speed commands at strategic locations.
19347 Hook functions are called in sequence until a valid handler is
19348 found.
19350 Each hook takes a single argument, a user-pressed command key
19351 which is also a `self-insert-command' from the global map.
19353 Within the hook, examine the cursor position and the command key
19354 and return nil or a valid handler as appropriate. Handler could
19355 be one of an interactive command, a function, or a form.
19357 Set `org-use-speed-commands' to non-nil value to enable this
19358 hook. The default setting is `org-speed-command-activate'."
19359 :group 'org-structure
19360 :version "24.1"
19361 :type 'hook)
19363 (defun org-self-insert-command (N)
19364 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19365 If the cursor is in a table looking at whitespace, the whitespace is
19366 overwritten, and the table is not marked as requiring realignment."
19367 (interactive "p")
19368 (org-check-before-invisible-edit 'insert)
19369 (cond
19370 ((and org-use-speed-commands
19371 (setq org-speed-command
19372 (run-hook-with-args-until-success
19373 'org-speed-command-hook (this-command-keys))))
19374 (cond
19375 ((commandp org-speed-command)
19376 (setq this-command org-speed-command)
19377 (call-interactively org-speed-command))
19378 ((functionp org-speed-command)
19379 (funcall org-speed-command))
19380 ((and org-speed-command (listp org-speed-command))
19381 (eval org-speed-command))
19382 (t (let (org-use-speed-commands)
19383 (call-interactively 'org-self-insert-command)))))
19384 ((and
19385 (org-table-p)
19386 (progn
19387 ;; check if we blank the field, and if that triggers align
19388 (and (featurep 'org-table) org-table-auto-blank-field
19389 (member last-command
19390 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19391 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19392 ;; got extra space, this field does not determine column width
19393 (let (org-table-may-need-update) (org-table-blank-field))
19394 ;; no extra space, this field may determine column width
19395 (org-table-blank-field)))
19397 (eq N 1)
19398 (looking-at "[^|\n]* |"))
19399 (let (org-table-may-need-update)
19400 (goto-char (1- (match-end 0)))
19401 (backward-delete-char 1)
19402 (goto-char (match-beginning 0))
19403 (self-insert-command N)))
19405 (setq org-table-may-need-update t)
19406 (self-insert-command N)
19407 (org-fix-tags-on-the-fly)
19408 (if org-self-insert-cluster-for-undo
19409 (if (not (eq last-command 'org-self-insert-command))
19410 (setq org-self-insert-command-undo-counter 1)
19411 (if (>= org-self-insert-command-undo-counter 20)
19412 (setq org-self-insert-command-undo-counter 1)
19413 (and (> org-self-insert-command-undo-counter 0)
19414 buffer-undo-list (listp buffer-undo-list)
19415 (not (cadr buffer-undo-list)) ; remove nil entry
19416 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19417 (setq org-self-insert-command-undo-counter
19418 (1+ org-self-insert-command-undo-counter))))))))
19420 (defun org-check-before-invisible-edit (kind)
19421 "Check is editing if kind KIND would be dangerous with invisible text around.
19422 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19423 ;; First, try to get out of here as quickly as possible, to reduce overhead
19424 (if (and org-catch-invisible-edits
19425 (or (not (boundp 'visible-mode)) (not visible-mode))
19426 (or (get-char-property (point) 'invisible)
19427 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19428 ;; OK, we need to take a closer look
19429 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19430 (invisible-before-point (if (bobp) nil (get-char-property
19431 (1- (point)) 'invisible)))
19432 (border-and-ok-direction
19434 ;; Check if we are acting predictably before invisible text
19435 (and invisible-at-point (not invisible-before-point)
19436 (memq kind '(insert delete-backward)))
19437 ;; Check if we are acting predictably after invisible text
19438 ;; This works not well, and I have turned it off. It seems
19439 ;; better to always show and stop after invisible text.
19440 ;; (and (not invisible-at-point) invisible-before-point
19441 ;; (memq kind '(insert delete)))
19443 (when (or (memq invisible-at-point '(outline org-hide-block t))
19444 (memq invisible-before-point '(outline org-hide-block t)))
19445 (if (eq org-catch-invisible-edits 'error)
19446 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19447 (if (and org-custom-properties-overlays
19448 (y-or-n-p "Display invisible properties in this buffer? "))
19449 (org-toggle-custom-properties-visibility)
19450 ;; Make the area visible
19451 (save-excursion
19452 (if invisible-before-point
19453 (goto-char (previous-single-char-property-change
19454 (point) 'invisible)))
19455 (org-cycle))
19456 (cond
19457 ((eq org-catch-invisible-edits 'show)
19458 ;; That's it, we do the edit after showing
19459 (message
19460 "Unfolding invisible region around point before editing")
19461 (sit-for 1))
19462 ((and (eq org-catch-invisible-edits 'smart)
19463 border-and-ok-direction)
19464 (message "Unfolding invisible region around point before editing"))
19466 ;; Don't do the edit, make the user repeat it in full visibility
19467 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19469 (defun org-fix-tags-on-the-fly ()
19470 (when (and (equal (char-after (point-at-bol)) ?*)
19471 (org-at-heading-p))
19472 (org-align-tags-here org-tags-column)))
19474 (defun org-delete-backward-char (N)
19475 "Like `delete-backward-char', insert whitespace at field end in tables.
19476 When deleting backwards, in tables this function will insert whitespace in
19477 front of the next \"|\" separator, to keep the table aligned. The table will
19478 still be marked for re-alignment if the field did fill the entire column,
19479 because, in this case the deletion might narrow the column."
19480 (interactive "p")
19481 (save-match-data
19482 (org-check-before-invisible-edit 'delete-backward)
19483 (if (and (org-table-p)
19484 (eq N 1)
19485 (string-match "|" (buffer-substring (point-at-bol) (point)))
19486 (looking-at ".*?|"))
19487 (let ((pos (point))
19488 (noalign (looking-at "[^|\n\r]* |"))
19489 (c org-table-may-need-update))
19490 (backward-delete-char N)
19491 (if (not overwrite-mode)
19492 (progn
19493 (skip-chars-forward "^|")
19494 (insert " ")
19495 (goto-char (1- pos))))
19496 ;; noalign: if there were two spaces at the end, this field
19497 ;; does not determine the width of the column.
19498 (if noalign (setq org-table-may-need-update c)))
19499 (backward-delete-char N)
19500 (org-fix-tags-on-the-fly))))
19502 (defun org-delete-char (N)
19503 "Like `delete-char', but insert whitespace at field end in tables.
19504 When deleting characters, in tables this function will insert whitespace in
19505 front of the next \"|\" separator, to keep the table aligned. The table will
19506 still be marked for re-alignment if the field did fill the entire column,
19507 because, in this case the deletion might narrow the column."
19508 (interactive "p")
19509 (save-match-data
19510 (org-check-before-invisible-edit 'delete)
19511 (if (and (org-table-p)
19512 (not (bolp))
19513 (not (= (char-after) ?|))
19514 (eq N 1))
19515 (if (looking-at ".*?|")
19516 (let ((pos (point))
19517 (noalign (looking-at "[^|\n\r]* |"))
19518 (c org-table-may-need-update))
19519 (replace-match
19520 (concat (substring (match-string 0) 1 -1) " |") nil t)
19521 (goto-char pos)
19522 ;; noalign: if there were two spaces at the end, this field
19523 ;; does not determine the width of the column.
19524 (if noalign (setq org-table-may-need-update c)))
19525 (delete-char N))
19526 (delete-char N)
19527 (org-fix-tags-on-the-fly))))
19529 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19530 (put 'org-self-insert-command 'delete-selection
19531 (lambda ()
19532 (not (run-hook-with-args-until-success
19533 'self-insert-uses-region-functions))))
19534 (put 'orgtbl-self-insert-command 'delete-selection
19535 (lambda ()
19536 (not (run-hook-with-args-until-success
19537 'self-insert-uses-region-functions))))
19538 (put 'org-delete-char 'delete-selection 'supersede)
19539 (put 'org-delete-backward-char 'delete-selection 'supersede)
19540 (put 'org-yank 'delete-selection 'yank)
19542 ;; Make `flyspell-mode' delay after some commands
19543 (put 'org-self-insert-command 'flyspell-delayed t)
19544 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19545 (put 'org-delete-char 'flyspell-delayed t)
19546 (put 'org-delete-backward-char 'flyspell-delayed t)
19548 ;; Make pabbrev-mode expand after org-mode commands
19549 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19550 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19552 (defun org-remap (map &rest commands)
19553 "In MAP, remap the functions given in COMMANDS.
19554 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19555 (let (new old)
19556 (while commands
19557 (setq old (pop commands) new (pop commands))
19558 (if (fboundp 'command-remapping)
19559 (org-defkey map (vector 'remap old) new)
19560 (substitute-key-definition old new map global-map)))))
19562 (defun org-transpose-words ()
19563 "Transpose words for Org.
19564 This uses the `org-mode-transpose-word-syntax-table' syntax
19565 table, which interprets characters in `org-emphasis-alist' as
19566 word constituents."
19567 (interactive)
19568 (with-syntax-table org-mode-transpose-word-syntax-table
19569 (call-interactively 'transpose-words)))
19570 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19572 (when (eq org-enable-table-editor 'optimized)
19573 ;; If the user wants maximum table support, we need to hijack
19574 ;; some standard editing functions
19575 (org-remap org-mode-map
19576 'self-insert-command 'org-self-insert-command
19577 'delete-char 'org-delete-char
19578 'delete-backward-char 'org-delete-backward-char)
19579 (org-defkey org-mode-map "|" 'org-force-self-insert))
19581 (defvar org-ctrl-c-ctrl-c-hook nil
19582 "Hook for functions attaching themselves to `C-c C-c'.
19584 This can be used to add additional functionality to the C-c C-c
19585 key which executes context-dependent commands. This hook is run
19586 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19587 run after the last test.
19589 Each function will be called with no arguments. The function
19590 must check if the context is appropriate for it to act. If yes,
19591 it should do its thing and then return a non-nil value. If the
19592 context is wrong, just do nothing and return nil.")
19594 (defvar org-ctrl-c-ctrl-c-final-hook nil
19595 "Hook for functions attaching themselves to `C-c C-c'.
19597 This can be used to add additional functionality to the C-c C-c
19598 key which executes context-dependent commands. This hook is run
19599 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19600 before the first test.
19602 Each function will be called with no arguments. The function
19603 must check if the context is appropriate for it to act. If yes,
19604 it should do its thing and then return a non-nil value. If the
19605 context is wrong, just do nothing and return nil.")
19607 (defvar org-tab-first-hook nil
19608 "Hook for functions to attach themselves to TAB.
19609 See `org-ctrl-c-ctrl-c-hook' for more information.
19610 This hook runs as the first action when TAB is pressed, even before
19611 `org-cycle' messes around with the `outline-regexp' to cater for
19612 inline tasks and plain list item folding.
19613 If any function in this hook returns t, any other actions that
19614 would have been caused by TAB (such as table field motion or visibility
19615 cycling) will not occur.")
19617 (defvar org-tab-after-check-for-table-hook nil
19618 "Hook for functions to attach themselves to TAB.
19619 See `org-ctrl-c-ctrl-c-hook' for more information.
19620 This hook runs after it has been established that the cursor is not in a
19621 table, but before checking if the cursor is in a headline or if global cycling
19622 should be done.
19623 If any function in this hook returns t, not other actions like visibility
19624 cycling will be done.")
19626 (defvar org-tab-after-check-for-cycling-hook nil
19627 "Hook for functions to attach themselves to TAB.
19628 See `org-ctrl-c-ctrl-c-hook' for more information.
19629 This hook runs after it has been established that not table field motion and
19630 not visibility should be done because of current context. This is probably
19631 the place where a package like yasnippets can hook in.")
19633 (defvar org-tab-before-tab-emulation-hook nil
19634 "Hook for functions to attach themselves to TAB.
19635 See `org-ctrl-c-ctrl-c-hook' for more information.
19636 This hook runs after every other options for TAB have been exhausted, but
19637 before indentation and \t insertion takes place.")
19639 (defvar org-metaleft-hook nil
19640 "Hook for functions attaching themselves to `M-left'.
19641 See `org-ctrl-c-ctrl-c-hook' for more information.")
19642 (defvar org-metaright-hook nil
19643 "Hook for functions attaching themselves to `M-right'.
19644 See `org-ctrl-c-ctrl-c-hook' for more information.")
19645 (defvar org-metaup-hook nil
19646 "Hook for functions attaching themselves to `M-up'.
19647 See `org-ctrl-c-ctrl-c-hook' for more information.")
19648 (defvar org-metadown-hook nil
19649 "Hook for functions attaching themselves to `M-down'.
19650 See `org-ctrl-c-ctrl-c-hook' for more information.")
19651 (defvar org-shiftmetaleft-hook nil
19652 "Hook for functions attaching themselves to `M-S-left'.
19653 See `org-ctrl-c-ctrl-c-hook' for more information.")
19654 (defvar org-shiftmetaright-hook nil
19655 "Hook for functions attaching themselves to `M-S-right'.
19656 See `org-ctrl-c-ctrl-c-hook' for more information.")
19657 (defvar org-shiftmetaup-hook nil
19658 "Hook for functions attaching themselves to `M-S-up'.
19659 See `org-ctrl-c-ctrl-c-hook' for more information.")
19660 (defvar org-shiftmetadown-hook nil
19661 "Hook for functions attaching themselves to `M-S-down'.
19662 See `org-ctrl-c-ctrl-c-hook' for more information.")
19663 (defvar org-metareturn-hook nil
19664 "Hook for functions attaching themselves to `M-RET'.
19665 See `org-ctrl-c-ctrl-c-hook' for more information.")
19666 (defvar org-shiftup-hook nil
19667 "Hook for functions attaching themselves to `S-up'.
19668 See `org-ctrl-c-ctrl-c-hook' for more information.")
19669 (defvar org-shiftup-final-hook nil
19670 "Hook for functions attaching themselves to `S-up'.
19671 This one runs after all other options except shift-select have been excluded.
19672 See `org-ctrl-c-ctrl-c-hook' for more information.")
19673 (defvar org-shiftdown-hook nil
19674 "Hook for functions attaching themselves to `S-down'.
19675 See `org-ctrl-c-ctrl-c-hook' for more information.")
19676 (defvar org-shiftdown-final-hook nil
19677 "Hook for functions attaching themselves to `S-down'.
19678 This one runs after all other options except shift-select have been excluded.
19679 See `org-ctrl-c-ctrl-c-hook' for more information.")
19680 (defvar org-shiftleft-hook nil
19681 "Hook for functions attaching themselves to `S-left'.
19682 See `org-ctrl-c-ctrl-c-hook' for more information.")
19683 (defvar org-shiftleft-final-hook nil
19684 "Hook for functions attaching themselves to `S-left'.
19685 This one runs after all other options except shift-select have been excluded.
19686 See `org-ctrl-c-ctrl-c-hook' for more information.")
19687 (defvar org-shiftright-hook nil
19688 "Hook for functions attaching themselves to `S-right'.
19689 See `org-ctrl-c-ctrl-c-hook' for more information.")
19690 (defvar org-shiftright-final-hook nil
19691 "Hook for functions attaching themselves to `S-right'.
19692 This one runs after all other options except shift-select have been excluded.
19693 See `org-ctrl-c-ctrl-c-hook' for more information.")
19695 (defun org-modifier-cursor-error ()
19696 "Throw an error, a modified cursor command was applied in wrong context."
19697 (user-error "This command is active in special context like tables, headlines or items"))
19699 (defun org-shiftselect-error ()
19700 "Throw an error because Shift-Cursor command was applied in wrong context."
19701 (if (and (boundp 'shift-select-mode) shift-select-mode)
19702 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19703 (user-error "This command works only in special context like headlines or timestamps")))
19705 (defun org-call-for-shift-select (cmd)
19706 (let ((this-command-keys-shift-translated t))
19707 (call-interactively cmd)))
19709 (defun org-shifttab (&optional arg)
19710 "Global visibility cycling or move to previous table field.
19711 Call `org-table-previous-field' within a table.
19712 When ARG is nil, cycle globally through visibility states.
19713 When ARG is a numeric prefix, show contents of this level."
19714 (interactive "P")
19715 (cond
19716 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19717 ((integerp arg)
19718 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19719 (message "Content view to level: %d" arg)
19720 (org-content (prefix-numeric-value arg2))
19721 (org-cycle-show-empty-lines t)
19722 (setq org-cycle-global-status 'overview)))
19723 (t (call-interactively 'org-global-cycle))))
19725 (defun org-shiftmetaleft ()
19726 "Promote subtree or delete table column.
19727 Calls `org-promote-subtree', `org-outdent-item-tree', or
19728 `org-table-delete-column', depending on context. See the
19729 individual commands for more information."
19730 (interactive)
19731 (cond
19732 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19733 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19734 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19735 ((if (not (org-region-active-p)) (org-at-item-p)
19736 (save-excursion (goto-char (region-beginning))
19737 (org-at-item-p)))
19738 (call-interactively 'org-outdent-item-tree))
19739 (t (org-modifier-cursor-error))))
19741 (defun org-shiftmetaright ()
19742 "Demote subtree or insert table column.
19743 Calls `org-demote-subtree', `org-indent-item-tree', or
19744 `org-table-insert-column', depending on context. See the
19745 individual commands for more information."
19746 (interactive)
19747 (cond
19748 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19749 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19750 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19751 ((if (not (org-region-active-p)) (org-at-item-p)
19752 (save-excursion (goto-char (region-beginning))
19753 (org-at-item-p)))
19754 (call-interactively 'org-indent-item-tree))
19755 (t (org-modifier-cursor-error))))
19757 (defun org-shiftmetaup (&optional arg)
19758 "Move subtree up or kill table row.
19759 Calls `org-move-subtree-up' or `org-table-kill-row' or
19760 `org-move-item-up' or `org-timestamp-up', depending on context.
19761 See the individual commands for more information."
19762 (interactive "P")
19763 (cond
19764 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19765 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19766 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19767 ((org-at-item-p) (call-interactively 'org-move-item-up))
19768 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19769 (call-interactively 'org-timestamp-up)))
19770 (t (call-interactively 'org-drag-line-backward))))
19772 (defun org-shiftmetadown (&optional arg)
19773 "Move subtree down or insert table row.
19774 Calls `org-move-subtree-down' or `org-table-insert-row' or
19775 `org-move-item-down' or `org-timestamp-up', depending on context.
19776 See the individual commands for more information."
19777 (interactive "P")
19778 (cond
19779 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19780 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19781 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19782 ((org-at-item-p) (call-interactively 'org-move-item-down))
19783 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19784 (call-interactively 'org-timestamp-down)))
19785 (t (call-interactively 'org-drag-line-forward))))
19787 (defsubst org-hidden-tree-error ()
19788 (user-error
19789 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19791 (defun org-metaleft (&optional arg)
19792 "Promote heading or move table column to left.
19793 Calls `org-do-promote' or `org-table-move-column', depending on context.
19794 With no specific context, calls the Emacs default `backward-word'.
19795 See the individual commands for more information."
19796 (interactive "P")
19797 (cond
19798 ((run-hook-with-args-until-success 'org-metaleft-hook))
19799 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19800 ((org-with-limited-levels
19801 (or (org-at-heading-p)
19802 (and (org-region-active-p)
19803 (save-excursion
19804 (goto-char (region-beginning))
19805 (org-at-heading-p)))))
19806 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19807 (call-interactively 'org-do-promote))
19808 ;; At an inline task.
19809 ((org-at-heading-p)
19810 (call-interactively 'org-inlinetask-promote))
19811 ((or (org-at-item-p)
19812 (and (org-region-active-p)
19813 (save-excursion
19814 (goto-char (region-beginning))
19815 (org-at-item-p))))
19816 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19817 (call-interactively 'org-outdent-item))
19818 (t (call-interactively 'backward-word))))
19820 (defun org-metaright (&optional arg)
19821 "Demote a subtree, a list item or move table column to right.
19822 In front of a drawer or a block keyword, indent it correctly.
19823 With no specific context, calls the Emacs default `forward-word'.
19824 See the individual commands for more information."
19825 (interactive "P")
19826 (cond
19827 ((run-hook-with-args-until-success 'org-metaright-hook))
19828 ((org-at-table-p) (call-interactively 'org-table-move-column))
19829 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19830 ((org-at-block-p) (call-interactively 'org-indent-block))
19831 ((org-with-limited-levels
19832 (or (org-at-heading-p)
19833 (and (org-region-active-p)
19834 (save-excursion
19835 (goto-char (region-beginning))
19836 (org-at-heading-p)))))
19837 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19838 (call-interactively 'org-do-demote))
19839 ;; At an inline task.
19840 ((org-at-heading-p)
19841 (call-interactively 'org-inlinetask-demote))
19842 ((or (org-at-item-p)
19843 (and (org-region-active-p)
19844 (save-excursion
19845 (goto-char (region-beginning))
19846 (org-at-item-p))))
19847 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19848 (call-interactively 'org-indent-item))
19849 (t (call-interactively 'forward-word))))
19851 (defun org-check-for-hidden (what)
19852 "Check if there are hidden headlines/items in the current visual line.
19853 WHAT can be either `headlines' or `items'. If the current line is
19854 an outline or item heading and it has a folded subtree below it,
19855 this function returns t, nil otherwise."
19856 (let ((re (cond
19857 ((eq what 'headlines) org-outline-regexp-bol)
19858 ((eq what 'items) (org-item-beginning-re))
19859 (t (error "This should not happen"))))
19860 beg end)
19861 (save-excursion
19862 (catch 'exit
19863 (unless (org-region-active-p)
19864 (setq beg (point-at-bol))
19865 (beginning-of-line 2)
19866 (while (and (not (eobp)) ;; this is like `next-line'
19867 (get-char-property (1- (point)) 'invisible))
19868 (beginning-of-line 2))
19869 (setq end (point))
19870 (goto-char beg)
19871 (goto-char (point-at-eol))
19872 (setq end (max end (point)))
19873 (while (re-search-forward re end t)
19874 (if (get-char-property (match-beginning 0) 'invisible)
19875 (throw 'exit t))))
19876 nil))))
19878 (defun org-metaup (&optional arg)
19879 "Move subtree up or move table row up.
19880 Calls `org-move-subtree-up' or `org-table-move-row' or
19881 `org-move-item-up', depending on context. See the individual commands
19882 for more information."
19883 (interactive "P")
19884 (cond
19885 ((run-hook-with-args-until-success 'org-metaup-hook))
19886 ((org-region-active-p)
19887 (let* ((a (min (region-beginning) (region-end)))
19888 (b (1- (max (region-beginning) (region-end))))
19889 (c (save-excursion (goto-char a)
19890 (move-beginning-of-line 0)))
19891 (d (save-excursion (goto-char a)
19892 (move-end-of-line 0) (point))))
19893 (transpose-regions a b c d)
19894 (goto-char c)))
19895 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19896 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19897 ((org-at-item-p) (call-interactively 'org-move-item-up))
19898 (t (org-drag-element-backward))))
19900 (defun org-metadown (&optional arg)
19901 "Move subtree down or move table row down.
19902 Calls `org-move-subtree-down' or `org-table-move-row' or
19903 `org-move-item-down', depending on context. See the individual
19904 commands for more information."
19905 (interactive "P")
19906 (cond
19907 ((run-hook-with-args-until-success 'org-metadown-hook))
19908 ((org-region-active-p)
19909 (let* ((a (min (region-beginning) (region-end)))
19910 (b (max (region-beginning) (region-end)))
19911 (c (save-excursion (goto-char b)
19912 (move-beginning-of-line 1)))
19913 (d (save-excursion (goto-char b)
19914 (move-end-of-line 1) (1+ (point)))))
19915 (transpose-regions a b c d)
19916 (goto-char d)))
19917 ((org-at-table-p) (call-interactively 'org-table-move-row))
19918 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19919 ((org-at-item-p) (call-interactively 'org-move-item-down))
19920 (t (org-drag-element-forward))))
19922 (defun org-shiftup (&optional arg)
19923 "Increase item in timestamp or increase priority of current headline.
19924 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19925 depending on context. See the individual commands for more information."
19926 (interactive "P")
19927 (cond
19928 ((run-hook-with-args-until-success 'org-shiftup-hook))
19929 ((and org-support-shift-select (org-region-active-p))
19930 (org-call-for-shift-select 'previous-line))
19931 ((org-at-timestamp-p t)
19932 (call-interactively (if org-edit-timestamp-down-means-later
19933 'org-timestamp-down 'org-timestamp-up)))
19934 ((and (not (eq org-support-shift-select 'always))
19935 org-enable-priority-commands
19936 (org-at-heading-p))
19937 (call-interactively 'org-priority-up))
19938 ((and (not org-support-shift-select) (org-at-item-p))
19939 (call-interactively 'org-previous-item))
19940 ((org-clocktable-try-shift 'up arg))
19941 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19942 (org-support-shift-select
19943 (org-call-for-shift-select 'previous-line))
19944 (t (org-shiftselect-error))))
19946 (defun org-shiftdown (&optional arg)
19947 "Decrease item in timestamp or decrease priority of current headline.
19948 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19949 depending on context. See the individual commands for more information."
19950 (interactive "P")
19951 (cond
19952 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19953 ((and org-support-shift-select (org-region-active-p))
19954 (org-call-for-shift-select 'next-line))
19955 ((org-at-timestamp-p t)
19956 (call-interactively (if org-edit-timestamp-down-means-later
19957 'org-timestamp-up 'org-timestamp-down)))
19958 ((and (not (eq org-support-shift-select 'always))
19959 org-enable-priority-commands
19960 (org-at-heading-p))
19961 (call-interactively 'org-priority-down))
19962 ((and (not org-support-shift-select) (org-at-item-p))
19963 (call-interactively 'org-next-item))
19964 ((org-clocktable-try-shift 'down arg))
19965 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19966 (org-support-shift-select
19967 (org-call-for-shift-select 'next-line))
19968 (t (org-shiftselect-error))))
19970 (defun org-shiftright (&optional arg)
19971 "Cycle the thing at point or in the current line, depending on context.
19972 Depending on context, this does one of the following:
19974 - switch a timestamp at point one day into the future
19975 - on a headline, switch to the next TODO keyword.
19976 - on an item, switch entire list to the next bullet type
19977 - on a property line, switch to the next allowed value
19978 - on a clocktable definition line, move time block into the future"
19979 (interactive "P")
19980 (cond
19981 ((run-hook-with-args-until-success 'org-shiftright-hook))
19982 ((and org-support-shift-select (org-region-active-p))
19983 (org-call-for-shift-select 'forward-char))
19984 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19985 ((and (not (eq org-support-shift-select 'always))
19986 (org-at-heading-p))
19987 (let ((org-inhibit-logging
19988 (not org-treat-S-cursor-todo-selection-as-state-change))
19989 (org-inhibit-blocking
19990 (not org-treat-S-cursor-todo-selection-as-state-change)))
19991 (org-call-with-arg 'org-todo 'right)))
19992 ((or (and org-support-shift-select
19993 (not (eq org-support-shift-select 'always))
19994 (org-at-item-bullet-p))
19995 (and (not org-support-shift-select) (org-at-item-p)))
19996 (org-call-with-arg 'org-cycle-list-bullet nil))
19997 ((and (not (eq org-support-shift-select 'always))
19998 (org-at-property-p))
19999 (call-interactively 'org-property-next-allowed-value))
20000 ((org-clocktable-try-shift 'right arg))
20001 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20002 (org-support-shift-select
20003 (org-call-for-shift-select 'forward-char))
20004 (t (org-shiftselect-error))))
20006 (defun org-shiftleft (&optional arg)
20007 "Cycle the thing at point or in the current line, depending on context.
20008 Depending on context, this does one of the following:
20010 - switch a timestamp at point one day into the past
20011 - on a headline, switch to the previous TODO keyword.
20012 - on an item, switch entire list to the previous bullet type
20013 - on a property line, switch to the previous allowed value
20014 - on a clocktable definition line, move time block into the past"
20015 (interactive "P")
20016 (cond
20017 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20018 ((and org-support-shift-select (org-region-active-p))
20019 (org-call-for-shift-select 'backward-char))
20020 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20021 ((and (not (eq org-support-shift-select 'always))
20022 (org-at-heading-p))
20023 (let ((org-inhibit-logging
20024 (not org-treat-S-cursor-todo-selection-as-state-change))
20025 (org-inhibit-blocking
20026 (not org-treat-S-cursor-todo-selection-as-state-change)))
20027 (org-call-with-arg 'org-todo 'left)))
20028 ((or (and org-support-shift-select
20029 (not (eq org-support-shift-select 'always))
20030 (org-at-item-bullet-p))
20031 (and (not org-support-shift-select) (org-at-item-p)))
20032 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20033 ((and (not (eq org-support-shift-select 'always))
20034 (org-at-property-p))
20035 (call-interactively 'org-property-previous-allowed-value))
20036 ((org-clocktable-try-shift 'left arg))
20037 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20038 (org-support-shift-select
20039 (org-call-for-shift-select 'backward-char))
20040 (t (org-shiftselect-error))))
20042 (defun org-shiftcontrolright ()
20043 "Switch to next TODO set."
20044 (interactive)
20045 (cond
20046 ((and org-support-shift-select (org-region-active-p))
20047 (org-call-for-shift-select 'forward-word))
20048 ((and (not (eq org-support-shift-select 'always))
20049 (org-at-heading-p))
20050 (org-call-with-arg 'org-todo 'nextset))
20051 (org-support-shift-select
20052 (org-call-for-shift-select 'forward-word))
20053 (t (org-shiftselect-error))))
20055 (defun org-shiftcontrolleft ()
20056 "Switch to previous TODO set."
20057 (interactive)
20058 (cond
20059 ((and org-support-shift-select (org-region-active-p))
20060 (org-call-for-shift-select 'backward-word))
20061 ((and (not (eq org-support-shift-select 'always))
20062 (org-at-heading-p))
20063 (org-call-with-arg 'org-todo 'previousset))
20064 (org-support-shift-select
20065 (org-call-for-shift-select 'backward-word))
20066 (t (org-shiftselect-error))))
20068 (defun org-shiftcontrolup (&optional n)
20069 "Change timestamps synchronously up in CLOCK log lines.
20070 Optional argument N tells to change by that many units."
20071 (interactive "P")
20072 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20073 (let (org-support-shift-select)
20074 (org-clock-timestamps-up n))
20075 (user-error "Not at a clock log")))
20077 (defun org-shiftcontroldown (&optional n)
20078 "Change timestamps synchronously down in CLOCK log lines.
20079 Optional argument N tells to change by that many units."
20080 (interactive "P")
20081 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20082 (let (org-support-shift-select)
20083 (org-clock-timestamps-down n))
20084 (user-error "Not at a clock log")))
20086 (defun org-ctrl-c-ret ()
20087 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20088 (interactive)
20089 (cond
20090 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20091 (t (call-interactively 'org-insert-heading))))
20093 (defun org-find-visible ()
20094 (let ((s (point)))
20095 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20096 (get-char-property s 'invisible)))
20098 (defun org-find-invisible ()
20099 (let ((s (point)))
20100 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20101 (not (get-char-property s 'invisible))))
20104 (defun org-copy-visible (beg end)
20105 "Copy the visible parts of the region."
20106 (interactive "r")
20107 (let (snippets s)
20108 (save-excursion
20109 (save-restriction
20110 (narrow-to-region beg end)
20111 (setq s (goto-char (point-min)))
20112 (while (not (= (point) (point-max)))
20113 (goto-char (org-find-invisible))
20114 (push (buffer-substring s (point)) snippets)
20115 (setq s (goto-char (org-find-visible))))))
20116 (kill-new (apply 'concat (nreverse snippets)))))
20118 (defun org-copy-special ()
20119 "Copy region in table or copy current subtree.
20120 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20121 See the individual commands for more information."
20122 (interactive)
20123 (call-interactively
20124 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20126 (defun org-cut-special ()
20127 "Cut region in table or cut current subtree.
20128 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20129 See the individual commands for more information."
20130 (interactive)
20131 (call-interactively
20132 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20134 (defun org-paste-special (arg)
20135 "Paste rectangular region into table, or past subtree relative to level.
20136 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20137 See the individual commands for more information."
20138 (interactive "P")
20139 (if (org-at-table-p)
20140 (org-table-paste-rectangle)
20141 (org-paste-subtree arg)))
20143 (defsubst org-in-fixed-width-region-p ()
20144 "Is point in a fixed-width region?"
20145 (save-match-data
20146 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20148 (defun org-edit-special (&optional arg)
20149 "Call a special editor for the element at point.
20150 When at a table, call the formula editor with `org-table-edit-formulas'.
20151 When in a source code block, call `org-edit-src-code'.
20152 When in a fixed-width region, call `org-edit-fixed-width-region'.
20153 When at an #+INCLUDE keyword, visit the included file.
20154 On a link, call `ffap' to visit the link at point.
20155 Otherwise, return a user error."
20156 (interactive "P")
20157 (let ((element (org-element-at-point)))
20158 (assert (not buffer-read-only) nil
20159 "Buffer is read-only: %s" (buffer-name))
20160 (case (org-element-type element)
20161 (src-block
20162 (if (not arg) (org-edit-src-code)
20163 (let* ((info (org-babel-get-src-block-info))
20164 (lang (nth 0 info))
20165 (params (nth 2 info))
20166 (session (cdr (assq :session params))))
20167 (if (not session) (org-edit-src-code)
20168 ;; At a src-block with a session and function called with
20169 ;; an ARG: switch to the buffer related to the inferior
20170 ;; process.
20171 (switch-to-buffer
20172 (funcall (intern (concat "org-babel-prep-session:" lang))
20173 session params))))))
20174 (keyword
20175 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20176 (find-file
20177 (org-remove-double-quotes
20178 (car (org-split-string (org-element-property :value element)))))
20179 (user-error "No special environment to edit here")))
20180 (table
20181 (if (eq (org-element-property :type element) 'table.el)
20182 (org-edit-src-code)
20183 (call-interactively 'org-table-edit-formulas)))
20184 ;; Only Org tables contain `table-row' type elements.
20185 (table-row (call-interactively 'org-table-edit-formulas))
20186 ((example-block export-block) (org-edit-src-code))
20187 (fixed-width (org-edit-fixed-width-region))
20188 (otherwise
20189 ;; No notable element at point. Though, we may be at a link,
20190 ;; which is an object. Thus, scan deeper.
20191 (if (eq (org-element-type (org-element-context element)) 'link)
20192 (call-interactively 'ffap)
20193 (user-error "No special environment to edit here"))))))
20195 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20196 (defun org-ctrl-c-ctrl-c (&optional arg)
20197 "Set tags in headline, or update according to changed information at point.
20199 This command does many different things, depending on context:
20201 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20202 this is what we do.
20204 - If the cursor is on a statistics cookie, update it.
20206 - If the cursor is in a headline, prompt for tags and insert them
20207 into the current line, aligned to `org-tags-column'. When called
20208 with prefix arg, realign all tags in the current buffer.
20210 - If the cursor is in one of the special #+KEYWORD lines, this
20211 triggers scanning the buffer for these lines and updating the
20212 information.
20214 - If the cursor is inside a table, realign the table. This command
20215 works even if the automatic table editor has been turned off.
20217 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20218 the entire table.
20220 - If the cursor is at a footnote reference or definition, jump to
20221 the corresponding definition or references, respectively.
20223 - If the cursor is a the beginning of a dynamic block, update it.
20225 - If the current buffer is a capture buffer, close note and file it.
20227 - If the cursor is on a <<<target>>>, update radio targets and
20228 corresponding links in this buffer.
20230 - If the cursor is on a numbered item in a plain list, renumber the
20231 ordered list.
20233 - If the cursor is on a checkbox, toggle it.
20235 - If the cursor is on a code block, evaluate it. The variable
20236 `org-confirm-babel-evaluate' can be used to control prompting
20237 before code block evaluation, by default every code block
20238 evaluation requires confirmation. Code block evaluation can be
20239 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20240 (interactive "P")
20241 (cond
20242 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20243 org-occur-highlights
20244 org-latex-fragment-image-overlays)
20245 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20246 (org-remove-occur-highlights)
20247 (org-remove-latex-fragment-image-overlays)
20248 (message "Temporary highlights/overlays removed from current buffer"))
20249 ((and (local-variable-p 'org-finish-function (current-buffer))
20250 (fboundp org-finish-function))
20251 (funcall org-finish-function))
20252 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20254 (let* ((context (org-element-context)) (type (org-element-type context)))
20255 ;; Test if point is within a blank line.
20256 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20257 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20258 (user-error "C-c C-c can do nothing useful at this location"))
20259 (case type
20260 ;; When at a link, act according to the parent instead.
20261 (link (setq context (org-element-property :parent context))
20262 (setq type (org-element-type context)))
20263 ;; Unsupported object types: check parent element instead.
20264 ((bold code entity export-snippet inline-babel-call inline-src-block
20265 italic latex-fragment line-break macro strike-through subscript
20266 superscript underline verbatim)
20267 (while (and (setq context (org-element-property :parent context))
20268 (not (memq (setq type (org-element-type context))
20269 '(paragraph verse-block table-cell)))))))
20270 ;; For convenience: at the first line of a paragraph on the
20271 ;; same line as an item, apply function on that item instead.
20272 (when (eq type 'paragraph)
20273 (let ((parent (org-element-property :parent context)))
20274 (when (and (eq (org-element-type parent) 'item)
20275 (= (point-at-bol) (org-element-property :begin parent)))
20276 (setq context parent type 'item))))
20277 ;; Act according to type of element or object at point.
20278 (case type
20279 (clock (org-clock-update-time-maybe))
20280 (dynamic-block
20281 (save-excursion
20282 (goto-char (org-element-property :post-affiliated context))
20283 (org-update-dblock)))
20284 (footnote-definition
20285 (goto-char (org-element-property :post-affiliated context))
20286 (call-interactively 'org-footnote-action))
20287 (footnote-reference (call-interactively 'org-footnote-action))
20288 ((headline inlinetask)
20289 (save-excursion (goto-char (org-element-property :begin context))
20290 (call-interactively 'org-set-tags)))
20291 (item
20292 ;; At an item: a double C-u set checkbox to "[-]"
20293 ;; unconditionally, whereas a single one will toggle its
20294 ;; presence. Without an universal argument, if the item
20295 ;; has a checkbox, toggle it. Otherwise repair the list.
20296 (let* ((box (org-element-property :checkbox context))
20297 (struct (org-element-property :structure context))
20298 (old-struct (copy-tree struct))
20299 (parents (org-list-parents-alist struct))
20300 (prevs (org-list-prevs-alist struct))
20301 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20302 (org-list-set-checkbox
20303 (org-element-property :begin context) struct
20304 (cond ((equal arg '(16)) "[-]")
20305 ((and (not box) (equal arg '(4))) "[ ]")
20306 ((or (not box) (equal arg '(4))) nil)
20307 ((eq box 'on) "[ ]")
20308 (t "[X]")))
20309 ;; Mimic `org-list-write-struct' but with grabbing
20310 ;; a return value from `org-list-struct-fix-box'.
20311 (org-list-struct-fix-ind struct parents 2)
20312 (org-list-struct-fix-item-end struct)
20313 (org-list-struct-fix-bul struct prevs)
20314 (org-list-struct-fix-ind struct parents)
20315 (let ((block-item
20316 (org-list-struct-fix-box struct parents prevs orderedp)))
20317 (if (and box (equal struct old-struct))
20318 (if (equal arg '(16))
20319 (message "Checkboxes already reset")
20320 (user-error "Cannot toggle this checkbox: %s"
20321 (if (eq box 'on)
20322 "all subitems checked"
20323 "unchecked subitems")))
20324 (org-list-struct-apply-struct struct old-struct)
20325 (org-update-checkbox-count-maybe))
20326 (when block-item
20327 (message "Checkboxes were removed due to empty box at line %d"
20328 (org-current-line block-item))))))
20329 (keyword
20330 (let ((org-inhibit-startup-visibility-stuff t)
20331 (org-startup-align-all-tables nil))
20332 (when (boundp 'org-table-coordinate-overlays)
20333 (mapc 'delete-overlay org-table-coordinate-overlays)
20334 (setq org-table-coordinate-overlays nil))
20335 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20336 (message "Local setup has been refreshed"))
20337 (plain-list
20338 ;; At a plain list, with a double C-u argument, set
20339 ;; checkboxes of each item to "[-]", whereas a single one
20340 ;; will toggle their presence according to the state of the
20341 ;; first item in the list. Without an argument, repair the
20342 ;; list.
20343 (let* ((begin (org-element-property :contents-begin context))
20344 (beginm (move-marker (make-marker) begin))
20345 (struct (org-element-property :structure context))
20346 (old-struct (copy-tree struct))
20347 (first-box (save-excursion
20348 (goto-char begin)
20349 (looking-at org-list-full-item-re)
20350 (match-string-no-properties 3)))
20351 (new-box (cond ((equal arg '(16)) "[-]")
20352 ((equal arg '(4)) (unless first-box "[ ]"))
20353 ((equal first-box "[X]") "[ ]")
20354 (t "[X]"))))
20355 (cond
20356 (arg
20357 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20358 (org-list-get-all-items
20359 begin struct (org-list-prevs-alist struct))))
20360 ((and first-box (eq (point) begin))
20361 ;; For convenience, when point is at bol on the first
20362 ;; item of the list and no argument is provided, simply
20363 ;; toggle checkbox of that item, if any.
20364 (org-list-set-checkbox begin struct new-box)))
20365 (org-list-write-struct
20366 struct (org-list-parents-alist struct) old-struct)
20367 (org-update-checkbox-count-maybe)
20368 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20369 ((property-drawer node-property)
20370 (call-interactively 'org-property-action))
20371 ((radio-target target)
20372 (call-interactively 'org-update-radio-target-regexp))
20373 (statistics-cookie
20374 (call-interactively 'org-update-statistics-cookies))
20375 ((table table-cell table-row)
20376 ;; At a table, recalculate every field and align it. Also
20377 ;; send the table if necessary. If the table has
20378 ;; a `table.el' type, just give up. At a table row or
20379 ;; cell, maybe recalculate line but always align table.
20380 (if (eq (org-element-property :type context) 'table.el)
20381 (message "Use C-c ' to edit table.el tables")
20382 (let ((org-enable-table-editor t))
20383 (if (or (eq type 'table)
20384 ;; Check if point is at a TBLFM line.
20385 (and (eq type 'table-row)
20386 (= (point) (org-element-property :end context))))
20387 (save-excursion
20388 (if (org-at-TBLFM-p)
20389 (progn (require 'org-table)
20390 (org-table-calc-current-TBLFM))
20391 (goto-char (org-element-property :contents-begin context))
20392 (org-call-with-arg 'org-table-recalculate (or arg t))
20393 (orgtbl-send-table 'maybe)))
20394 (org-table-maybe-eval-formula)
20395 (cond (arg (call-interactively 'org-table-recalculate))
20396 ((org-table-maybe-recalculate-line))
20397 (t (org-table-align)))))))
20398 (timestamp (org-timestamp-change 0 'day))
20399 (otherwise
20400 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20401 (user-error
20402 "C-c C-c can do nothing useful at this location")))))))))
20404 (defun org-mode-restart ()
20405 (interactive)
20406 (let ((indent-status (org-bound-and-true-p org-indent-mode)))
20407 (funcall major-mode)
20408 (hack-local-variables)
20409 (when (and indent-status (not (org-bound-and-true-p org-indent-mode)))
20410 (org-indent-mode -1)))
20411 (message "%s restarted" major-mode))
20413 (defun org-kill-note-or-show-branches ()
20414 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20415 (interactive)
20416 (if (not org-finish-function)
20417 (progn
20418 (hide-subtree)
20419 (call-interactively 'show-branches))
20420 (let ((org-note-abort t))
20421 (funcall org-finish-function))))
20423 (defun org-open-line (n)
20424 "Insert a new row in tables, call `open-line' elsewhere.
20425 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
20426 (interactive "*p")
20427 (cond
20428 ((not org-special-ctrl-o)
20429 (open-line n))
20430 ((org-at-table-p)
20431 (org-table-insert-row))
20433 (open-line n))))
20435 (defun org-return (&optional indent)
20436 "Goto next table row or insert a newline.
20437 Calls `org-table-next-row' or `newline', depending on context.
20438 See the individual commands for more information."
20439 (interactive)
20440 (let (org-ts-what)
20441 (cond
20442 ((or (bobp) (org-in-src-block-p))
20443 (if indent (newline-and-indent) (newline)))
20444 ((org-at-table-p)
20445 (org-table-justify-field-maybe)
20446 (call-interactively 'org-table-next-row))
20447 ;; when `newline-and-indent' is called within a list, make sure
20448 ;; text moved stays inside the item.
20449 ((and (org-in-item-p) indent)
20450 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20451 (progn
20452 (save-match-data (newline))
20453 (org-indent-line-to (length (match-string 0))))
20454 (let ((ind (org-get-indentation)))
20455 (newline)
20456 (if (org-looking-back org-list-end-re)
20457 (org-indent-line)
20458 (org-indent-line-to ind)))))
20459 ((and org-return-follows-link
20460 (org-at-timestamp-p t)
20461 (not (eq org-ts-what 'after)))
20462 (org-follow-timestamp-link))
20463 ((and org-return-follows-link
20464 (let ((tprop (get-text-property (point) 'face)))
20465 (or (eq tprop 'org-link)
20466 (and (listp tprop) (memq 'org-link tprop)))))
20467 (call-interactively 'org-open-at-point))
20468 ((and (org-at-heading-p)
20469 (looking-at
20470 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20471 (org-show-entry)
20472 (end-of-line 1)
20473 (newline))
20474 (t (if indent (newline-and-indent) (newline))))))
20476 (defun org-return-indent ()
20477 "Goto next table row or insert a newline and indent.
20478 Calls `org-table-next-row' or `newline-and-indent', depending on
20479 context. See the individual commands for more information."
20480 (interactive)
20481 (org-return t))
20483 (defun org-ctrl-c-star ()
20484 "Compute table, or change heading status of lines.
20485 Calls `org-table-recalculate' or `org-toggle-heading',
20486 depending on context."
20487 (interactive)
20488 (cond
20489 ((org-at-table-p)
20490 (call-interactively 'org-table-recalculate))
20492 ;; Convert all lines in region to list items
20493 (call-interactively 'org-toggle-heading))))
20495 (defun org-ctrl-c-minus ()
20496 "Insert separator line in table or modify bullet status of line.
20497 Also turns a plain line or a region of lines into list items.
20498 Calls `org-table-insert-hline', `org-toggle-item', or
20499 `org-cycle-list-bullet', depending on context."
20500 (interactive)
20501 (cond
20502 ((org-at-table-p)
20503 (call-interactively 'org-table-insert-hline))
20504 ((org-region-active-p)
20505 (call-interactively 'org-toggle-item))
20506 ((org-in-item-p)
20507 (call-interactively 'org-cycle-list-bullet))
20509 (call-interactively 'org-toggle-item))))
20511 (defun org-toggle-item (arg)
20512 "Convert headings or normal lines to items, items to normal lines.
20513 If there is no active region, only the current line is considered.
20515 If the first non blank line in the region is a headline, convert
20516 all headlines to items, shifting text accordingly.
20518 If it is an item, convert all items to normal lines.
20520 If it is normal text, change region into a list of items.
20521 With a prefix argument ARG, change the region in a single item."
20522 (interactive "P")
20523 (let ((shift-text
20524 (function
20525 ;; Shift text in current section to IND, from point to END.
20526 ;; The function leaves point to END line.
20527 (lambda (ind end)
20528 (let ((min-i 1000) (end (copy-marker end)))
20529 ;; First determine the minimum indentation (MIN-I) of
20530 ;; the text.
20531 (save-excursion
20532 (catch 'exit
20533 (while (< (point) end)
20534 (let ((i (org-get-indentation)))
20535 (cond
20536 ;; Skip blank lines and inline tasks.
20537 ((looking-at "^[ \t]*$"))
20538 ((looking-at org-outline-regexp-bol))
20539 ;; We can't find less than 0 indentation.
20540 ((zerop i) (throw 'exit (setq min-i 0)))
20541 ((< i min-i) (setq min-i i))))
20542 (forward-line))))
20543 ;; Then indent each line so that a line indented to
20544 ;; MIN-I becomes indented to IND. Ignore blank lines
20545 ;; and inline tasks in the process.
20546 (let ((delta (- ind min-i)))
20547 (while (< (point) end)
20548 (unless (or (looking-at "^[ \t]*$")
20549 (looking-at org-outline-regexp-bol))
20550 (org-indent-line-to (+ (org-get-indentation) delta)))
20551 (forward-line)))))))
20552 (skip-blanks
20553 (function
20554 ;; Return beginning of first non-blank line, starting from
20555 ;; line at POS.
20556 (lambda (pos)
20557 (save-excursion
20558 (goto-char pos)
20559 (skip-chars-forward " \r\t\n")
20560 (point-at-bol)))))
20561 beg end)
20562 ;; Determine boundaries of changes.
20563 (if (org-region-active-p)
20564 (setq beg (funcall skip-blanks (region-beginning))
20565 end (copy-marker (region-end)))
20566 (setq beg (funcall skip-blanks (point-at-bol))
20567 end (copy-marker (point-at-eol))))
20568 ;; Depending on the starting line, choose an action on the text
20569 ;; between BEG and END.
20570 (org-with-limited-levels
20571 (save-excursion
20572 (goto-char beg)
20573 (cond
20574 ;; Case 1. Start at an item: de-itemize. Note that it only
20575 ;; happens when a region is active: `org-ctrl-c-minus'
20576 ;; would call `org-cycle-list-bullet' otherwise.
20577 ((org-at-item-p)
20578 (while (< (point) end)
20579 (when (org-at-item-p)
20580 (skip-chars-forward " \t")
20581 (delete-region (point) (match-end 0)))
20582 (forward-line)))
20583 ;; Case 2. Start at an heading: convert to items.
20584 ((org-at-heading-p)
20585 (let* ((bul (org-list-bullet-string "-"))
20586 (bul-len (length bul))
20587 ;; Indentation of the first heading. It should be
20588 ;; relative to the indentation of its parent, if any.
20589 (start-ind (save-excursion
20590 (cond
20591 ((not org-adapt-indentation) 0)
20592 ((not (outline-previous-heading)) 0)
20593 (t (length (match-string 0))))))
20594 ;; Level of first heading. Further headings will be
20595 ;; compared to it to determine hierarchy in the list.
20596 (ref-level (org-reduced-level (org-outline-level))))
20597 (while (< (point) end)
20598 (let* ((level (org-reduced-level (org-outline-level)))
20599 (delta (max 0 (- level ref-level))))
20600 ;; If current headline is less indented than the first
20601 ;; one, set it as reference, in order to preserve
20602 ;; subtrees.
20603 (when (< level ref-level) (setq ref-level level))
20604 (replace-match bul t t)
20605 (org-indent-line-to (+ start-ind (* delta bul-len)))
20606 ;; Ensure all text down to END (or SECTION-END) belongs
20607 ;; to the newly created item.
20608 (let ((section-end (save-excursion
20609 (or (outline-next-heading) (point)))))
20610 (forward-line)
20611 (funcall shift-text
20612 (+ start-ind (* (1+ delta) bul-len))
20613 (min end section-end)))))))
20614 ;; Case 3. Normal line with ARG: make the first line of region
20615 ;; an item, and shift indentation of others lines to
20616 ;; set them as item's body.
20617 (arg (let* ((bul (org-list-bullet-string "-"))
20618 (bul-len (length bul))
20619 (ref-ind (org-get-indentation)))
20620 (skip-chars-forward " \t")
20621 (insert bul)
20622 (forward-line)
20623 (while (< (point) end)
20624 ;; Ensure that lines less indented than first one
20625 ;; still get included in item body.
20626 (funcall shift-text
20627 (+ ref-ind bul-len)
20628 (min end (save-excursion (or (outline-next-heading)
20629 (point)))))
20630 (forward-line))))
20631 ;; Case 4. Normal line without ARG: turn each non-item line
20632 ;; into an item.
20634 (while (< (point) end)
20635 (unless (or (org-at-heading-p) (org-at-item-p))
20636 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20637 (replace-match
20638 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20639 (forward-line))))))))
20641 (defun org-toggle-heading (&optional nstars)
20642 "Convert headings to normal text, or items or text to headings.
20643 If there is no active region, only convert the current line.
20645 With a \\[universal-argument] prefix, convert the whole list at
20646 point into heading.
20648 In a region:
20650 - If the first non blank line is a headline, remove the stars
20651 from all headlines in the region.
20653 - If it is a normal line, turn each and every normal line (i.e.,
20654 not an heading or an item) in the region into headings. If you
20655 want to convert only the first line of this region, use one
20656 universal prefix argument.
20658 - If it is a plain list item, turn all plain list items into headings.
20660 When converting a line into a heading, the number of stars is chosen
20661 such that the lines become children of the current entry. However,
20662 when a numeric prefix argument is given, its value determines the
20663 number of stars to add."
20664 (interactive "P")
20665 (let ((skip-blanks
20666 (function
20667 ;; Return beginning of first non-blank line, starting from
20668 ;; line at POS.
20669 (lambda (pos)
20670 (save-excursion
20671 (goto-char pos)
20672 (while (org-at-comment-p) (forward-line))
20673 (skip-chars-forward " \r\t\n")
20674 (point-at-bol)))))
20675 beg end toggled)
20676 ;; Determine boundaries of changes. If a universal prefix has
20677 ;; been given, put the list in a region. If region ends at a bol,
20678 ;; do not consider the last line to be in the region.
20680 (when (and current-prefix-arg (org-at-item-p))
20681 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20682 (org-mark-element))
20684 (if (org-region-active-p)
20685 (setq beg (funcall skip-blanks (region-beginning))
20686 end (copy-marker (save-excursion
20687 (goto-char (region-end))
20688 (if (bolp) (point) (point-at-eol)))))
20689 (setq beg (funcall skip-blanks (point-at-bol))
20690 end (copy-marker (point-at-eol))))
20691 ;; Ensure inline tasks don't count as headings.
20692 (org-with-limited-levels
20693 (save-excursion
20694 (goto-char beg)
20695 (cond
20696 ;; Case 1. Started at an heading: de-star headings.
20697 ((org-at-heading-p)
20698 (while (< (point) end)
20699 (when (org-at-heading-p t)
20700 (looking-at org-outline-regexp) (replace-match "")
20701 (setq toggled t))
20702 (forward-line)))
20703 ;; Case 2. Started at an item: change items into headlines.
20704 ;; One star will be added by `org-list-to-subtree'.
20705 ((org-at-item-p)
20706 (let* ((stars (make-string
20707 ;; subtract the star that will be added again by
20708 ;; `org-list-to-subtree'
20709 (if (numberp nstars) (1- nstars)
20710 (or (org-current-level) 0))
20711 ?*))
20712 (add-stars
20713 (cond (nstars "") ; stars from prefix only
20714 ((equal stars "") "") ; before first heading
20715 (org-odd-levels-only "*") ; inside heading, odd
20716 (t "")))) ; inside heading, oddeven
20717 (while (< (point) end)
20718 (when (org-at-item-p)
20719 ;; Pay attention to cases when region ends before list.
20720 (let* ((struct (org-list-struct))
20721 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20722 (save-restriction
20723 (narrow-to-region (point) list-end)
20724 (insert
20725 (org-list-to-subtree
20726 (org-list-parse-list t)
20727 '(:istart (concat stars add-stars (funcall get-stars depth))
20728 :icount (concat stars add-stars (funcall get-stars depth)))))))
20729 (setq toggled t))
20730 (forward-line))))
20731 ;; Case 3. Started at normal text: make every line an heading,
20732 ;; skipping headlines and items.
20733 (t (let* ((stars
20734 (make-string
20735 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20736 (add-stars
20737 (cond (nstars "") ; stars from prefix only
20738 ((equal stars "") "*") ; before first heading
20739 (org-odd-levels-only "**") ; inside heading, odd
20740 (t "*"))) ; inside heading, oddeven
20741 (rpl (concat stars add-stars " "))
20742 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20743 (while (< (point) (if (equal nstars '(4)) lend end))
20744 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20745 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20746 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20747 (forward-line)))))))
20748 (unless toggled (message "Cannot toggle heading from here"))))
20750 (defun org-meta-return (&optional arg)
20751 "Insert a new heading or wrap a region in a table.
20752 Calls `org-insert-heading' or `org-table-wrap-region', depending
20753 on context. See the individual commands for more information."
20754 (interactive "P")
20755 (org-check-before-invisible-edit 'insert)
20756 (or (run-hook-with-args-until-success 'org-metareturn-hook)
20757 (let* ((element (org-element-at-point))
20758 (type (org-element-type element)))
20759 (when (eq type 'table-row)
20760 (setq element (org-element-property :parent element))
20761 (setq type 'table))
20762 (if (and (eq type 'table)
20763 (eq (org-element-property :type element) 'org)
20764 (>= (point) (org-element-property :contents-begin element))
20765 (< (point) (org-element-property :contents-end element)))
20766 (call-interactively 'org-table-wrap-region)
20767 (call-interactively 'org-insert-heading)))))
20769 ;;; Menu entries
20771 (defsubst org-in-subtree-not-table-p ()
20772 "Are we in a subtree and not in a table?"
20773 (and (not (org-before-first-heading-p))
20774 (not (org-at-table-p))))
20776 ;; Define the Org-mode menus
20777 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20778 '("Tbl"
20779 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20780 ["Next Field" org-cycle (org-at-table-p)]
20781 ["Previous Field" org-shifttab (org-at-table-p)]
20782 ["Next Row" org-return (org-at-table-p)]
20783 "--"
20784 ["Blank Field" org-table-blank-field (org-at-table-p)]
20785 ["Edit Field" org-table-edit-field (org-at-table-p)]
20786 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20787 "--"
20788 ("Column"
20789 ["Move Column Left" org-metaleft (org-at-table-p)]
20790 ["Move Column Right" org-metaright (org-at-table-p)]
20791 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20792 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20793 ("Row"
20794 ["Move Row Up" org-metaup (org-at-table-p)]
20795 ["Move Row Down" org-metadown (org-at-table-p)]
20796 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20797 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20798 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20799 "--"
20800 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20801 ("Rectangle"
20802 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20803 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20804 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20805 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20806 "--"
20807 ("Calculate"
20808 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20809 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20810 ["Edit Formulas" org-edit-special (org-at-table-p)]
20811 "--"
20812 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20813 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20814 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20815 "--"
20816 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20817 "--"
20818 ["Sum Column/Rectangle" org-table-sum
20819 (or (org-at-table-p) (org-region-active-p))]
20820 ["Which Column?" org-table-current-column (org-at-table-p)])
20821 ["Debug Formulas"
20822 org-table-toggle-formula-debugger
20823 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20824 ["Show Col/Row Numbers"
20825 org-table-toggle-coordinate-overlays
20826 :style toggle
20827 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20828 "--"
20829 ["Create" org-table-create (and (not (org-at-table-p))
20830 org-enable-table-editor)]
20831 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20832 ["Import from File" org-table-import (not (org-at-table-p))]
20833 ["Export to File" org-table-export (org-at-table-p)]
20834 "--"
20835 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20837 (easy-menu-define org-org-menu org-mode-map "Org menu"
20838 '("Org"
20839 ("Show/Hide"
20840 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20841 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20842 ["Sparse Tree..." org-sparse-tree t]
20843 ["Reveal Context" org-reveal t]
20844 ["Show All" show-all t]
20845 "--"
20846 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20847 "--"
20848 ["New Heading" org-insert-heading t]
20849 ("Navigate Headings"
20850 ["Up" outline-up-heading t]
20851 ["Next" outline-next-visible-heading t]
20852 ["Previous" outline-previous-visible-heading t]
20853 ["Next Same Level" outline-forward-same-level t]
20854 ["Previous Same Level" outline-backward-same-level t]
20855 "--"
20856 ["Jump" org-goto t])
20857 ("Edit Structure"
20858 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20859 "--"
20860 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20861 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20862 "--"
20863 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20864 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20865 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20866 "--"
20867 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20868 "--"
20869 ["Copy visible text" org-copy-visible t]
20870 "--"
20871 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20872 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20873 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20874 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20875 "--"
20876 ["Sort Region/Children" org-sort t]
20877 "--"
20878 ["Convert to odd levels" org-convert-to-odd-levels t]
20879 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20880 ("Editing"
20881 ["Emphasis..." org-emphasize t]
20882 ["Edit Source Example" org-edit-special t]
20883 "--"
20884 ["Footnote new/jump" org-footnote-action t]
20885 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20886 ("Archive"
20887 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20888 "--"
20889 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20890 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20891 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20893 "--"
20894 ("Hyperlinks"
20895 ["Store Link (Global)" org-store-link t]
20896 ["Find existing link to here" org-occur-link-in-agenda-files t]
20897 ["Insert Link" org-insert-link t]
20898 ["Follow Link" org-open-at-point t]
20899 "--"
20900 ["Next link" org-next-link t]
20901 ["Previous link" org-previous-link t]
20902 "--"
20903 ["Descriptive Links"
20904 org-toggle-link-display
20905 :style radio
20906 :selected org-descriptive-links
20908 ["Literal Links"
20909 org-toggle-link-display
20910 :style radio
20911 :selected (not org-descriptive-links)])
20912 "--"
20913 ("TODO Lists"
20914 ["TODO/DONE/-" org-todo t]
20915 ("Select keyword"
20916 ["Next keyword" org-shiftright (org-at-heading-p)]
20917 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20918 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20919 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20920 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20921 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20922 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20923 "--"
20924 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20925 :selected org-enforce-todo-dependencies :style toggle :active t]
20926 "Settings for tree at point"
20927 ["Do Children sequentially" org-toggle-ordered-property :style radio
20928 :selected (org-entry-get nil "ORDERED")
20929 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20930 ["Do Children parallel" org-toggle-ordered-property :style radio
20931 :selected (not (org-entry-get nil "ORDERED"))
20932 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20933 "--"
20934 ["Set Priority" org-priority t]
20935 ["Priority Up" org-shiftup t]
20936 ["Priority Down" org-shiftdown t]
20937 "--"
20938 ["Get news from all feeds" org-feed-update-all t]
20939 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20940 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20941 ("TAGS and Properties"
20942 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20943 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20944 "--"
20945 ["Set property" org-set-property (not (org-before-first-heading-p))]
20946 ["Column view of properties" org-columns t]
20947 ["Insert Column View DBlock" org-insert-columns-dblock t])
20948 ("Dates and Scheduling"
20949 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20950 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20951 ("Change Date"
20952 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20953 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20954 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20955 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20956 ["Compute Time Range" org-evaluate-time-range t]
20957 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20958 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20959 "--"
20960 ["Custom time format" org-toggle-time-stamp-overlays
20961 :style radio :selected org-display-custom-times]
20962 "--"
20963 ["Goto Calendar" org-goto-calendar t]
20964 ["Date from Calendar" org-date-from-calendar t]
20965 "--"
20966 ["Start/Restart Timer" org-timer-start t]
20967 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20968 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20969 ["Insert Timer String" org-timer t]
20970 ["Insert Timer Item" org-timer-item t])
20971 ("Logging work"
20972 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20973 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20974 ["Clock out" org-clock-out t]
20975 ["Clock cancel" org-clock-cancel t]
20976 "--"
20977 ["Mark as default task" org-clock-mark-default-task t]
20978 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20979 ["Goto running clock" org-clock-goto t]
20980 "--"
20981 ["Display times" org-clock-display t]
20982 ["Create clock table" org-clock-report t]
20983 "--"
20984 ["Record DONE time"
20985 (progn (setq org-log-done (not org-log-done))
20986 (message "Switching to %s will %s record a timestamp"
20987 (car org-done-keywords)
20988 (if org-log-done "automatically" "not")))
20989 :style toggle :selected org-log-done])
20990 "--"
20991 ["Agenda Command..." org-agenda t]
20992 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20993 ("File List for Agenda")
20994 ("Special views current file"
20995 ["TODO Tree" org-show-todo-tree t]
20996 ["Check Deadlines" org-check-deadlines t]
20997 ["Timeline" org-timeline t]
20998 ["Tags/Property tree" org-match-sparse-tree t])
20999 "--"
21000 ["Export/Publish..." org-export-dispatch t]
21001 ("LaTeX"
21002 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21003 :selected org-cdlatex-mode]
21004 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21005 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21006 ["Modify math symbol" org-cdlatex-math-modify
21007 (org-inside-LaTeX-fragment-p)]
21008 ["Insert citation" org-reftex-citation t]
21009 "--"
21010 ["Template for BEAMER" (org-beamer-insert-options-template) t])
21011 "--"
21012 ("MobileOrg"
21013 ["Push Files and Views" org-mobile-push t]
21014 ["Get Captured and Flagged" org-mobile-pull t]
21015 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21016 "--"
21017 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21018 "--"
21019 ("Documentation"
21020 ["Show Version" org-version t]
21021 ["Info Documentation" org-info t])
21022 ("Customize"
21023 ["Browse Org Group" org-customize t]
21024 "--"
21025 ["Expand This Menu" org-create-customize-menu
21026 (fboundp 'customize-menu-create)])
21027 ["Send bug report" org-submit-bug-report t]
21028 "--"
21029 ("Refresh/Reload"
21030 ["Refresh setup current buffer" org-mode-restart t]
21031 ["Reload Org (after update)" org-reload t]
21032 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21035 (defun org-info (&optional node)
21036 "Read documentation for Org-mode in the info system.
21037 With optional NODE, go directly to that node."
21038 (interactive)
21039 (info (format "(org)%s" (or node ""))))
21041 ;;;###autoload
21042 (defun org-submit-bug-report ()
21043 "Submit a bug report on Org-mode via mail.
21045 Don't hesitate to report any problems or inaccurate documentation.
21047 If you don't have setup sending mail from (X)Emacs, please copy the
21048 output buffer into your mail program, as it gives us important
21049 information about your Org-mode version and configuration."
21050 (interactive)
21051 (require 'reporter)
21052 (org-load-modules-maybe)
21053 (org-require-autoloaded-modules)
21054 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21055 (reporter-submit-bug-report
21056 "emacs-orgmode@gnu.org"
21057 (org-version nil 'full)
21058 (let (list)
21059 (save-window-excursion
21060 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21061 (delete-other-windows)
21062 (erase-buffer)
21063 (insert "You are about to submit a bug report to the Org-mode mailing list.
21065 We would like to add your full Org-mode and Outline configuration to the
21066 bug report. This greatly simplifies the work of the maintainer and
21067 other experts on the mailing list.
21069 HOWEVER, some variables you have customized may contain private
21070 information. The names of customers, colleagues, or friends, might
21071 appear in the form of file names, tags, todo states, or search strings.
21072 If you answer yes to the prompt, you might want to check and remove
21073 such private information before sending the email.")
21074 (add-text-properties (point-min) (point-max) '(face org-warning))
21075 (when (yes-or-no-p "Include your Org-mode configuration ")
21076 (mapatoms
21077 (lambda (v)
21078 (and (boundp v)
21079 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21080 (or (and (symbol-value v)
21081 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21082 (and
21083 (get v 'custom-type) (get v 'standard-value)
21084 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21085 (push v list)))))
21086 (kill-buffer (get-buffer "*Warn about privacy*"))
21087 list))
21088 nil nil
21089 "Remember to cover the basics, that is, what you expected to happen and
21090 what in fact did happen. You don't know how to make a good report? See
21092 http://orgmode.org/manual/Feedback.html#Feedback
21094 Your bug report will be posted to the Org-mode mailing list.
21095 ------------------------------------------------------------------------")
21096 (save-excursion
21097 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21098 (replace-match "\\1Bug: \\3 [\\2]")))))
21101 (defun org-install-agenda-files-menu ()
21102 (let ((bl (buffer-list)))
21103 (save-excursion
21104 (while bl
21105 (set-buffer (pop bl))
21106 (if (derived-mode-p 'org-mode) (setq bl nil)))
21107 (when (derived-mode-p 'org-mode)
21108 (easy-menu-change
21109 '("Org") "File List for Agenda"
21110 (append
21111 (list
21112 ["Edit File List" (org-edit-agenda-file-list) t]
21113 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21114 ["Remove Current File from List" org-remove-file t]
21115 ["Cycle through agenda files" org-cycle-agenda-files t]
21116 ["Occur in all agenda files" org-occur-in-agenda-files t]
21117 "--")
21118 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21120 ;;;; Documentation
21122 (defun org-require-autoloaded-modules ()
21123 (interactive)
21124 (mapc 'require
21125 '(org-agenda org-archive org-attach org-clock org-colview org-id
21126 org-table org-timer)))
21128 ;;;###autoload
21129 (defun org-reload (&optional uncompiled)
21130 "Reload all org lisp files.
21131 With prefix arg UNCOMPILED, load the uncompiled versions."
21132 (interactive "P")
21133 (require 'loadhist)
21134 (let* ((org-dir (org-find-library-dir "org"))
21135 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21136 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21137 (remove-re (mapconcat 'identity
21138 (mapcar (lambda (f) (concat "^" f "$"))
21139 (list (if (featurep 'xemacs)
21140 "org-colview"
21141 "org-colview-xemacs")
21142 "org" "org-loaddefs" "org-version"))
21143 "\\|"))
21144 (feats (delete-dups
21145 (mapcar 'file-name-sans-extension
21146 (mapcar 'file-name-nondirectory
21147 (delq nil
21148 (mapcar 'feature-file
21149 features))))))
21150 (lfeat (append
21151 (sort
21152 (setq feats
21153 (delq nil (mapcar
21154 (lambda (f)
21155 (if (and (string-match feature-re f)
21156 (not (string-match remove-re f)))
21157 f nil))
21158 feats)))
21159 'string-lessp)
21160 (list "org-version" "org")))
21161 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21162 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21163 load-uncore load-misses)
21164 (setq load-misses
21165 (delq 't
21166 (mapcar (lambda (f)
21167 (or (org-load-noerror-mustsuffix (concat org-dir f))
21168 (and (string= org-dir contrib-dir)
21169 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21170 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21171 (add-to-list 'load-uncore f 'append)
21174 lfeat)))
21175 (if load-uncore
21176 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21177 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21178 (if load-misses
21179 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21180 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21181 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21183 ;;;###autoload
21184 (defun org-customize ()
21185 "Call the customize function with org as argument."
21186 (interactive)
21187 (org-load-modules-maybe)
21188 (org-require-autoloaded-modules)
21189 (customize-browse 'org))
21191 (defun org-create-customize-menu ()
21192 "Create a full customization menu for Org-mode, insert it into the menu."
21193 (interactive)
21194 (org-load-modules-maybe)
21195 (org-require-autoloaded-modules)
21196 (if (fboundp 'customize-menu-create)
21197 (progn
21198 (easy-menu-change
21199 '("Org") "Customize"
21200 `(["Browse Org group" org-customize t]
21201 "--"
21202 ,(customize-menu-create 'org)
21203 ["Set" Custom-set t]
21204 ["Save" Custom-save t]
21205 ["Reset to Current" Custom-reset-current t]
21206 ["Reset to Saved" Custom-reset-saved t]
21207 ["Reset to Standard Settings" Custom-reset-standard t]))
21208 (message "\"Org\"-menu now contains full customization menu"))
21209 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21211 ;;;; Miscellaneous stuff
21213 ;;; Generally useful functions
21215 (defun org-get-at-bol (property)
21216 "Get text property PROPERTY at beginning of line."
21217 (get-text-property (point-at-bol) property))
21219 (defun org-find-text-property-in-string (prop s)
21220 "Return the first non-nil value of property PROP in string S."
21221 (or (get-text-property 0 prop s)
21222 (get-text-property (or (next-single-property-change 0 prop s) 0)
21223 prop s)))
21225 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21226 "Display the given MESSAGE as a warning."
21227 (if (fboundp 'display-warning)
21228 (display-warning 'org message
21229 (if (featurep 'xemacs) 'warning :warning))
21230 (let ((buf (get-buffer-create "*Org warnings*")))
21231 (with-current-buffer buf
21232 (goto-char (point-max))
21233 (insert "Warning (Org): " message)
21234 (unless (bolp)
21235 (newline)))
21236 (display-buffer buf)
21237 (sit-for 0))))
21239 (defun org-eval (form)
21240 "Eval FORM and return result."
21241 (condition-case error
21242 (eval form)
21243 (error (format "%%![Error: %s]" error))))
21245 (defun org-in-clocktable-p ()
21246 "Check if the cursor is in a clocktable."
21247 (let ((pos (point)) start)
21248 (save-excursion
21249 (end-of-line 1)
21250 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21251 (setq start (match-beginning 0))
21252 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21253 (>= (match-end 0) pos)
21254 start))))
21256 (defun org-in-commented-line ()
21257 "Is point in a line starting with `#'?"
21258 (equal (char-after (point-at-bol)) ?#))
21260 (defun org-in-indented-comment-line ()
21261 "Is point in a line starting with `#' after some white space?"
21262 (save-excursion
21263 (save-match-data
21264 (goto-char (point-at-bol))
21265 (looking-at "[ \t]*#"))))
21267 (defun org-in-verbatim-emphasis ()
21268 (save-match-data
21269 (and (org-in-regexp org-emph-re 2)
21270 (>= (point) (match-beginning 3))
21271 (<= (point) (match-end 4))
21272 (member (match-string 3) '("=" "~")))))
21274 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21275 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21276 (if (and marker (marker-buffer marker)
21277 (buffer-live-p (marker-buffer marker)))
21278 (progn
21279 (org-pop-to-buffer-same-window (marker-buffer marker))
21280 (if (or (> marker (point-max)) (< marker (point-min)))
21281 (widen))
21282 (goto-char marker)
21283 (org-show-context 'org-goto))
21284 (if bookmark
21285 (bookmark-jump bookmark)
21286 (error "Cannot find location"))))
21288 (defun org-quote-csv-field (s)
21289 "Quote field for inclusion in CSV material."
21290 (if (string-match "[\",]" s)
21291 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21294 (defun org-force-self-insert (N)
21295 "Needed to enforce self-insert under remapping."
21296 (interactive "p")
21297 (self-insert-command N))
21299 (defun org-string-width (s)
21300 "Compute width of string, ignoring invisible characters.
21301 This ignores character with invisibility property `org-link', and also
21302 characters with property `org-cwidth', because these will become invisible
21303 upon the next fontification round."
21304 (let (b l)
21305 (when (or (eq t buffer-invisibility-spec)
21306 (assq 'org-link buffer-invisibility-spec))
21307 (while (setq b (text-property-any 0 (length s)
21308 'invisible 'org-link s))
21309 (setq s (concat (substring s 0 b)
21310 (substring s (or (next-single-property-change
21311 b 'invisible s) (length s)))))))
21312 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21313 (setq s (concat (substring s 0 b)
21314 (substring s (or (next-single-property-change
21315 b 'org-cwidth s) (length s))))))
21316 (setq l (string-width s) b -1)
21317 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21318 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21321 (defun org-shorten-string (s maxlength)
21322 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21323 If the string is shorter or has length MAXLENGTH, just return the
21324 original string. If it is longer, the functions finds a space in the
21325 string, breaks this string off at that locations and adds three dots
21326 as ellipsis. Including the ellipsis, the string will not be longer
21327 than MAXLENGTH. If finding a good breaking point in the string does
21328 not work, the string is just chopped off in the middle of a word
21329 if necessary."
21330 (if (<= (length s) maxlength)
21332 (let* ((n (max (- maxlength 4) 1))
21333 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21334 (if (string-match re s)
21335 (concat (match-string 1 s) "...")
21336 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21338 (defun org-get-indentation (&optional line)
21339 "Get the indentation of the current line, interpreting tabs.
21340 When LINE is given, assume it represents a line and compute its indentation."
21341 (if line
21342 (if (string-match "^ *" (org-remove-tabs line))
21343 (match-end 0))
21344 (save-excursion
21345 (beginning-of-line 1)
21346 (skip-chars-forward " \t")
21347 (current-column))))
21349 (defun org-get-string-indentation (s)
21350 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21351 (let ((n -1) (i 0) (w tab-width) c)
21352 (catch 'exit
21353 (while (< (setq n (1+ n)) (length s))
21354 (setq c (aref s n))
21355 (cond ((= c ?\ ) (setq i (1+ i)))
21356 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21357 (t (throw 'exit t)))))
21360 (defun org-remove-tabs (s &optional width)
21361 "Replace tabulators in S with spaces.
21362 Assumes that s is a single line, starting in column 0."
21363 (setq width (or width tab-width))
21364 (while (string-match "\t" s)
21365 (setq s (replace-match
21366 (make-string
21367 (- (* width (/ (+ (match-beginning 0) width) width))
21368 (match-beginning 0)) ?\ )
21369 t t s)))
21372 (defun org-fix-indentation (line ind)
21373 "Fix indentation in LINE.
21374 IND is a cons cell with target and minimum indentation.
21375 If the current indentation in LINE is smaller than the minimum,
21376 leave it alone. If it is larger than ind, set it to the target."
21377 (let* ((l (org-remove-tabs line))
21378 (i (org-get-indentation l))
21379 (i1 (car ind)) (i2 (cdr ind)))
21380 (if (>= i i2) (setq l (substring line i2)))
21381 (if (> i1 0)
21382 (concat (make-string i1 ?\ ) l)
21383 l)))
21385 (defun org-remove-indentation (code &optional n)
21386 "Remove the maximum common indentation from the lines in CODE.
21387 N may optionally be the number of spaces to remove."
21388 (with-temp-buffer
21389 (insert code)
21390 (org-do-remove-indentation n)
21391 (buffer-string)))
21393 (defun org-do-remove-indentation (&optional n)
21394 "Remove the maximum common indentation from the buffer."
21395 (untabify (point-min) (point-max))
21396 (let ((min 10000) re)
21397 (if n
21398 (setq min n)
21399 (goto-char (point-min))
21400 (while (re-search-forward "^ *[^ \n]" nil t)
21401 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21402 (unless (or (= min 0) (= min 10000))
21403 (setq re (format "^ \\{%d\\}" min))
21404 (goto-char (point-min))
21405 (while (re-search-forward re nil t)
21406 (replace-match "")
21407 (end-of-line 1))
21408 min)))
21410 (defun org-fill-template (template alist)
21411 "Find each %key of ALIST in TEMPLATE and replace it."
21412 (let ((case-fold-search nil)
21413 entry key value)
21414 (setq alist (sort (copy-sequence alist)
21415 (lambda (a b) (< (length (car a)) (length (car b))))))
21416 (while (setq entry (pop alist))
21417 (setq template
21418 (replace-regexp-in-string
21419 (concat "%" (regexp-quote (car entry)))
21420 (or (cdr entry) "") template t t)))
21421 template))
21423 (defun org-base-buffer (buffer)
21424 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21425 (if (not buffer)
21426 buffer
21427 (or (buffer-base-buffer buffer)
21428 buffer)))
21430 (defun org-trim (s)
21431 "Remove whitespace at beginning and end of string."
21432 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
21433 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
21436 (defun org-wrap (string &optional width lines)
21437 "Wrap string to either a number of lines, or a width in characters.
21438 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21439 that costs. If there is a word longer than WIDTH, the text is actually
21440 wrapped to the length of that word.
21441 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21442 many lines, whatever width that takes.
21443 The return value is a list of lines, without newlines at the end."
21444 (let* ((words (org-split-string string "[ \t\n]+"))
21445 (maxword (apply 'max (mapcar 'org-string-width words)))
21446 w ll)
21447 (cond (width
21448 (org-do-wrap words (max maxword width)))
21449 (lines
21450 (setq w maxword)
21451 (setq ll (org-do-wrap words maxword))
21452 (if (<= (length ll) lines)
21454 (setq ll words)
21455 (while (> (length ll) lines)
21456 (setq w (1+ w))
21457 (setq ll (org-do-wrap words w)))
21458 ll))
21459 (t (error "Cannot wrap this")))))
21461 (defun org-do-wrap (words width)
21462 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21463 (let (lines line)
21464 (while words
21465 (setq line (pop words))
21466 (while (and words (< (+ (length line) (length (car words))) width))
21467 (setq line (concat line " " (pop words))))
21468 (setq lines (push line lines)))
21469 (nreverse lines)))
21471 (defun org-split-string (string &optional separators)
21472 "Splits STRING into substrings at SEPARATORS.
21473 No empty strings are returned if there are matches at the beginning
21474 and end of string."
21475 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21476 (start 0)
21477 notfirst
21478 (list nil))
21479 (while (and (string-match rexp string
21480 (if (and notfirst
21481 (= start (match-beginning 0))
21482 (< start (length string)))
21483 (1+ start) start))
21484 (< (match-beginning 0) (length string)))
21485 (setq notfirst t)
21486 (or (eq (match-beginning 0) 0)
21487 (and (eq (match-beginning 0) (match-end 0))
21488 (eq (match-beginning 0) start))
21489 (setq list
21490 (cons (substring string start (match-beginning 0))
21491 list)))
21492 (setq start (match-end 0)))
21493 (or (eq start (length string))
21494 (setq list
21495 (cons (substring string start)
21496 list)))
21497 (nreverse list)))
21499 (defun org-quote-vert (s)
21500 "Replace \"|\" with \"\\vert\"."
21501 (while (string-match "|" s)
21502 (setq s (replace-match "\\vert" t t s)))
21505 (defun org-uuidgen-p (s)
21506 "Is S an ID created by UUIDGEN?"
21507 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21509 (defun org-in-src-block-p (&optional inside)
21510 "Whether point is in a code source block.
21511 When INSIDE is non-nil, don't consider we are within a src block
21512 when point is at #+BEGIN_SRC or #+END_SRC."
21513 (let ((case-fold-search t) ov)
21514 (or (and (setq ov (overlays-at (point)))
21515 (memq 'org-block-background
21516 (overlay-properties (car ov))))
21517 (and (not inside)
21518 (save-match-data
21519 (save-excursion
21520 (beginning-of-line)
21521 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21523 (defun org-context ()
21524 "Return a list of contexts of the current cursor position.
21525 If several contexts apply, all are returned.
21526 Each context entry is a list with a symbol naming the context, and
21527 two positions indicating start and end of the context. Possible
21528 contexts are:
21530 :headline anywhere in a headline
21531 :headline-stars on the leading stars in a headline
21532 :todo-keyword on a TODO keyword (including DONE) in a headline
21533 :tags on the TAGS in a headline
21534 :priority on the priority cookie in a headline
21535 :item on the first line of a plain list item
21536 :item-bullet on the bullet/number of a plain list item
21537 :checkbox on the checkbox in a plain list item
21538 :table in an org-mode table
21539 :table-special on a special filed in a table
21540 :table-table in a table.el table
21541 :clocktable in a clocktable
21542 :src-block in a source block
21543 :link on a hyperlink
21544 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21545 :target on a <<target>>
21546 :radio-target on a <<<radio-target>>>
21547 :latex-fragment on a LaTeX fragment
21548 :latex-preview on a LaTeX fragment with overlaid preview image
21550 This function expects the position to be visible because it uses font-lock
21551 faces as a help to recognize the following contexts: :table-special, :link,
21552 and :keyword."
21553 (let* ((f (get-text-property (point) 'face))
21554 (faces (if (listp f) f (list f)))
21555 (case-fold-search t)
21556 (p (point)) clist o)
21557 ;; First the large context
21558 (cond
21559 ((org-at-heading-p t)
21560 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21561 (when (progn
21562 (beginning-of-line 1)
21563 (looking-at org-todo-line-tags-regexp))
21564 (push (org-point-in-group p 1 :headline-stars) clist)
21565 (push (org-point-in-group p 2 :todo-keyword) clist)
21566 (push (org-point-in-group p 4 :tags) clist))
21567 (goto-char p)
21568 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21569 (if (looking-at "\\[#[A-Z0-9]\\]")
21570 (push (org-point-in-group p 0 :priority) clist)))
21572 ((org-at-item-p)
21573 (push (org-point-in-group p 2 :item-bullet) clist)
21574 (push (list :item (point-at-bol)
21575 (save-excursion (org-end-of-item) (point)))
21576 clist)
21577 (and (org-at-item-checkbox-p)
21578 (push (org-point-in-group p 0 :checkbox) clist)))
21580 ((org-at-table-p)
21581 (push (list :table (org-table-begin) (org-table-end)) clist)
21582 (if (memq 'org-formula faces)
21583 (push (list :table-special
21584 (previous-single-property-change p 'face)
21585 (next-single-property-change p 'face)) clist)))
21586 ((org-at-table-p 'any)
21587 (push (list :table-table) clist)))
21588 (goto-char p)
21590 (let ((case-fold-search t))
21591 ;; New the "medium" contexts: clocktables, source blocks
21592 (cond ((org-in-clocktable-p)
21593 (push (list :clocktable
21594 (and (or (looking-at "#\\+BEGIN: clocktable")
21595 (search-backward "#+BEGIN: clocktable" nil t))
21596 (match-beginning 0))
21597 (and (re-search-forward "#\\+END:?" nil t)
21598 (match-end 0))) clist))
21599 ((org-in-src-block-p)
21600 (push (list :src-block
21601 (and (or (looking-at "#\\+BEGIN_SRC")
21602 (search-backward "#+BEGIN_SRC" nil t))
21603 (match-beginning 0))
21604 (and (search-forward "#+END_SRC" nil t)
21605 (match-beginning 0))) clist))))
21606 (goto-char p)
21608 ;; Now the small context
21609 (cond
21610 ((org-at-timestamp-p)
21611 (push (org-point-in-group p 0 :timestamp) clist))
21612 ((memq 'org-link faces)
21613 (push (list :link
21614 (previous-single-property-change p 'face)
21615 (next-single-property-change p 'face)) clist))
21616 ((memq 'org-special-keyword faces)
21617 (push (list :keyword
21618 (previous-single-property-change p 'face)
21619 (next-single-property-change p 'face)) clist))
21620 ((org-at-target-p)
21621 (push (org-point-in-group p 0 :target) clist)
21622 (goto-char (1- (match-beginning 0)))
21623 (if (looking-at org-radio-target-regexp)
21624 (push (org-point-in-group p 0 :radio-target) clist))
21625 (goto-char p))
21626 ((setq o (car (delq nil
21627 (mapcar
21628 (lambda (x)
21629 (if (memq x org-latex-fragment-image-overlays) x))
21630 (overlays-at (point))))))
21631 (push (list :latex-fragment
21632 (overlay-start o) (overlay-end o)) clist)
21633 (push (list :latex-preview
21634 (overlay-start o) (overlay-end o)) clist))
21635 ((org-inside-LaTeX-fragment-p)
21636 ;; FIXME: positions wrong.
21637 (push (list :latex-fragment (point) (point)) clist)))
21639 (setq clist (nreverse (delq nil clist)))
21640 clist))
21642 ;; FIXME: Compare with at-regexp-p Do we need both?
21643 (defun org-in-regexp (re &optional nlines visually)
21644 "Check if point is inside a match of regexp.
21645 Normally only the current line is checked, but you can include NLINES extra
21646 lines both before and after point into the search.
21647 If VISUALLY is set, require that the cursor is not after the match but
21648 really on, so that the block visually is on the match."
21649 (catch 'exit
21650 (let ((pos (point))
21651 (eol (point-at-eol (+ 1 (or nlines 0))))
21652 (inc (if visually 1 0)))
21653 (save-excursion
21654 (beginning-of-line (- 1 (or nlines 0)))
21655 (while (re-search-forward re eol t)
21656 (if (and (<= (match-beginning 0) pos)
21657 (>= (+ inc (match-end 0)) pos))
21658 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21660 (defun org-at-regexp-p (regexp)
21661 "Is point inside a match of REGEXP in the current line?"
21662 (catch 'exit
21663 (save-excursion
21664 (let ((pos (point)) (end (point-at-eol)))
21665 (beginning-of-line 1)
21666 (while (re-search-forward regexp end t)
21667 (if (and (<= (match-beginning 0) pos)
21668 (>= (match-end 0) pos))
21669 (throw 'exit t)))
21670 nil))))
21672 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21673 "Non-nil when point is between matches of START-RE and END-RE.
21675 Also return a non-nil value when point is on one of the matches.
21677 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21678 buffer positions. Default values are the positions of headlines
21679 surrounding the point.
21681 The functions returns a cons cell whose car (resp. cdr) is the
21682 position before START-RE (resp. after END-RE)."
21683 (save-match-data
21684 (let ((pos (point))
21685 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21686 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21687 beg end)
21688 (save-excursion
21689 ;; Point is on a block when on START-RE or if START-RE can be
21690 ;; found before it...
21691 (and (or (org-at-regexp-p start-re)
21692 (re-search-backward start-re limit-up t))
21693 (setq beg (match-beginning 0))
21694 ;; ... and END-RE after it...
21695 (goto-char (match-end 0))
21696 (re-search-forward end-re limit-down t)
21697 (> (setq end (match-end 0)) pos)
21698 ;; ... without another START-RE in-between.
21699 (goto-char (match-beginning 0))
21700 (not (re-search-backward start-re (1+ beg) t))
21701 ;; Return value.
21702 (cons beg end))))))
21704 (defun org-in-block-p (names)
21705 "Non-nil when point belongs to a block whose name belongs to NAMES.
21707 NAMES is a list of strings containing names of blocks.
21709 Return first block name matched, or nil. Beware that in case of
21710 nested blocks, the returned name may not belong to the closest
21711 block from point."
21712 (save-match-data
21713 (catch 'exit
21714 (let ((case-fold-search t)
21715 (lim-up (save-excursion (outline-previous-heading)))
21716 (lim-down (save-excursion (outline-next-heading))))
21717 (mapc (lambda (name)
21718 (let ((n (regexp-quote name)))
21719 (when (org-between-regexps-p
21720 (concat "^[ \t]*#\\+begin_" n)
21721 (concat "^[ \t]*#\\+end_" n)
21722 lim-up lim-down)
21723 (throw 'exit n))))
21724 names))
21725 nil)))
21727 (defun org-in-drawer-p ()
21728 "Is point within a drawer?"
21729 (save-match-data
21730 (let ((case-fold-search t)
21731 (lim-up (save-excursion (outline-previous-heading)))
21732 (lim-down (save-excursion (outline-next-heading))))
21733 (org-between-regexps-p
21734 (concat "^[ \t]*:" (regexp-opt org-drawers) ":")
21735 "^[ \t]*:end:.*$"
21736 lim-up lim-down))))
21738 (defun org-occur-in-agenda-files (regexp &optional nlines)
21739 "Call `multi-occur' with buffers for all agenda files."
21740 (interactive "sOrg-files matching: \np")
21741 (let* ((files (org-agenda-files))
21742 (tnames (mapcar 'file-truename files))
21743 (extra org-agenda-text-search-extra-files)
21745 (when (eq (car extra) 'agenda-archives)
21746 (setq extra (cdr extra))
21747 (setq files (org-add-archive-files files)))
21748 (while (setq f (pop extra))
21749 (unless (member (file-truename f) tnames)
21750 (add-to-list 'files f 'append)
21751 (add-to-list 'tnames (file-truename f) 'append)))
21752 (multi-occur
21753 (mapcar (lambda (x)
21754 (with-current-buffer
21755 (or (get-file-buffer x) (find-file-noselect x))
21756 (widen)
21757 (current-buffer)))
21758 files)
21759 regexp)))
21761 (if (boundp 'occur-mode-find-occurrence-hook)
21762 ;; Emacs 23
21763 (add-hook 'occur-mode-find-occurrence-hook
21764 (lambda ()
21765 (when (derived-mode-p 'org-mode)
21766 (org-reveal))))
21767 ;; Emacs 22
21768 (defadvice occur-mode-goto-occurrence
21769 (after org-occur-reveal activate)
21770 (and (derived-mode-p 'org-mode) (org-reveal)))
21771 (defadvice occur-mode-goto-occurrence-other-window
21772 (after org-occur-reveal activate)
21773 (and (derived-mode-p 'org-mode) (org-reveal)))
21774 (defadvice occur-mode-display-occurrence
21775 (after org-occur-reveal activate)
21776 (when (derived-mode-p 'org-mode)
21777 (let ((pos (occur-mode-find-occurrence)))
21778 (with-current-buffer (marker-buffer pos)
21779 (save-excursion
21780 (goto-char pos)
21781 (org-reveal)))))))
21783 (defun org-occur-link-in-agenda-files ()
21784 "Create a link and search for it in the agendas.
21785 The link is not stored in `org-stored-links', it is just created
21786 for the search purpose."
21787 (interactive)
21788 (let ((link (condition-case nil
21789 (org-store-link nil)
21790 (error "Unable to create a link to here"))))
21791 (org-occur-in-agenda-files (regexp-quote link))))
21793 (defun org-reverse-string (string)
21794 "Return the reverse of STRING."
21795 (apply 'string (reverse (string-to-list string))))
21797 (defsubst org-uniquify (list)
21798 "Non-destructively remove duplicate elements from LIST."
21799 (let ((res (copy-sequence list))) (delete-dups res)))
21801 (defun org-uniquify-alist (alist)
21802 "Merge elements of ALIST with the same key.
21804 For example, in this alist:
21806 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
21807 => '((a 1 3) (b 2))
21809 merge (a 1) and (a 3) into (a 1 3).
21811 The function returns the new ALIST."
21812 (let (rtn)
21813 (mapc
21814 (lambda (e)
21815 (let (n)
21816 (if (not (assoc (car e) rtn))
21817 (push e rtn)
21818 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
21819 (setq rtn (assq-delete-all (car e) rtn))
21820 (push n rtn))))
21821 alist)
21822 rtn))
21824 (defun org-delete-all (elts list)
21825 "Remove all elements in ELTS from LIST."
21826 (while elts
21827 (setq list (delete (pop elts) list)))
21828 list)
21830 (defun org-count (cl-item cl-seq)
21831 "Count the number of occurrences of ITEM in SEQ.
21832 Taken from `count' in cl-seq.el with all keyword arguments removed."
21833 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21834 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21835 (while (< cl-start cl-end)
21836 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21837 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21838 (setq cl-start (1+ cl-start)))
21839 cl-count))
21841 (defun org-remove-if (predicate seq)
21842 "Remove everything from SEQ that fulfills PREDICATE."
21843 (let (res e)
21844 (while seq
21845 (setq e (pop seq))
21846 (if (not (funcall predicate e)) (push e res)))
21847 (nreverse res)))
21849 (defun org-remove-if-not (predicate seq)
21850 "Remove everything from SEQ that does not fulfill PREDICATE."
21851 (let (res e)
21852 (while seq
21853 (setq e (pop seq))
21854 (if (funcall predicate e) (push e res)))
21855 (nreverse res)))
21857 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21858 "Reduce two-argument FUNCTION across SEQ.
21859 Taken from `reduce' in cl-seq.el with all keyword arguments but
21860 \":initial-value\" removed."
21861 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21862 (cadr (memq :initial-value cl-keys)))
21863 (cl-seq (pop cl-seq))
21864 (t (funcall cl-func)))))
21865 (while cl-seq
21866 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21867 cl-accum))
21869 (defun org-every (pred seq)
21870 "Return true if PREDICATE is true of every element of SEQ.
21871 Adapted from `every' in cl.el."
21872 (catch 'org-every
21873 (mapc (lambda (e) (unless (funcall pred e) (throw 'org-every nil))) seq)
21876 (defun org-some (pred seq)
21877 "Return true if PREDICATE is true of any element of SEQ.
21878 Adapted from `some' in cl.el."
21879 (catch 'org-some
21880 (mapc (lambda (e) (when (funcall pred e) (throw 'org-some t))) seq)
21881 nil))
21883 (defun org-back-over-empty-lines ()
21884 "Move backwards over whitespace, to the beginning of the first empty line.
21885 Returns the number of empty lines passed."
21886 (let ((pos (point)))
21887 (if (cdr (assoc 'heading org-blank-before-new-entry))
21888 (skip-chars-backward " \t\n\r")
21889 (unless (eobp)
21890 (forward-line -1)))
21891 (beginning-of-line 2)
21892 (goto-char (min (point) pos))
21893 (count-lines (point) pos)))
21895 (defun org-skip-whitespace ()
21896 (skip-chars-forward " \t\n\r"))
21898 (defun org-point-in-group (point group &optional context)
21899 "Check if POINT is in match-group GROUP.
21900 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21901 match. If the match group does not exist or point is not inside it,
21902 return nil."
21903 (and (match-beginning group)
21904 (>= point (match-beginning group))
21905 (<= point (match-end group))
21906 (if context
21907 (list context (match-beginning group) (match-end group))
21908 t)))
21910 (defun org-switch-to-buffer-other-window (&rest args)
21911 "Switch to buffer in a second window on the current frame.
21912 In particular, do not allow pop-up frames.
21913 Returns the newly created buffer."
21914 (org-no-popups
21915 (apply 'switch-to-buffer-other-window args)))
21917 (defun org-combine-plists (&rest plists)
21918 "Create a single property list from all plists in PLISTS.
21919 The process starts by copying the first list, and then setting properties
21920 from the other lists. Settings in the last list are the most significant
21921 ones and overrule settings in the other lists."
21922 (let ((rtn (copy-sequence (pop plists)))
21923 p v ls)
21924 (while plists
21925 (setq ls (pop plists))
21926 (while ls
21927 (setq p (pop ls) v (pop ls))
21928 (setq rtn (plist-put rtn p v))))
21929 rtn))
21931 (defun org-replace-escapes (string table)
21932 "Replace %-escapes in STRING with values in TABLE.
21933 TABLE is an association list with keys like \"%a\" and string values.
21934 The sequences in STRING may contain normal field width and padding information,
21935 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21936 so values can contain further %-escapes if they are define later in TABLE."
21937 (let ((tbl (copy-alist table))
21938 (case-fold-search nil)
21939 (pchg 0)
21940 e re rpl)
21941 (while (setq e (pop tbl))
21942 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21943 (when (and (cdr e) (string-match re (cdr e)))
21944 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21945 (safe "SREF"))
21946 (add-text-properties 0 3 (list 'sref sref) safe)
21947 (setcdr e (replace-match safe t t (cdr e)))))
21948 (while (string-match re string)
21949 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21950 (cdr e)))
21951 (setq string (replace-match rpl t t string))))
21952 (while (setq pchg (next-property-change pchg string))
21953 (let ((sref (get-text-property pchg 'sref string)))
21954 (when (and sref (string-match "SREF" string pchg))
21955 (setq string (replace-match sref t t string)))))
21956 string))
21958 (defun org-sublist (list start end)
21959 "Return a section of LIST, from START to END.
21960 Counting starts at 1."
21961 (let (rtn (c start))
21962 (setq list (nthcdr (1- start) list))
21963 (while (and list (<= c end))
21964 (push (pop list) rtn)
21965 (setq c (1+ c)))
21966 (nreverse rtn)))
21968 (defun org-find-base-buffer-visiting (file)
21969 "Like `find-buffer-visiting' but always return the base buffer and
21970 not an indirect buffer."
21971 (let ((buf (or (get-file-buffer file)
21972 (find-buffer-visiting file))))
21973 (if buf
21974 (or (buffer-base-buffer buf) buf)
21975 nil)))
21977 (defun org-image-file-name-regexp (&optional extensions)
21978 "Return regexp matching the file names of images.
21979 If EXTENSIONS is given, only match these."
21980 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21981 (image-file-name-regexp)
21982 (let ((image-file-name-extensions
21983 (or extensions
21984 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21985 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21986 (concat "\\."
21987 (regexp-opt (nconc (mapcar 'upcase
21988 image-file-name-extensions)
21989 image-file-name-extensions)
21991 "\\'"))))
21993 (defun org-file-image-p (file &optional extensions)
21994 "Return non-nil if FILE is an image."
21995 (save-match-data
21996 (string-match (org-image-file-name-regexp extensions) file)))
21998 (defun org-get-cursor-date (&optional with-time)
21999 "Return the date at cursor in as a time.
22000 This works in the calendar and in the agenda, anywhere else it just
22001 returns the current time.
22002 If WITH-TIME is non-nil, returns the time of the event at point (in
22003 the agenda) or the current time of the day."
22004 (let (date day defd tp tm hod mod)
22005 (when with-time
22006 (setq tp (get-text-property (point) 'time))
22007 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22008 (setq hod (string-to-number (match-string 1 tp))
22009 mod (string-to-number (match-string 2 tp))))
22010 (or tp (setq hod (nth 2 (decode-time (current-time)))
22011 mod (nth 1 (decode-time (current-time))))))
22012 (cond
22013 ((eq major-mode 'calendar-mode)
22014 (setq date (calendar-cursor-to-date)
22015 defd (encode-time 0 (or mod 0) (or hod 0)
22016 (nth 1 date) (nth 0 date) (nth 2 date))))
22017 ((eq major-mode 'org-agenda-mode)
22018 (setq day (get-text-property (point) 'day))
22019 (if day
22020 (setq date (calendar-gregorian-from-absolute day)
22021 defd (encode-time 0 (or mod 0) (or hod 0)
22022 (nth 1 date) (nth 0 date) (nth 2 date))))))
22023 (or defd (current-time))))
22025 (defun org-mark-subtree (&optional up)
22026 "Mark the current subtree.
22027 This puts point at the start of the current subtree, and mark at
22028 the end. If a numeric prefix UP is given, move up into the
22029 hierarchy of headlines by UP levels before marking the subtree."
22030 (interactive "P")
22031 (org-with-limited-levels
22032 (cond ((org-at-heading-p) (beginning-of-line))
22033 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22034 (t (outline-previous-visible-heading 1))))
22035 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
22036 (if (org-called-interactively-p 'any)
22037 (call-interactively 'org-mark-element)
22038 (org-mark-element)))
22041 ;;; Indentation
22043 (defun org-indent-line ()
22044 "Indent line depending on context."
22045 (interactive)
22046 (let* ((pos (point))
22047 (itemp (org-at-item-p))
22048 (case-fold-search t)
22049 (org-drawer-regexp (or org-drawer-regexp "\000"))
22050 (inline-task-p (and (featurep 'org-inlinetask)
22051 (org-inlinetask-in-task-p)))
22052 (inline-re (and inline-task-p
22053 (org-inlinetask-outline-regexp)))
22054 column)
22055 (if (and orgstruct-is-++ (eq pos (point)))
22056 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
22057 (indent-according-to-mode))
22058 (beginning-of-line 1)
22059 (cond
22060 ;; Headings
22061 ((looking-at org-outline-regexp) (setq column 0))
22062 ;; Footnote definition
22063 ((looking-at org-footnote-definition-re) (setq column 0))
22064 ;; Literal examples
22065 ((looking-at "[ \t]*:\\( \\|$\\)")
22066 (setq column (org-get-indentation))) ; do nothing
22067 ;; Lists
22068 ((ignore-errors (goto-char (org-in-item-p)))
22069 (setq column (if itemp
22070 (org-get-indentation)
22071 (org-list-item-body-column (point))))
22072 (goto-char pos))
22073 ;; Drawers
22074 ((and (looking-at "[ \t]*:END:")
22075 (save-excursion (re-search-backward org-drawer-regexp nil t)))
22076 (save-excursion
22077 (goto-char (1- (match-beginning 1)))
22078 (setq column (current-column))))
22079 ;; Special blocks
22080 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
22081 (save-excursion
22082 (re-search-backward
22083 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
22084 (setq column (org-get-indentation (match-string 0))))
22085 ((and (not (looking-at "[ \t]*#\\+begin_"))
22086 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
22087 (save-excursion
22088 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
22089 (setq column
22090 (cond ((equal (downcase (match-string 1)) "src")
22091 ;; src blocks: let `org-edit-src-exit' handle them
22092 (org-get-indentation))
22093 ((equal (downcase (match-string 1)) "example")
22094 (max (org-get-indentation)
22095 (org-get-indentation (match-string 0))))
22097 (org-get-indentation (match-string 0))))))
22098 ;; This line has nothing special, look at the previous relevant
22099 ;; line to compute indentation
22101 (beginning-of-line 0)
22102 (while (and (not (bobp))
22103 (not (looking-at org-table-line-regexp))
22104 (not (looking-at org-drawer-regexp))
22105 ;; When point started in an inline task, do not move
22106 ;; above task starting line.
22107 (not (and inline-task-p (looking-at inline-re)))
22108 ;; Skip drawers, blocks, empty lines, verbatim,
22109 ;; comments, tables, footnotes definitions, lists,
22110 ;; inline tasks.
22111 (or (and (looking-at "[ \t]*:END:")
22112 (re-search-backward org-drawer-regexp nil t))
22113 (and (looking-at "[ \t]*#\\+end_")
22114 (re-search-backward "[ \t]*#\\+begin_"nil t))
22115 (looking-at "[ \t]*[\n:#|]")
22116 (looking-at org-footnote-definition-re)
22117 (and (not inline-task-p)
22118 (featurep 'org-inlinetask)
22119 (org-inlinetask-in-task-p)
22120 (or (org-inlinetask-goto-beginning) t))))
22121 (beginning-of-line 0))
22122 (cond
22123 ;; There was a list item above.
22124 ((ignore-errors (goto-char (org-in-item-p)))
22125 (goto-char (org-list-get-top-point (org-list-struct)))
22126 (setq column (org-get-indentation)))
22127 ;; There was an heading above.
22128 ((looking-at "\\*+[ \t]+")
22129 (if (not org-adapt-indentation)
22130 (setq column 0)
22131 (goto-char (match-end 0))
22132 (setq column (current-column))))
22133 ;; A drawer had started and is unfinished
22134 ((looking-at org-drawer-regexp)
22135 (goto-char (1- (match-beginning 1)))
22136 (setq column (current-column)))
22137 ;; Else, nothing noticeable found: get indentation and go on.
22138 (t (setq column (org-get-indentation))))))
22139 ;; Now apply indentation and move cursor accordingly
22140 (goto-char pos)
22141 (if (<= (current-column) (current-indentation))
22142 (org-indent-line-to column)
22143 (save-excursion (org-indent-line-to column)))
22144 ;; Special polishing for properties, see `org-property-format'
22145 (setq column (current-column))
22146 (beginning-of-line 1)
22147 (if (looking-at org-property-re)
22148 (replace-match (concat (match-string 4)
22149 (format org-property-format
22150 (match-string 1) (match-string 3)))
22151 t t))
22152 (org-move-to-column column))))
22154 (defun org-indent-drawer ()
22155 "Indent the drawer at point."
22156 (interactive)
22157 (let ((p (point))
22158 (e (and (save-excursion (re-search-forward ":END:" nil t))
22159 (match-end 0)))
22160 (folded
22161 (save-excursion
22162 (end-of-line)
22163 (when (overlays-at (point))
22164 (member 'invisible (overlay-properties
22165 (car (overlays-at (point)))))))))
22166 (when folded (org-cycle))
22167 (indent-for-tab-command)
22168 (while (and (move-beginning-of-line 2) (< (point) e))
22169 (indent-for-tab-command))
22170 (goto-char p)
22171 (when folded (org-cycle)))
22172 (message "Drawer at point indented"))
22174 (defun org-indent-block ()
22175 "Indent the block at point."
22176 (interactive)
22177 (let ((p (point))
22178 (case-fold-search t)
22179 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
22180 (match-end 0)))
22181 (folded
22182 (save-excursion
22183 (end-of-line)
22184 (when (overlays-at (point))
22185 (member 'invisible (overlay-properties
22186 (car (overlays-at (point)))))))))
22187 (when folded (org-cycle))
22188 (indent-for-tab-command)
22189 (while (and (move-beginning-of-line 2) (< (point) e))
22190 (indent-for-tab-command))
22191 (goto-char p)
22192 (when folded (org-cycle)))
22193 (message "Block at point indented"))
22195 (defun org-indent-region (start end)
22196 "Indent region."
22197 (interactive "r")
22198 (save-excursion
22199 (let ((line-end (org-current-line end)))
22200 (goto-char start)
22201 (while (< (org-current-line) line-end)
22202 (cond ((org-in-src-block-p t) (org-src-native-tab-command-maybe))
22203 (t (call-interactively 'org-indent-line)))
22204 (move-beginning-of-line 2)))))
22207 ;;; Filling
22209 ;; We use our own fill-paragraph and auto-fill functions.
22211 ;; `org-fill-paragraph' relies on adaptive filling and context
22212 ;; checking. Appropriate `fill-prefix' is computed with
22213 ;; `org-adaptive-fill-function'.
22215 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22216 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22217 ;; `org-adaptive-fill-function' value. Internally,
22218 ;; `org-comment-line-break-function' breaks the line.
22220 ;; `org-setup-filling' installs filling and auto-filling related
22221 ;; variables during `org-mode' initialization.
22223 (defvar org-element-paragraph-separate) ; org-element.el
22224 (defun org-setup-filling ()
22225 (require 'org-element)
22226 ;; Prevent auto-fill from inserting unwanted new items.
22227 (when (boundp 'fill-nobreak-predicate)
22228 (org-set-local
22229 'fill-nobreak-predicate
22230 (org-uniquify
22231 (append fill-nobreak-predicate
22232 '(org-fill-line-break-nobreak-p
22233 org-fill-paragraph-with-timestamp-nobreak-p)))))
22234 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22235 (org-set-local 'paragraph-start paragraph-ending)
22236 (org-set-local 'paragraph-separate paragraph-ending))
22237 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22238 (org-set-local 'auto-fill-inhibit-regexp nil)
22239 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22240 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22241 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22243 (defun org-fill-line-break-nobreak-p ()
22244 "Non-nil when a new line at point would create an Org line break."
22245 (save-excursion
22246 (skip-chars-backward "[ \t]")
22247 (skip-chars-backward "\\\\")
22248 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22250 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22251 "Non-nil when a new line at point would split a timestamp."
22252 (and (org-at-timestamp-p t)
22253 (not (looking-at org-ts-regexp-both))))
22255 (declare-function message-in-body-p "message" ())
22256 (defvar orgtbl-line-start-regexp) ; From org-table.el
22257 (defun org-adaptive-fill-function ()
22258 "Compute a fill prefix for the current line.
22259 Return fill prefix, as a string, or nil if current line isn't
22260 meant to be filled. For convenience, if `adaptive-fill-regexp'
22261 matches in paragraphs or comments, use it."
22262 (catch 'exit
22263 (when (derived-mode-p 'message-mode)
22264 (save-excursion
22265 (beginning-of-line)
22266 (cond ((or (not (message-in-body-p))
22267 (looking-at orgtbl-line-start-regexp))
22268 (throw 'exit nil))
22269 ((looking-at message-cite-prefix-regexp)
22270 (throw 'exit (match-string-no-properties 0)))
22271 ((looking-at org-outline-regexp)
22272 (throw 'exit (make-string (length (match-string 0)) ? ))))))
22273 (org-with-wide-buffer
22274 (let* ((p (line-beginning-position))
22275 (element (save-excursion
22276 (beginning-of-line)
22277 (or (ignore-errors (org-element-at-point))
22278 (user-error "An element cannot be parsed line %d"
22279 (line-number-at-pos (point))))))
22280 (type (org-element-type element))
22281 (post-affiliated (org-element-property :post-affiliated element)))
22282 (unless (and post-affiliated (< p post-affiliated))
22283 (case type
22284 (comment
22285 (save-excursion
22286 (beginning-of-line)
22287 (looking-at "[ \t]*")
22288 (concat (match-string 0) "# ")))
22289 (footnote-definition "")
22290 ((item plain-list)
22291 (make-string (org-list-item-body-column
22292 (or post-affiliated
22293 (org-element-property :begin element)))
22294 ? ))
22295 (paragraph
22296 ;; Fill prefix is usually the same as the current line,
22297 ;; unless the paragraph is at the beginning of an item.
22298 (let ((parent (org-element-property :parent element)))
22299 (save-excursion
22300 (beginning-of-line)
22301 (cond ((eq (org-element-type parent) 'item)
22302 (make-string (org-list-item-body-column
22303 (org-element-property :begin parent))
22304 ? ))
22305 ((and adaptive-fill-regexp
22306 ;; Locally disable
22307 ;; `adaptive-fill-function' to let
22308 ;; `fill-context-prefix' handle
22309 ;; `adaptive-fill-regexp' variable.
22310 (let (adaptive-fill-function)
22311 (fill-context-prefix
22312 post-affiliated
22313 (org-element-property :end element)))))
22314 ((looking-at "[ \t]+") (match-string 0))
22315 (t "")))))
22316 (comment-block
22317 ;; Only fill contents if P is within block boundaries.
22318 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22319 (forward-line)
22320 (point)))
22321 (cend (save-excursion
22322 (goto-char (org-element-property :end element))
22323 (skip-chars-backward " \r\t\n")
22324 (line-beginning-position))))
22325 (when (and (>= p cbeg) (< p cend))
22326 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22327 (match-string 0)
22328 ""))))))))))
22330 (declare-function message-goto-body "message" ())
22331 (defvar message-cite-prefix-regexp) ; From message.el
22332 (defun org-fill-paragraph (&optional justify)
22333 "Fill element at point, when applicable.
22335 This function only applies to comment blocks, comments, example
22336 blocks and paragraphs. Also, as a special case, re-align table
22337 when point is at one.
22339 If JUSTIFY is non-nil (interactively, with prefix argument),
22340 justify as well. If `sentence-end-double-space' is non-nil, then
22341 period followed by one space does not end a sentence, so don't
22342 break a line there. The variable `fill-column' controls the
22343 width for filling.
22345 For convenience, when point is at a plain list, an item or
22346 a footnote definition, try to fill the first paragraph within."
22347 (interactive)
22348 (if (and (derived-mode-p 'message-mode)
22349 (or (not (message-in-body-p))
22350 (save-excursion (move-beginning-of-line 1)
22351 (looking-at message-cite-prefix-regexp))))
22352 ;; First ensure filling is correct in message-mode.
22353 (let ((fill-paragraph-function
22354 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22355 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22356 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22357 (paragraph-separate
22358 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22359 (fill-paragraph nil))
22360 (with-syntax-table org-mode-transpose-word-syntax-table
22361 ;; Move to end of line in order to get the first paragraph
22362 ;; within a plain list or a footnote definition.
22363 (let ((element (save-excursion
22364 (end-of-line)
22365 (or (ignore-errors (org-element-at-point))
22366 (user-error "An element cannot be parsed line %d"
22367 (line-number-at-pos (point)))))))
22368 ;; First check if point is in a blank line at the beginning of
22369 ;; the buffer. In that case, ignore filling.
22370 (case (org-element-type element)
22371 ;; Use major mode filling function is src blocks.
22372 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22373 ;; Align Org tables, leave table.el tables as-is.
22374 (table-row (org-table-align) t)
22375 (table
22376 (when (eq (org-element-property :type element) 'org)
22377 (save-excursion
22378 (goto-char (org-element-property :post-affiliated element))
22379 (org-table-align)))
22381 (paragraph
22382 ;; Paragraphs may contain `line-break' type objects.
22383 (let ((beg (max (point-min)
22384 (org-element-property :contents-begin element)))
22385 (end (min (point-max)
22386 (org-element-property :contents-end element))))
22387 ;; Do nothing if point is at an affiliated keyword.
22388 (if (< (line-end-position) beg) t
22389 (when (derived-mode-p 'message-mode)
22390 ;; In `message-mode', do not fill following citation
22391 ;; in current paragraph nor text before message body.
22392 (let ((body-start (save-excursion (message-goto-body))))
22393 (when body-start (setq beg (max body-start beg))))
22394 (when (save-excursion
22395 (re-search-forward
22396 (concat "^" message-cite-prefix-regexp) end t))
22397 (setq end (match-beginning 0))))
22398 ;; Fill paragraph, taking line breaks into account.
22399 ;; For that, slice the paragraph using line breaks as
22400 ;; separators, and fill the parts in reverse order to
22401 ;; avoid messing with markers.
22402 (save-excursion
22403 (goto-char end)
22404 (mapc
22405 (lambda (pos)
22406 (fill-region-as-paragraph pos (point) justify)
22407 (goto-char pos))
22408 ;; Find the list of ending positions for line breaks
22409 ;; in the current paragraph. Add paragraph
22410 ;; beginning to include first slice.
22411 (nreverse
22412 (cons beg
22413 (org-element-map
22414 (org-element--parse-objects
22415 beg end nil (org-element-restriction 'paragraph))
22416 'line-break
22417 (lambda (lb) (org-element-property :end lb)))))))
22418 t)))
22419 ;; Contents of `comment-block' type elements should be
22420 ;; filled as plain text, but only if point is within block
22421 ;; markers.
22422 (comment-block
22423 (let* ((case-fold-search t)
22424 (beg (save-excursion
22425 (goto-char (org-element-property :begin element))
22426 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22427 (forward-line)
22428 (point)))
22429 (end (save-excursion
22430 (goto-char (org-element-property :end element))
22431 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22432 (line-beginning-position))))
22433 (if (or (< (point) beg) (> (point) end)) t
22434 (fill-region-as-paragraph
22435 (save-excursion (end-of-line)
22436 (re-search-backward "^[ \t]*$" beg 'move)
22437 (line-beginning-position))
22438 (save-excursion (beginning-of-line)
22439 (re-search-forward "^[ \t]*$" end 'move)
22440 (line-beginning-position))
22441 justify))))
22442 ;; Fill comments.
22443 (comment
22444 (let ((begin (org-element-property :post-affiliated element))
22445 (end (org-element-property :end element)))
22446 (when (and (>= (point) begin) (<= (point) end))
22447 (let ((begin (save-excursion
22448 (end-of-line)
22449 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22450 (progn (forward-line) (point))
22451 begin)))
22452 (end (save-excursion
22453 (end-of-line)
22454 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22455 (1- (line-beginning-position))
22456 (skip-chars-backward " \r\t\n")
22457 (line-end-position)))))
22458 ;; Do not fill comments when at a blank line.
22459 (when (> end begin)
22460 (let ((fill-prefix
22461 (save-excursion
22462 (beginning-of-line)
22463 (looking-at "[ \t]*#")
22464 (let ((comment-prefix (match-string 0)))
22465 (goto-char (match-end 0))
22466 (if (looking-at adaptive-fill-regexp)
22467 (concat comment-prefix (match-string 0))
22468 (concat comment-prefix " "))))))
22469 (save-excursion
22470 (fill-region-as-paragraph begin end justify))))))
22472 ;; Ignore every other element.
22473 (otherwise t))))))
22475 (defun org-auto-fill-function ()
22476 "Auto-fill function."
22477 ;; Check if auto-filling is meaningful.
22478 (let ((fc (current-fill-column)))
22479 (when (and fc (> (current-column) fc))
22480 (let* ((fill-prefix (org-adaptive-fill-function))
22481 ;; Enforce empty fill prefix, if required. Otherwise, it
22482 ;; will be computed again.
22483 (adaptive-fill-mode (not (equal fill-prefix ""))))
22484 (when fill-prefix (do-auto-fill))))))
22486 (defun org-comment-line-break-function (&optional soft)
22487 "Break line at point and indent, continuing comment if within one.
22488 The inserted newline is marked hard if variable
22489 `use-hard-newlines' is true, unless optional argument SOFT is
22490 non-nil."
22491 (if soft (insert-and-inherit ?\n) (newline 1))
22492 (save-excursion (forward-char -1) (delete-horizontal-space))
22493 (delete-horizontal-space)
22494 (indent-to-left-margin)
22495 (insert-before-markers-and-inherit fill-prefix))
22498 ;;; Comments
22500 ;; Org comments syntax is quite complex. It requires the entire line
22501 ;; to be just a comment. Also, even with the right syntax at the
22502 ;; beginning of line, some some elements (i.e. verse-block or
22503 ;; example-block) don't accept comments. Usual Emacs comment commands
22504 ;; cannot cope with those requirements. Therefore, Org replaces them.
22506 ;; Org still relies on `comment-dwim', but cannot trust
22507 ;; `comment-only-p'. So, `comment-region-function' and
22508 ;; `uncomment-region-function' both point
22509 ;; to`org-comment-or-uncomment-region'. Eventually,
22510 ;; `org-insert-comment' takes care of insertion of comments at the
22511 ;; beginning of line.
22513 ;; `org-setup-comments-handling' install comments related variables
22514 ;; during `org-mode' initialization.
22516 (defun org-setup-comments-handling ()
22517 (interactive)
22518 (org-set-local 'comment-use-syntax nil)
22519 (org-set-local 'comment-start "# ")
22520 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22521 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22522 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22523 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22525 (defun org-insert-comment ()
22526 "Insert an empty comment above current line.
22527 If the line is empty, insert comment at its beginning."
22528 (beginning-of-line)
22529 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
22530 (org-indent-line)
22531 (insert "# "))
22533 (defvar comment-empty-lines) ; From newcomment.el.
22534 (defun org-comment-or-uncomment-region (beg end &rest ignore)
22535 "Comment or uncomment each non-blank line in the region.
22536 Uncomment each non-blank line between BEG and END if it only
22537 contains commented lines. Otherwise, comment them."
22538 (save-restriction
22539 ;; Restrict region
22540 (narrow-to-region (save-excursion (goto-char beg)
22541 (skip-chars-forward " \r\t\n" end)
22542 (line-beginning-position))
22543 (save-excursion (goto-char end)
22544 (skip-chars-backward " \r\t\n" beg)
22545 (line-end-position)))
22546 (let ((uncommentp
22547 ;; UNCOMMENTP is non-nil when every non blank line between
22548 ;; BEG and END is a comment.
22549 (save-excursion
22550 (goto-char (point-min))
22551 (while (and (not (eobp))
22552 (let ((element (org-element-at-point)))
22553 (and (eq (org-element-type element) 'comment)
22554 (goto-char (min (point-max)
22555 (org-element-property
22556 :end element)))))))
22557 (eobp))))
22558 (if uncommentp
22559 ;; Only blank lines and comments in region: uncomment it.
22560 (save-excursion
22561 (goto-char (point-min))
22562 (while (not (eobp))
22563 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22564 (replace-match "" nil nil nil 1))
22565 (forward-line)))
22566 ;; Comment each line in region.
22567 (let ((min-indent (point-max)))
22568 ;; First find the minimum indentation across all lines.
22569 (save-excursion
22570 (goto-char (point-min))
22571 (while (and (not (eobp)) (not (zerop min-indent)))
22572 (unless (looking-at "[ \t]*$")
22573 (setq min-indent (min min-indent (current-indentation))))
22574 (forward-line)))
22575 ;; Then loop over all lines.
22576 (save-excursion
22577 (goto-char (point-min))
22578 (while (not (eobp))
22579 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22580 ;; Don't get fooled by invisible text (e.g. link path)
22581 ;; when moving to column MIN-INDENT.
22582 (let ((buffer-invisibility-spec nil))
22583 (org-move-to-column min-indent t))
22584 (insert comment-start))
22585 (forward-line))))))))
22588 ;;; Planning
22590 ;; This section contains tools to operate on timestamp objects, as
22591 ;; returned by, e.g. `org-element-context'.
22593 (defun org-timestamp-has-time-p (timestamp)
22594 "Non-nil when TIMESTAMP has a time specified."
22595 (org-element-property :hour-start timestamp))
22597 (defun org-timestamp-format (timestamp format &optional end utc)
22598 "Format a TIMESTAMP element into a string.
22600 FORMAT is a format specifier to be passed to
22601 `format-time-string'.
22603 When optional argument END is non-nil, use end of date-range or
22604 time-range, if possible.
22606 When optional argument UTC is non-nil, time will be expressed as
22607 Universal Time."
22608 (format-time-string
22609 format
22610 (apply 'encode-time
22611 (cons 0
22612 (mapcar
22613 (lambda (prop) (or (org-element-property prop timestamp) 0))
22614 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22615 '(:minute-start :hour-start :day-start :month-start
22616 :year-start)))))
22617 utc))
22619 (defun org-timestamp-split-range (timestamp &optional end)
22620 "Extract a timestamp object from a date or time range.
22622 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22623 the end of the range. Otherwise, extract its start.
22625 Return a new timestamp object sharing the same parent as
22626 TIMESTAMP."
22627 (let ((type (org-element-property :type timestamp)))
22628 (if (memq type '(active inactive diary)) timestamp
22629 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22630 ;; Set new type.
22631 (org-element-put-property
22632 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22633 ;; Copy start properties over end properties if END is
22634 ;; non-nil. Otherwise, copy end properties over `start' ones.
22635 (let ((p-alist '((:minute-start . :minute-end)
22636 (:hour-start . :hour-end)
22637 (:day-start . :day-end)
22638 (:month-start . :month-end)
22639 (:year-start . :year-end))))
22640 (dolist (p-cell p-alist)
22641 (org-element-put-property
22642 split-ts
22643 (funcall (if end 'car 'cdr) p-cell)
22644 (org-element-property
22645 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22646 ;; Eventually refresh `:raw-value'.
22647 (org-element-put-property split-ts :raw-value nil)
22648 (org-element-put-property
22649 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22651 (defun org-timestamp-translate (timestamp &optional boundary)
22652 "Apply `org-translate-time' on a TIMESTAMP object.
22653 When optional argument BOUNDARY is non-nil, it is either the
22654 symbol `start' or `end'. In this case, only translate the
22655 starting or ending part of TIMESTAMP if it is a date or time
22656 range. Otherwise, translate both parts."
22657 (if (and (not boundary)
22658 (memq (org-element-property :type timestamp)
22659 '(active-range inactive-range)))
22660 (concat
22661 (org-translate-time
22662 (org-element-property :raw-value
22663 (org-timestamp-split-range timestamp)))
22664 "--"
22665 (org-translate-time
22666 (org-element-property :raw-value
22667 (org-timestamp-split-range timestamp t))))
22668 (org-translate-time
22669 (org-element-property
22670 :raw-value
22671 (if (not boundary) timestamp
22672 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22676 ;;; Other stuff.
22678 (defun org-toggle-fixed-width-section (arg)
22679 "Toggle the fixed-width export.
22680 If there is no active region, the QUOTE keyword at the current headline is
22681 inserted or removed. When present, it causes the text between this headline
22682 and the next to be exported as fixed-width text, and unmodified.
22683 If there is an active region, this command adds or removes a colon as the
22684 first character of this line. If the first character of a line is a colon,
22685 this line is also exported in fixed-width font."
22686 (interactive "P")
22687 (let* ((cc 0)
22688 (regionp (org-region-active-p))
22689 (beg (if regionp (region-beginning) (point)))
22690 (end (if regionp (region-end)))
22691 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22692 (case-fold-search nil)
22693 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22694 off)
22695 (if regionp
22696 (save-excursion
22697 (goto-char beg)
22698 (setq cc (current-column))
22699 (beginning-of-line 1)
22700 (setq off (looking-at re))
22701 (while (> nlines 0)
22702 (setq nlines (1- nlines))
22703 (beginning-of-line 1)
22704 (cond
22705 (arg
22706 (org-move-to-column cc t)
22707 (insert ": \n")
22708 (forward-line -1))
22709 ((and off (looking-at re))
22710 (replace-match "" t t nil 1))
22711 ((not off) (org-move-to-column cc t) (insert ": ")))
22712 (forward-line 1)))
22713 (save-excursion
22714 (org-back-to-heading)
22715 (cond
22716 ((looking-at (format org-heading-keyword-regexp-format
22717 org-quote-string))
22718 (goto-char (match-end 1))
22719 (looking-at (concat " +" org-quote-string))
22720 (replace-match "" t t)
22721 (when (eolp) (insert " ")))
22722 ((looking-at org-outline-regexp)
22723 (goto-char (match-end 0))
22724 (insert org-quote-string " ")))))))
22726 (defun org-reftex-citation ()
22727 "Use reftex-citation to insert a citation into the buffer.
22728 This looks for a line like
22730 #+BIBLIOGRAPHY: foo plain option:-d
22732 and derives from it that foo.bib is the bibliography file relevant
22733 for this document. It then installs the necessary environment for RefTeX
22734 to work in this buffer and calls `reftex-citation' to insert a citation
22735 into the buffer.
22737 Export of such citations to both LaTeX and HTML is handled by the contributed
22738 package ox-bibtex by Taru Karttunen."
22739 (interactive)
22740 (let ((reftex-docstruct-symbol 'rds)
22741 (reftex-cite-format "\\cite{%l}")
22742 rds bib)
22743 (save-excursion
22744 (save-restriction
22745 (widen)
22746 (let ((case-fold-search t)
22747 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22748 (if (not (save-excursion
22749 (or (re-search-forward re nil t)
22750 (re-search-backward re nil t))))
22751 (error "No bibliography defined in file")
22752 (setq bib (concat (match-string 1) ".bib")
22753 rds (list (list 'bib bib)))))))
22754 (call-interactively 'reftex-citation)))
22756 ;;;; Functions extending outline functionality
22758 (defun org-beginning-of-line (&optional arg)
22759 "Go to the beginning of the current line. If that is invisible, continue
22760 to a visible line beginning. This makes the function of C-a more intuitive.
22761 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22762 first attempt, and only move to after the tags when the cursor is already
22763 beyond the end of the headline."
22764 (interactive "P")
22765 (let ((pos (point))
22766 (special (if (consp org-special-ctrl-a/e)
22767 (car org-special-ctrl-a/e)
22768 org-special-ctrl-a/e))
22769 deactivate-mark refpos)
22770 (if (org-bound-and-true-p visual-line-mode)
22771 (beginning-of-visual-line 1)
22772 (beginning-of-line 1))
22773 (if (and arg (fboundp 'move-beginning-of-line))
22774 (call-interactively 'move-beginning-of-line)
22775 (if (bobp)
22777 (backward-char 1)
22778 (if (org-truely-invisible-p)
22779 (while (and (not (bobp)) (org-truely-invisible-p))
22780 (backward-char 1)
22781 (beginning-of-line 1))
22782 (forward-char 1))))
22783 (when special
22784 (cond
22785 ((and (looking-at org-complex-heading-regexp)
22786 (= (char-after (match-end 1)) ?\ ))
22787 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22788 (point-at-eol)))
22789 (goto-char
22790 (if (eq special t)
22791 (cond ((> pos refpos) refpos)
22792 ((= pos (point)) refpos)
22793 (t (point)))
22794 (cond ((> pos (point)) (point))
22795 ((not (eq last-command this-command)) (point))
22796 (t refpos)))))
22797 ((org-at-item-p)
22798 ;; Being at an item and not looking at an the item means point
22799 ;; was previously moved to beginning of a visual line, which
22800 ;; doesn't contain the item. Therefore, do nothing special,
22801 ;; just stay here.
22802 (when (looking-at org-list-full-item-re)
22803 ;; Set special position at first white space character after
22804 ;; bullet, and check-box, if any.
22805 (let ((after-bullet
22806 (let ((box (match-end 3)))
22807 (if (not box) (match-end 1)
22808 (let ((after (char-after box)))
22809 (if (and after (= after ? )) (1+ box) box))))))
22810 ;; Special case: Move point to special position when
22811 ;; currently after it or at beginning of line.
22812 (if (eq special t)
22813 (when (or (> pos after-bullet) (= (point) pos))
22814 (goto-char after-bullet))
22815 ;; Reversed case: Move point to special position when
22816 ;; point was already at beginning of line and command is
22817 ;; repeated.
22818 (when (and (= (point) pos) (eq last-command this-command))
22819 (goto-char after-bullet))))))))
22820 (org-no-warnings
22821 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22822 (setq disable-point-adjustment
22823 (or (not (invisible-p (point)))
22824 (not (invisible-p (max (point-min) (1- (point))))))))
22826 (defun org-end-of-line (&optional arg)
22827 "Go to the end of the line.
22828 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22829 tags on the first attempt, and only move to after the tags when
22830 the cursor is already beyond the end of the headline."
22831 (interactive "P")
22832 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22833 org-special-ctrl-a/e))
22834 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22835 'end-of-visual-line)
22836 ((fboundp 'move-end-of-line) 'move-end-of-line)
22837 (t 'end-of-line)))
22838 deactivate-mark)
22839 (if (or (not special) arg) (call-interactively move-fun)
22840 (let* ((element (save-excursion (beginning-of-line)
22841 (org-element-at-point)))
22842 (type (org-element-type element)))
22843 (cond
22844 ((memq type '(headline inlinetask))
22845 (let ((pos (point)))
22846 (beginning-of-line 1)
22847 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22848 (if (eq special t)
22849 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22850 (goto-char (match-beginning 1))
22851 (goto-char (match-end 0)))
22852 (if (or (< pos (match-end 0))
22853 (not (eq this-command last-command)))
22854 (goto-char (match-end 0))
22855 (goto-char (match-beginning 1))))
22856 (call-interactively move-fun))))
22857 ((org-element-property :hiddenp element)
22858 ;; If element is hidden, `move-end-of-line' would put point
22859 ;; after it. Use `end-of-line' to stay on current line.
22860 (call-interactively 'end-of-line))
22861 (t (call-interactively move-fun)))))
22862 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22863 (setq disable-point-adjustment
22864 (or (not (invisible-p (point)))
22865 (not (invisible-p (max (point-min) (1- (point))))))))
22867 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22868 (define-key org-mode-map "\C-e" 'org-end-of-line)
22870 (defun org-backward-sentence (&optional arg)
22871 "Go to beginning of sentence, or beginning of table field.
22872 This will call `backward-sentence' or `org-table-beginning-of-field',
22873 depending on context."
22874 (interactive "P")
22875 (cond
22876 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22877 (t (call-interactively 'backward-sentence))))
22879 (defun org-forward-sentence (&optional arg)
22880 "Go to end of sentence, or end of table field.
22881 This will call `forward-sentence' or `org-table-end-of-field',
22882 depending on context."
22883 (interactive "P")
22884 (cond
22885 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22886 (t (call-interactively 'forward-sentence))))
22888 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22889 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22891 (defun org-kill-line (&optional arg)
22892 "Kill line, to tags or end of line."
22893 (interactive "P")
22894 (cond
22895 ((or (not org-special-ctrl-k)
22896 (bolp)
22897 (not (org-at-heading-p)))
22898 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22899 org-ctrl-k-protect-subtree)
22900 (if (or (eq org-ctrl-k-protect-subtree 'error)
22901 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22902 (user-error "C-k aborted as it would kill a hidden subtree")))
22903 (call-interactively
22904 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22905 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22906 (kill-region (point) (match-beginning 1))
22907 (org-set-tags nil t))
22908 (t (kill-region (point) (point-at-eol)))))
22910 (define-key org-mode-map "\C-k" 'org-kill-line)
22912 (defun org-yank (&optional arg)
22913 "Yank. If the kill is a subtree, treat it specially.
22914 This command will look at the current kill and check if is a single
22915 subtree, or a series of subtrees[1]. If it passes the test, and if the
22916 cursor is at the beginning of a line or after the stars of a currently
22917 empty headline, then the yank is handled specially. How exactly depends
22918 on the value of the following variables, both set by default.
22920 org-yank-folded-subtrees
22921 When set, the subtree(s) will be folded after insertion, but only
22922 if doing so would now swallow text after the yanked text.
22924 org-yank-adjusted-subtrees
22925 When set, the subtree will be promoted or demoted in order to
22926 fit into the local outline tree structure, which means that the level
22927 will be adjusted so that it becomes the smaller one of the two
22928 *visible* surrounding headings.
22930 Any prefix to this command will cause `yank' to be called directly with
22931 no special treatment. In particular, a simple \\[universal-argument] prefix \
22932 will just
22933 plainly yank the text as it is.
22935 \[1] The test checks if the first non-white line is a heading
22936 and if there are no other headings with fewer stars."
22937 (interactive "P")
22938 (org-yank-generic 'yank arg))
22940 (defun org-yank-generic (command arg)
22941 "Perform some yank-like command.
22943 This function implements the behavior described in the `org-yank'
22944 documentation. However, it has been generalized to work for any
22945 interactive command with similar behavior."
22947 ;; pretend to be command COMMAND
22948 (setq this-command command)
22950 (if arg
22951 (call-interactively command)
22953 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22954 (and (org-kill-is-subtree-p)
22955 (or (bolp)
22956 (and (looking-at "[ \t]*$")
22957 (string-match
22958 "\\`\\*+\\'"
22959 (buffer-substring (point-at-bol) (point)))))))
22960 swallowp)
22961 (cond
22962 ((and subtreep org-yank-folded-subtrees)
22963 (let ((beg (point))
22964 end)
22965 (if (and subtreep org-yank-adjusted-subtrees)
22966 (org-paste-subtree nil nil 'for-yank)
22967 (call-interactively command))
22969 (setq end (point))
22970 (goto-char beg)
22971 (when (and (bolp) subtreep
22972 (not (setq swallowp
22973 (org-yank-folding-would-swallow-text beg end))))
22974 (org-with-limited-levels
22975 (or (looking-at org-outline-regexp)
22976 (re-search-forward org-outline-regexp-bol end t))
22977 (while (and (< (point) end) (looking-at org-outline-regexp))
22978 (hide-subtree)
22979 (org-cycle-show-empty-lines 'folded)
22980 (condition-case nil
22981 (outline-forward-same-level 1)
22982 (error (goto-char end))))))
22983 (when swallowp
22984 (message
22985 "Inserted text not folded because that would swallow text"))
22987 (goto-char end)
22988 (skip-chars-forward " \t\n\r")
22989 (beginning-of-line 1)
22990 (push-mark beg 'nomsg)))
22991 ((and subtreep org-yank-adjusted-subtrees)
22992 (let ((beg (point-at-bol)))
22993 (org-paste-subtree nil nil 'for-yank)
22994 (push-mark beg 'nomsg)))
22996 (call-interactively command))))))
22998 (defun org-yank-folding-would-swallow-text (beg end)
22999 "Would hide-subtree at BEG swallow any text after END?"
23000 (let (level)
23001 (org-with-limited-levels
23002 (save-excursion
23003 (goto-char beg)
23004 (when (or (looking-at org-outline-regexp)
23005 (re-search-forward org-outline-regexp-bol end t))
23006 (setq level (org-outline-level)))
23007 (goto-char end)
23008 (skip-chars-forward " \t\r\n\v\f")
23009 (if (or (eobp)
23010 (and (bolp) (looking-at org-outline-regexp)
23011 (<= (org-outline-level) level)))
23012 nil ; Nothing would be swallowed
23013 t))))) ; something would swallow
23015 (define-key org-mode-map "\C-y" 'org-yank)
23017 (defun org-truely-invisible-p ()
23018 "Check if point is at a character currently not visible.
23019 This version does not only check the character property, but also
23020 `visible-mode'."
23021 ;; Early versions of noutline don't have `outline-invisible-p'.
23022 (if (org-bound-and-true-p visible-mode)
23024 (outline-invisible-p)))
23026 (defun org-invisible-p2 ()
23027 "Check if point is at a character currently not visible."
23028 (save-excursion
23029 (if (and (eolp) (not (bobp))) (backward-char 1))
23030 ;; Early versions of noutline don't have `outline-invisible-p'.
23031 (outline-invisible-p)))
23033 (defun org-back-to-heading (&optional invisible-ok)
23034 "Call `outline-back-to-heading', but provide a better error message."
23035 (condition-case nil
23036 (outline-back-to-heading invisible-ok)
23037 (error (error "Before first headline at position %d in buffer %s"
23038 (point) (current-buffer)))))
23040 (defun org-before-first-heading-p ()
23041 "Before first heading?"
23042 (save-excursion
23043 (end-of-line)
23044 (null (re-search-backward org-outline-regexp-bol nil t))))
23046 (defun org-at-heading-p (&optional ignored)
23047 (outline-on-heading-p t))
23048 ;; Compatibility alias with Org versions < 7.8.03
23049 (defalias 'org-on-heading-p 'org-at-heading-p)
23051 (defun org-at-comment-p nil
23052 "Is cursor in a line starting with a # character?"
23053 (save-excursion
23054 (beginning-of-line)
23055 (looking-at "^#")))
23057 (defun org-at-drawer-p nil
23058 "Is cursor at a drawer keyword?"
23059 (save-excursion
23060 (move-beginning-of-line 1)
23061 (looking-at org-drawer-regexp)))
23063 (defun org-at-block-p nil
23064 "Is cursor at a block keyword?"
23065 (save-excursion
23066 (move-beginning-of-line 1)
23067 (looking-at org-block-regexp)))
23069 (defun org-point-at-end-of-empty-headline ()
23070 "If point is at the end of an empty headline, return t, else nil.
23071 If the heading only contains a TODO keyword, it is still still considered
23072 empty."
23073 (and (looking-at "[ \t]*$")
23074 (when org-todo-line-regexp
23075 (save-excursion
23076 (beginning-of-line 1)
23077 (let ((case-fold-search nil))
23078 (looking-at org-todo-line-regexp)
23079 (string= (match-string 3) ""))))))
23081 (defun org-at-heading-or-item-p ()
23082 (or (org-at-heading-p) (org-at-item-p)))
23084 (defun org-at-target-p ()
23085 (or (org-in-regexp org-radio-target-regexp)
23086 (org-in-regexp org-target-regexp)))
23087 ;; Compatibility alias with Org versions < 7.8.03
23088 (defalias 'org-on-target-p 'org-at-target-p)
23090 (defun org-up-heading-all (arg)
23091 "Move to the heading line of which the present line is a subheading.
23092 This function considers both visible and invisible heading lines.
23093 With argument, move up ARG levels."
23094 (if (fboundp 'outline-up-heading-all)
23095 (outline-up-heading-all arg) ; emacs 21 version of outline.el
23096 (outline-up-heading arg t))) ; emacs 22 version of outline.el
23098 (defun org-up-heading-safe ()
23099 "Move to the heading line of which the present line is a subheading.
23100 This version will not throw an error. It will return the level of the
23101 headline found, or nil if no higher level is found.
23103 Also, this function will be a lot faster than `outline-up-heading',
23104 because it relies on stars being the outline starters. This can really
23105 make a significant difference in outlines with very many siblings."
23106 (let (start-level re)
23107 (org-back-to-heading t)
23108 (setq start-level (funcall outline-level))
23109 (if (equal start-level 1)
23111 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
23112 (if (re-search-backward re nil t)
23113 (funcall outline-level)))))
23115 (defun org-first-sibling-p ()
23116 "Is this heading the first child of its parents?"
23117 (interactive)
23118 (let ((re org-outline-regexp-bol)
23119 level l)
23120 (unless (org-at-heading-p t)
23121 (user-error "Not at a heading"))
23122 (setq level (funcall outline-level))
23123 (save-excursion
23124 (if (not (re-search-backward re nil t))
23126 (setq l (funcall outline-level))
23127 (< l level)))))
23129 (defun org-goto-sibling (&optional previous)
23130 "Goto the next sibling, even if it is invisible.
23131 When PREVIOUS is set, go to the previous sibling instead. Returns t
23132 when a sibling was found. When none is found, return nil and don't
23133 move point."
23134 (let ((fun (if previous 're-search-backward 're-search-forward))
23135 (pos (point))
23136 (re org-outline-regexp-bol)
23137 level l)
23138 (when (condition-case nil (org-back-to-heading t) (error nil))
23139 (setq level (funcall outline-level))
23140 (catch 'exit
23141 (or previous (forward-char 1))
23142 (while (funcall fun re nil t)
23143 (setq l (funcall outline-level))
23144 (when (< l level) (goto-char pos) (throw 'exit nil))
23145 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23146 (goto-char pos)
23147 nil))))
23149 (defun org-show-siblings ()
23150 "Show all siblings of the current headline."
23151 (save-excursion
23152 (while (org-goto-sibling) (org-flag-heading nil)))
23153 (save-excursion
23154 (while (org-goto-sibling 'previous)
23155 (org-flag-heading nil))))
23157 (defun org-goto-first-child ()
23158 "Goto the first child, even if it is invisible.
23159 Return t when a child was found. Otherwise don't move point and
23160 return nil."
23161 (let (level (pos (point)) (re org-outline-regexp-bol))
23162 (when (condition-case nil (org-back-to-heading t) (error nil))
23163 (setq level (outline-level))
23164 (forward-char 1)
23165 (if (and (re-search-forward re nil t) (> (outline-level) level))
23166 (progn (goto-char (match-beginning 0)) t)
23167 (goto-char pos) nil))))
23169 (defun org-show-hidden-entry ()
23170 "Show an entry where even the heading is hidden."
23171 (save-excursion
23172 (org-show-entry)))
23174 (defun org-flag-heading (flag &optional entry)
23175 "Flag the current heading. FLAG non-nil means make invisible.
23176 When ENTRY is non-nil, show the entire entry."
23177 (save-excursion
23178 (org-back-to-heading t)
23179 ;; Check if we should show the entire entry
23180 (if entry
23181 (progn
23182 (org-show-entry)
23183 (save-excursion
23184 (and (outline-next-heading)
23185 (org-flag-heading nil))))
23186 (outline-flag-region (max (point-min) (1- (point)))
23187 (save-excursion (outline-end-of-heading) (point))
23188 flag))))
23190 (defun org-get-next-sibling ()
23191 "Move to next heading of the same level, and return point.
23192 If there is no such heading, return nil.
23193 This is like outline-next-sibling, but invisible headings are ok."
23194 (let ((level (funcall outline-level)))
23195 (outline-next-heading)
23196 (while (and (not (eobp)) (> (funcall outline-level) level))
23197 (outline-next-heading))
23198 (if (or (eobp) (< (funcall outline-level) level))
23200 (point))))
23202 (defun org-get-last-sibling ()
23203 "Move to previous heading of the same level, and return point.
23204 If there is no such heading, return nil."
23205 (let ((opoint (point))
23206 (level (funcall outline-level)))
23207 (outline-previous-heading)
23208 (when (and (/= (point) opoint) (outline-on-heading-p t))
23209 (while (and (> (funcall outline-level) level)
23210 (not (bobp)))
23211 (outline-previous-heading))
23212 (if (< (funcall outline-level) level)
23214 (point)))))
23216 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23217 "Goto to the end of a subtree."
23218 ;; This contains an exact copy of the original function, but it uses
23219 ;; `org-back-to-heading', to make it work also in invisible
23220 ;; trees. And is uses an invisible-ok argument.
23221 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23222 ;; Furthermore, when used inside Org, finding the end of a large subtree
23223 ;; with many children and grandchildren etc, this can be much faster
23224 ;; than the outline version.
23225 (org-back-to-heading invisible-ok)
23226 (let ((first t)
23227 (level (funcall outline-level)))
23228 (if (and (derived-mode-p 'org-mode) (< level 1000))
23229 ;; A true heading (not a plain list item), in Org-mode
23230 ;; This means we can easily find the end by looking
23231 ;; only for the right number of stars. Using a regexp to do
23232 ;; this is so much faster than using a Lisp loop.
23233 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23234 (forward-char 1)
23235 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23236 ;; something else, do it the slow way
23237 (while (and (not (eobp))
23238 (or first (> (funcall outline-level) level)))
23239 (setq first nil)
23240 (outline-next-heading)))
23241 (unless to-heading
23242 (if (memq (preceding-char) '(?\n ?\^M))
23243 (progn
23244 ;; Go to end of line before heading
23245 (forward-char -1)
23246 (if (memq (preceding-char) '(?\n ?\^M))
23247 ;; leave blank line before heading
23248 (forward-char -1))))))
23249 (point))
23251 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
23252 "Use Org version in org-mode, for dramatic speed-up."
23253 (if (derived-mode-p 'org-mode)
23254 (progn
23255 (org-end-of-subtree nil t)
23256 (unless (eobp) (backward-char 1)))
23257 ad-do-it))
23259 (defun org-end-of-meta-data-and-drawers ()
23260 "Jump to the first text after meta data and drawers in the current entry.
23261 This will move over empty lines, lines with planning time stamps,
23262 clocking lines, and drawers."
23263 (org-back-to-heading t)
23264 (let ((end (save-excursion (outline-next-heading) (point)))
23265 (re (concat "\\(" org-drawer-regexp "\\)"
23266 "\\|" "[ \t]*" org-keyword-time-regexp)))
23267 (forward-line 1)
23268 (while (re-search-forward re end t)
23269 (if (not (match-end 1))
23270 ;; empty or planning line
23271 (forward-line 1)
23272 ;; a drawer, find the end
23273 (re-search-forward "^[ \t]*:END:" end 'move)
23274 (forward-line 1)))
23275 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23276 (point)))
23278 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23279 "Move forward to the ARG'th subheading at same level as this one.
23280 Stop at the first and last subheadings of a superior heading.
23281 Normally this only looks at visible headings, but when INVISIBLE-OK is
23282 non-nil it will also look at invisible ones."
23283 (interactive "p")
23284 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23285 (if (and arg (< arg 0))
23286 (goto-char (point-min))
23287 (outline-next-heading))
23288 (org-at-heading-p)
23289 (let ((level (- (match-end 0) (match-beginning 0) 1))
23290 (f (if (and arg (< arg 0))
23291 're-search-backward
23292 're-search-forward))
23293 (count (if arg (abs arg) 1))
23294 (result (point)))
23295 (while (and (prog1 (> count 0)
23296 (forward-char (if (and arg (< arg 0)) -1 1)))
23297 (funcall f org-outline-regexp-bol nil 'move))
23298 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23299 (cond ((< l level) (setq count 0))
23300 ((and (= l level)
23301 (or invisible-ok
23302 (progn
23303 (goto-char (line-beginning-position))
23304 (not (outline-invisible-p)))))
23305 (setq count (1- count))
23306 (when (eq l level)
23307 (setq result (point)))))))
23308 (goto-char result))
23309 (beginning-of-line 1)))
23311 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23312 "Move backward to the ARG'th subheading at same level as this one.
23313 Stop at the first and last subheadings of a superior heading."
23314 (interactive "p")
23315 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23317 (defun org-next-block (arg &optional backward block-regexp)
23318 "Jump to the next block.
23319 With a prefix argument ARG, jump forward ARG many source blocks.
23320 When BACKWARD is non-nil, jump to the previous block.
23321 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23322 (interactive "p")
23323 (let ((re (or block-regexp org-block-regexp))
23324 (re-search-fn (or (and backward 're-search-backward)
23325 're-search-forward)))
23326 (if (looking-at re) (forward-char 1))
23327 (condition-case nil
23328 (funcall re-search-fn re nil nil arg)
23329 (error (error "No %s code blocks" (if backward "previous" "further" ))))
23330 (goto-char (match-beginning 0)) (org-show-context)))
23332 (defun org-previous-block (arg &optional block-regexp)
23333 "Jump to the previous block.
23334 With a prefix argument ARG, jump backward ARG many source blocks.
23335 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23336 (interactive "p")
23337 (org-next-block arg t block-regexp))
23339 (defun org-forward-paragraph ()
23340 "Move forward to beginning of next paragraph or equivalent.
23342 The function moves point to the beginning of the next visible
23343 structural element, which can be a paragraph, a table, a list
23344 item, etc. It also provides some special moves for convenience:
23346 - On an affiliated keyword, jump to the beginning of the
23347 relative element.
23348 - On an item or a footnote definition, move to the second
23349 element inside, if any.
23350 - On a table or a property drawer, jump after it.
23351 - On a verse or source block, stop after blank lines."
23352 (interactive)
23353 (when (eobp) (user-error "Cannot move further down"))
23354 (let* ((deactivate-mark nil)
23355 (element (org-element-at-point))
23356 (type (org-element-type element))
23357 (post-affiliated (org-element-property :post-affiliated element))
23358 (contents-begin (org-element-property :contents-begin element))
23359 (contents-end (org-element-property :contents-end element))
23360 (end (let ((end (org-element-property :end element)) (parent element))
23361 (while (and (setq parent (org-element-property :parent parent))
23362 (= (org-element-property :contents-end parent) end))
23363 (setq end (org-element-property :end parent)))
23364 end)))
23365 (cond ((not element)
23366 (skip-chars-forward " \r\t\n")
23367 (or (eobp) (beginning-of-line)))
23368 ;; On affiliated keywords, move to element's beginning.
23369 ((and post-affiliated (< (point) post-affiliated))
23370 (goto-char post-affiliated))
23371 ;; At a table row, move to the end of the table. Similarly,
23372 ;; at a node property, move to the end of the property
23373 ;; drawer.
23374 ((memq type '(node-property table-row))
23375 (goto-char (org-element-property
23376 :end (org-element-property :parent element))))
23377 ((memq type '(property-drawer table)) (goto-char end))
23378 ;; Consider blank lines as separators in verse and source
23379 ;; blocks to ease editing.
23380 ((memq type '(src-block verse-block))
23381 (when (eq type 'src-block)
23382 (setq contents-end
23383 (save-excursion (goto-char end)
23384 (skip-chars-backward " \r\t\n")
23385 (line-beginning-position))))
23386 (beginning-of-line)
23387 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23388 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23389 (goto-char end)
23390 (skip-chars-forward " \r\t\n")
23391 (if (= (point) contents-end) (goto-char end)
23392 (beginning-of-line))))
23393 ;; With no contents, just skip element.
23394 ((not contents-begin) (goto-char end))
23395 ;; If contents are invisible, skip the element altogether.
23396 ((outline-invisible-p (line-end-position))
23397 (case type
23398 (headline
23399 (org-with-limited-levels (outline-next-visible-heading 1)))
23400 ;; At a plain list, make sure we move to the next item
23401 ;; instead of skipping the whole list.
23402 (plain-list (forward-char)
23403 (org-forward-paragraph))
23404 (otherwise (goto-char end))))
23405 ((>= (point) contents-end) (goto-char end))
23406 ((>= (point) contents-begin)
23407 ;; This can only happen on paragraphs and plain lists.
23408 (case type
23409 (paragraph (goto-char end))
23410 ;; At a plain list, try to move to second element in
23411 ;; first item, if possible.
23412 (plain-list (end-of-line)
23413 (org-forward-paragraph))))
23414 ;; When contents start on the middle of a line (e.g. in
23415 ;; items and footnote definitions), try to reach first
23416 ;; element starting after current line.
23417 ((> (line-end-position) contents-begin)
23418 (end-of-line)
23419 (org-forward-paragraph))
23420 (t (goto-char contents-begin)))))
23422 (defun org-backward-paragraph ()
23423 "Move backward to start of previous paragraph or equivalent.
23425 The function moves point to the beginning of the current
23426 structural element, which can be a paragraph, a table, a list
23427 item, etc., or to the beginning of the previous visible one if
23428 point is already there. It also provides some special moves for
23429 convenience:
23431 - On an affiliated keyword, jump to the first one.
23432 - On a table or a property drawer, move to its beginning.
23433 - On a verse or source block, stop before blank lines."
23434 (interactive)
23435 (when (bobp) (user-error "Cannot move further up"))
23436 (let* ((deactivate-mark nil)
23437 (element (org-element-at-point))
23438 (type (org-element-type element))
23439 (contents-begin (org-element-property :contents-begin element))
23440 (contents-end (org-element-property :contents-end element))
23441 (post-affiliated (org-element-property :post-affiliated element))
23442 (begin (org-element-property :begin element)))
23443 (cond
23444 ((not element) (goto-char (point-min)))
23445 ((= (point) begin)
23446 (backward-char)
23447 (org-backward-paragraph))
23448 ((and post-affiliated (<= (point) post-affiliated)) (goto-char begin))
23449 ((memq type '(node-property table-row))
23450 (goto-char (org-element-property
23451 :post-affiliated (org-element-property :parent element))))
23452 ((memq type '(property-drawer table)) (goto-char begin))
23453 ((memq type '(src-block verse-block))
23454 (when (eq type 'src-block)
23455 (setq contents-begin
23456 (save-excursion (goto-char begin) (forward-line) (point))))
23457 (if (= (point) contents-begin) (goto-char post-affiliated)
23458 ;; Inside a verse block, see blank lines as paragraph
23459 ;; separators.
23460 (let ((origin (point)))
23461 (skip-chars-backward " \r\t\n" contents-begin)
23462 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
23463 (skip-chars-forward " \r\t\n" origin)
23464 (if (= (point) origin) (goto-char contents-begin)
23465 (beginning-of-line))))))
23466 ((not contents-begin) (goto-char (or post-affiliated begin)))
23467 ((eq type 'paragraph)
23468 (goto-char contents-begin)
23469 ;; When at first paragraph in an item or a footnote definition,
23470 ;; move directly to beginning of line.
23471 (let ((parent-contents
23472 (org-element-property
23473 :contents-begin (org-element-property :parent element))))
23474 (when (and parent-contents (= parent-contents contents-begin))
23475 (beginning-of-line))))
23476 ;; At the end of a greater element, move to the beginning of the
23477 ;; last element within.
23478 ((>= (point) contents-end)
23479 (goto-char (1- contents-end))
23480 (org-backward-paragraph))
23481 (t (goto-char (or post-affiliated begin))))
23482 ;; Ensure we never leave point invisible.
23483 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
23485 (defun org-forward-element ()
23486 "Move forward by one element.
23487 Move to the next element at the same level, when possible."
23488 (interactive)
23489 (cond ((eobp) (user-error "Cannot move further down"))
23490 ((org-with-limited-levels (org-at-heading-p))
23491 (let ((origin (point)))
23492 (goto-char (org-end-of-subtree nil t))
23493 (unless (org-with-limited-levels (org-at-heading-p))
23494 (goto-char origin)
23495 (user-error "Cannot move further down"))))
23497 (let* ((elem (org-element-at-point))
23498 (end (org-element-property :end elem))
23499 (parent (org-element-property :parent elem)))
23500 (cond ((and parent (= (org-element-property :contents-end parent) end))
23501 (goto-char (org-element-property :end parent)))
23502 ((integer-or-marker-p end) (goto-char end))
23503 (t (message "No element at point")))))))
23505 (defun org-backward-element ()
23506 "Move backward by one element.
23507 Move to the previous element at the same level, when possible."
23508 (interactive)
23509 (cond ((bobp) (user-error "Cannot move further up"))
23510 ((org-with-limited-levels (org-at-heading-p))
23511 ;; At a headline, move to the previous one, if any, or stay
23512 ;; here.
23513 (let ((origin (point)))
23514 (org-with-limited-levels (org-backward-heading-same-level 1))
23515 ;; When current headline has no sibling above, move to its
23516 ;; parent.
23517 (when (= (point) origin)
23518 (or (org-with-limited-levels (org-up-heading-safe))
23519 (progn (goto-char origin)
23520 (user-error "Cannot move further up"))))))
23522 (let* ((trail (org-element-at-point 'keep-trail))
23523 (elem (car trail))
23524 (prev-elem (nth 1 trail))
23525 (beg (org-element-property :begin elem)))
23526 (cond
23527 ;; Move to beginning of current element if point isn't
23528 ;; there already.
23529 ((null beg) (message "No element at point"))
23530 ((/= (point) beg) (goto-char beg))
23531 (prev-elem (goto-char (org-element-property :begin prev-elem)))
23532 ((org-before-first-heading-p) (goto-char (point-min)))
23533 (t (org-back-to-heading)))))))
23535 (defun org-up-element ()
23536 "Move to upper element."
23537 (interactive)
23538 (if (org-with-limited-levels (org-at-heading-p))
23539 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23540 (let* ((elem (org-element-at-point))
23541 (parent (org-element-property :parent elem)))
23542 (if parent (goto-char (org-element-property :begin parent))
23543 (if (org-with-limited-levels (org-before-first-heading-p))
23544 (user-error "No surrounding element")
23545 (org-with-limited-levels (org-back-to-heading)))))))
23547 (defvar org-element-greater-elements)
23548 (defun org-down-element ()
23549 "Move to inner element."
23550 (interactive)
23551 (let ((element (org-element-at-point)))
23552 (cond
23553 ((memq (org-element-type element) '(plain-list table))
23554 (goto-char (org-element-property :contents-begin element))
23555 (forward-char))
23556 ((memq (org-element-type element) org-element-greater-elements)
23557 ;; If contents are hidden, first disclose them.
23558 (when (org-element-property :hiddenp element) (org-cycle))
23559 (goto-char (or (org-element-property :contents-begin element)
23560 (user-error "No content for this element"))))
23561 (t (user-error "No inner element")))))
23563 (defun org-drag-element-backward ()
23564 "Move backward element at point."
23565 (interactive)
23566 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
23567 (let* ((trail (org-element-at-point 'keep-trail))
23568 (elem (car trail))
23569 (prev-elem (nth 1 trail)))
23570 ;; Error out if no previous element or previous element is
23571 ;; a parent of the current one.
23572 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23573 (user-error "Cannot drag element backward")
23574 (let ((pos (point)))
23575 (org-element-swap-A-B prev-elem elem)
23576 (goto-char (+ (org-element-property :begin prev-elem)
23577 (- pos (org-element-property :begin elem)))))))))
23579 (defun org-drag-element-forward ()
23580 "Move forward element at point."
23581 (interactive)
23582 (let* ((pos (point))
23583 (elem (org-element-at-point)))
23584 (when (= (point-max) (org-element-property :end elem))
23585 (user-error "Cannot drag element forward"))
23586 (goto-char (org-element-property :end elem))
23587 (let ((next-elem (org-element-at-point)))
23588 (when (or (org-element-nested-p elem next-elem)
23589 (and (eq (org-element-type next-elem) 'headline)
23590 (not (eq (org-element-type elem) 'headline))))
23591 (goto-char pos)
23592 (user-error "Cannot drag element forward"))
23593 ;; Compute new position of point: it's shifted by NEXT-ELEM
23594 ;; body's length (without final blanks) and by the length of
23595 ;; blanks between ELEM and NEXT-ELEM.
23596 (let ((size-next (- (save-excursion
23597 (goto-char (org-element-property :end next-elem))
23598 (skip-chars-backward " \r\t\n")
23599 (forward-line)
23600 ;; Small correction if buffer doesn't end
23601 ;; with a newline character.
23602 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23603 (org-element-property :begin next-elem)))
23604 (size-blank (- (org-element-property :end elem)
23605 (save-excursion
23606 (goto-char (org-element-property :end elem))
23607 (skip-chars-backward " \r\t\n")
23608 (forward-line)
23609 (point)))))
23610 (org-element-swap-A-B elem next-elem)
23611 (goto-char (+ pos size-next size-blank))))))
23613 (defun org-drag-line-forward (arg)
23614 "Drag the line at point ARG lines forward."
23615 (interactive "p")
23616 (dotimes (n (abs arg))
23617 (let ((c (current-column)))
23618 (if (< 0 arg)
23619 (progn
23620 (beginning-of-line 2)
23621 (transpose-lines 1)
23622 (beginning-of-line 0))
23623 (transpose-lines 1)
23624 (beginning-of-line -1))
23625 (org-move-to-column c))))
23627 (defun org-drag-line-backward (arg)
23628 "Drag the line at point ARG lines backward."
23629 (interactive "p")
23630 (org-drag-line-forward (- arg)))
23632 (defun org-mark-element ()
23633 "Put point at beginning of this element, mark at end.
23635 Interactively, if this command is repeated or (in Transient Mark
23636 mode) if the mark is active, it marks the next element after the
23637 ones already marked."
23638 (interactive)
23639 (let (deactivate-mark)
23640 (if (and (org-called-interactively-p 'any)
23641 (or (and (eq last-command this-command) (mark t))
23642 (and transient-mark-mode mark-active)))
23643 (set-mark
23644 (save-excursion
23645 (goto-char (mark))
23646 (goto-char (org-element-property :end (org-element-at-point)))))
23647 (let ((element (org-element-at-point)))
23648 (end-of-line)
23649 (push-mark (org-element-property :end element) t t)
23650 (goto-char (org-element-property :begin element))))))
23652 (defun org-narrow-to-element ()
23653 "Narrow buffer to current element."
23654 (interactive)
23655 (let ((elem (org-element-at-point)))
23656 (cond
23657 ((eq (car elem) 'headline)
23658 (narrow-to-region
23659 (org-element-property :begin elem)
23660 (org-element-property :end elem)))
23661 ((memq (car elem) org-element-greater-elements)
23662 (narrow-to-region
23663 (org-element-property :contents-begin elem)
23664 (org-element-property :contents-end elem)))
23666 (narrow-to-region
23667 (org-element-property :begin elem)
23668 (org-element-property :end elem))))))
23670 (defun org-transpose-element ()
23671 "Transpose current and previous elements, keeping blank lines between.
23672 Point is moved after both elements."
23673 (interactive)
23674 (org-skip-whitespace)
23675 (let ((end (org-element-property :end (org-element-at-point))))
23676 (org-drag-element-backward)
23677 (goto-char end)))
23679 (defun org-unindent-buffer ()
23680 "Un-indent the visible part of the buffer.
23681 Relative indentation (between items, inside blocks, etc.) isn't
23682 modified."
23683 (interactive)
23684 (unless (eq major-mode 'org-mode)
23685 (user-error "Cannot un-indent a buffer not in Org mode"))
23686 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
23687 unindent-tree ; For byte-compiler.
23688 (unindent-tree
23689 (function
23690 (lambda (contents)
23691 (mapc
23692 (lambda (element)
23693 (if (memq (org-element-type element) '(headline section))
23694 (funcall unindent-tree (org-element-contents element))
23695 (save-excursion
23696 (save-restriction
23697 (narrow-to-region
23698 (org-element-property :begin element)
23699 (org-element-property :end element))
23700 (org-do-remove-indentation)))))
23701 (reverse contents))))))
23702 (funcall unindent-tree (org-element-contents parse-tree))))
23704 (defun org-show-subtree ()
23705 "Show everything after this heading at deeper levels."
23706 (interactive)
23707 (outline-flag-region
23708 (point)
23709 (save-excursion
23710 (org-end-of-subtree t t))
23711 nil))
23713 (defun org-show-entry ()
23714 "Show the body directly following this heading.
23715 Show the heading too, if it is currently invisible."
23716 (interactive)
23717 (save-excursion
23718 (condition-case nil
23719 (progn
23720 (org-back-to-heading t)
23721 (outline-flag-region
23722 (max (point-min) (1- (point)))
23723 (save-excursion
23724 (if (re-search-forward
23725 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23726 (match-beginning 1)
23727 (point-max)))
23728 nil)
23729 (org-cycle-hide-drawers 'children))
23730 (error nil))))
23732 (defun org-make-options-regexp (kwds &optional extra)
23733 "Make a regular expression for keyword lines."
23734 (concat
23735 "^#\\+\\("
23736 (mapconcat 'regexp-quote kwds "\\|")
23737 (if extra (concat "\\|" extra))
23738 "\\):[ \t]*\\(.*\\)"))
23740 ;; Make isearch reveal the necessary context
23741 (defun org-isearch-end ()
23742 "Reveal context after isearch exits."
23743 (when isearch-success ; only if search was successful
23744 (if (featurep 'xemacs)
23745 ;; Under XEmacs, the hook is run in the correct place,
23746 ;; we directly show the context.
23747 (org-show-context 'isearch)
23748 ;; In Emacs the hook runs *before* restoring the overlays.
23749 ;; So we have to use a one-time post-command-hook to do this.
23750 ;; (Emacs 22 has a special variable, see function `org-mode')
23751 (unless (and (boundp 'isearch-mode-end-hook-quit)
23752 isearch-mode-end-hook-quit)
23753 ;; Only when the isearch was not quitted.
23754 (org-add-hook 'post-command-hook 'org-isearch-post-command
23755 'append 'local)))
23756 (org-fix-ellipsis-at-bol)))
23758 (defun org-isearch-post-command ()
23759 "Remove self from hook, and show context."
23760 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23761 (org-show-context 'isearch))
23764 ;;;; Integration with and fixes for other packages
23766 ;;; Imenu support
23768 (defvar org-imenu-markers nil
23769 "All markers currently used by Imenu.")
23770 (make-variable-buffer-local 'org-imenu-markers)
23772 (defun org-imenu-new-marker (&optional pos)
23773 "Return a new marker for use by Imenu, and remember the marker."
23774 (let ((m (make-marker)))
23775 (move-marker m (or pos (point)))
23776 (push m org-imenu-markers)
23779 (defun org-imenu-get-tree ()
23780 "Produce the index for Imenu."
23781 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23782 (setq org-imenu-markers nil)
23783 (let* ((n org-imenu-depth)
23784 (re (concat "^" (org-get-limited-outline-regexp)))
23785 (subs (make-vector (1+ n) nil))
23786 (last-level 0)
23787 m level head0 head)
23788 (save-excursion
23789 (save-restriction
23790 (widen)
23791 (goto-char (point-max))
23792 (while (re-search-backward re nil t)
23793 (setq level (org-reduced-level (funcall outline-level)))
23794 (when (and (<= level n)
23795 (looking-at org-complex-heading-regexp)
23796 (setq head0 (org-match-string-no-properties 4)))
23797 (setq head (org-link-display-format head0)
23798 m (org-imenu-new-marker))
23799 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23800 (if (>= level last-level)
23801 (push (cons head m) (aref subs level))
23802 (push (cons head (aref subs (1+ level))) (aref subs level))
23803 (loop for i from (1+ level) to n do (aset subs i nil)))
23804 (setq last-level level)))))
23805 (aref subs 1)))
23807 (eval-after-load "imenu"
23808 '(progn
23809 (add-hook 'imenu-after-jump-hook
23810 (lambda ()
23811 (if (derived-mode-p 'org-mode)
23812 (org-show-context 'org-goto))))))
23814 (defun org-link-display-format (link)
23815 "Replace a link with its the description.
23816 If there is no description, use the link target."
23817 (save-match-data
23818 (if (string-match org-bracket-link-analytic-regexp link)
23819 (replace-match (if (match-end 5)
23820 (match-string 5 link)
23821 (concat (match-string 1 link)
23822 (match-string 3 link)))
23823 nil t link)
23824 link)))
23826 (defun org-toggle-link-display ()
23827 "Toggle the literal or descriptive display of links."
23828 (interactive)
23829 (if org-descriptive-links
23830 (progn (org-remove-from-invisibility-spec '(org-link))
23831 (org-restart-font-lock)
23832 (setq org-descriptive-links nil))
23833 (progn (add-to-invisibility-spec '(org-link))
23834 (org-restart-font-lock)
23835 (setq org-descriptive-links t))))
23837 ;; Speedbar support
23839 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23840 "Overlay marking the agenda restriction line in speedbar.")
23841 (overlay-put org-speedbar-restriction-lock-overlay
23842 'face 'org-agenda-restriction-lock)
23843 (overlay-put org-speedbar-restriction-lock-overlay
23844 'help-echo "Agendas are currently limited to this item.")
23845 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23847 (defun org-speedbar-set-agenda-restriction ()
23848 "Restrict future agenda commands to the location at point in speedbar.
23849 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23850 (interactive)
23851 (require 'org-agenda)
23852 (let (p m tp np dir txt)
23853 (cond
23854 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23855 'org-imenu t))
23856 (setq m (get-text-property p 'org-imenu-marker))
23857 (with-current-buffer (marker-buffer m)
23858 (goto-char m)
23859 (org-agenda-set-restriction-lock 'subtree)))
23860 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23861 'speedbar-function 'speedbar-find-file))
23862 (setq tp (previous-single-property-change
23863 (1+ p) 'speedbar-function)
23864 np (next-single-property-change
23865 tp 'speedbar-function)
23866 dir (speedbar-line-directory)
23867 txt (buffer-substring-no-properties (or tp (point-min))
23868 (or np (point-max))))
23869 (with-current-buffer (find-file-noselect
23870 (let ((default-directory dir))
23871 (expand-file-name txt)))
23872 (unless (derived-mode-p 'org-mode)
23873 (user-error "Cannot restrict to non-Org-mode file"))
23874 (org-agenda-set-restriction-lock 'file)))
23875 (t (user-error "Don't know how to restrict Org-mode's agenda")))
23876 (move-overlay org-speedbar-restriction-lock-overlay
23877 (point-at-bol) (point-at-eol))
23878 (setq current-prefix-arg nil)
23879 (org-agenda-maybe-redo)))
23881 (defvar speedbar-file-key-map)
23882 (declare-function speedbar-add-supported-extension "speedbar" (extension))
23883 (eval-after-load "speedbar"
23884 '(progn
23885 (speedbar-add-supported-extension ".org")
23886 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23887 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23888 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23889 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23890 (add-hook 'speedbar-visiting-tag-hook
23891 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23893 ;;; Fixes and Hacks for problems with other packages
23895 ;; Make flyspell not check words in links, to not mess up our keymap
23896 (defvar org-element-affiliated-keywords) ; From org-element.el
23897 (defvar org-element-block-name-alist) ; From org-element.el
23898 (defun org-mode-flyspell-verify ()
23899 "Don't let flyspell put overlays at active buttons, or on
23900 {todo,all-time,additional-option-like}-keywords."
23901 (require 'org-element) ; For `org-element-affiliated-keywords'
23902 (let ((pos (max (1- (point)) (point-min)))
23903 (word (thing-at-point 'word)))
23904 (and (not (get-text-property pos 'keymap))
23905 (not (get-text-property pos 'org-no-flyspell))
23906 (not (member word org-todo-keywords-1))
23907 (not (member word org-all-time-keywords))
23908 (not (member word org-options-keywords))
23909 (not (member word (mapcar 'car org-startup-options)))
23910 (not (member-ignore-case word org-element-affiliated-keywords))
23911 (not (member-ignore-case word (org-get-export-keywords)))
23912 (not (member-ignore-case
23913 word (mapcar 'car org-element-block-name-alist)))
23914 (not (member-ignore-case word '("BEGIN" "END" "ATTR")))
23915 (not (org-in-src-block-p)))))
23917 (defun org-remove-flyspell-overlays-in (beg end)
23918 "Remove flyspell overlays in region."
23919 (and (org-bound-and-true-p flyspell-mode)
23920 (fboundp 'flyspell-delete-region-overlays)
23921 (flyspell-delete-region-overlays beg end))
23922 (add-text-properties beg end '(org-no-flyspell t)))
23924 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23925 (eval-after-load "bookmark"
23926 '(if (boundp 'bookmark-after-jump-hook)
23927 ;; We can use the hook
23928 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23929 ;; Hook not available, use advice
23930 (defadvice bookmark-jump (after org-make-visible activate)
23931 "Make the position visible."
23932 (org-bookmark-jump-unhide))))
23934 ;; Make sure saveplace shows the location if it was hidden
23935 (eval-after-load "saveplace"
23936 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23937 "Make the position visible."
23938 (org-bookmark-jump-unhide)))
23940 ;; Make sure ecb shows the location if it was hidden
23941 (eval-after-load "ecb"
23942 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23943 "Make hierarchy visible when jumping into location from ECB tree buffer."
23944 (if (derived-mode-p 'org-mode)
23945 (org-show-context))))
23947 (defun org-bookmark-jump-unhide ()
23948 "Unhide the current position, to show the bookmark location."
23949 (and (derived-mode-p 'org-mode)
23950 (or (outline-invisible-p)
23951 (save-excursion (goto-char (max (point-min) (1- (point))))
23952 (outline-invisible-p)))
23953 (org-show-context 'bookmark-jump)))
23955 ;; Make session.el ignore our circular variable
23956 (defvar session-globals-exclude)
23957 (eval-after-load "session"
23958 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23960 ;;;; Finish up
23962 (provide 'org)
23964 (run-hooks 'org-load-hook)
23966 ;;; org.el ends here