Lazy autoloading of org-id.el to follow links
[org-mode.git] / lisp / org.el
blobaebf58f8c470b038b7869d8424b2686c8c49d169
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2013 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;;; Commentary:
28 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
29 ;; project planning with a fast and effective plain-text system.
31 ;; Org-mode develops organizational tasks around NOTES files that contain
32 ;; information about projects as plain text. Org-mode is implemented on
33 ;; top of outline-mode, which makes it possible to keep the content of
34 ;; large files well structured. Visibility cycling and structure editing
35 ;; help to work with the tree. Tables are easily created with a built-in
36 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
37 ;; and scheduling. It dynamically compiles entries into an agenda that
38 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
39 ;; Plain text URL-like links connect to websites, emails, Usenet
40 ;; messages, BBDB entries, and any files related to the projects. For
41 ;; printing and sharing of notes, an Org-mode file can be exported as a
42 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
43 ;; iCalendar file. It can also serve as a publishing tool for a set of
44 ;; linked webpages.
46 ;; Installation and Activation
47 ;; ---------------------------
48 ;; See the corresponding sections in the manual at
50 ;; http://orgmode.org/org.html#Installation
52 ;; Documentation
53 ;; -------------
54 ;; The documentation of Org-mode can be found in the TeXInfo file. The
55 ;; distribution also contains a PDF version of it. At the homepage of
56 ;; Org-mode, you can read the same text online as HTML. There is also an
57 ;; excellent reference card made by Philip Rooke. This card can be found
58 ;; in the etc/ directory of Emacs 22.
60 ;; A list of recent changes can be found at
61 ;; http://orgmode.org/Changes.html
63 ;;; Code:
65 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
66 (defvar org-table-formula-constants-local nil
67 "Local version of `org-table-formula-constants'.")
68 (make-variable-buffer-local 'org-table-formula-constants-local)
70 ;;;; Require other packages
72 (eval-when-compile
73 (require 'cl)
74 (require 'gnus-sum))
76 (require 'calendar)
77 (require 'find-func)
78 (require 'format-spec)
80 (load "org-loaddefs.el" t t t)
82 (require 'org-macs)
83 (require 'org-compat)
85 ;; `org-outline-regexp' ought to be a defconst but is let-binding 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 (org-babel-tangle-file file exported-file "emacs-lisp"))
202 (message "%s %s"
203 (if compile
204 (progn (byte-compile-file exported-file 'load)
205 "Compiled and loaded")
206 (progn (load-file exported-file) "Loaded"))
207 exported-file)))
209 (defcustom org-babel-load-languages '((emacs-lisp . t))
210 "Languages which can be evaluated in Org-mode buffers.
211 This list can be used to load support for any of the languages
212 below, note that each language will depend on a different set of
213 system executables and/or Emacs modes. When a language is
214 \"loaded\", then code blocks in that language can be evaluated
215 with `org-babel-execute-src-block' bound by default to C-c
216 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
217 be set to remove code block evaluation from the C-c C-c
218 keybinding. By default only Emacs Lisp (which has no
219 requirements) is loaded."
220 :group 'org-babel
221 :set 'org-babel-do-load-languages
222 :version "24.1"
223 :type '(alist :tag "Babel Languages"
224 :key-type
225 (choice
226 (const :tag "Awk" awk)
227 (const :tag "C" C)
228 (const :tag "R" R)
229 (const :tag "Asymptote" asymptote)
230 (const :tag "Calc" calc)
231 (const :tag "Clojure" clojure)
232 (const :tag "CSS" css)
233 (const :tag "Ditaa" ditaa)
234 (const :tag "Dot" dot)
235 (const :tag "Emacs Lisp" emacs-lisp)
236 (const :tag "Fortran" fortran)
237 (const :tag "Gnuplot" gnuplot)
238 (const :tag "Haskell" haskell)
239 (const :tag "IO" io)
240 (const :tag "Java" java)
241 (const :tag "Javascript" js)
242 (const :tag "LaTeX" latex)
243 (const :tag "Ledger" ledger)
244 (const :tag "Lilypond" lilypond)
245 (const :tag "Lisp" lisp)
246 (const :tag "Makefile" makefile)
247 (const :tag "Maxima" maxima)
248 (const :tag "Matlab" matlab)
249 (const :tag "Mscgen" mscgen)
250 (const :tag "Ocaml" ocaml)
251 (const :tag "Octave" octave)
252 (const :tag "Org" org)
253 (const :tag "Perl" perl)
254 (const :tag "Pico Lisp" picolisp)
255 (const :tag "PlantUML" plantuml)
256 (const :tag "Python" python)
257 (const :tag "Ruby" ruby)
258 (const :tag "Sass" sass)
259 (const :tag "Scala" scala)
260 (const :tag "Scheme" scheme)
261 (const :tag "Screen" screen)
262 (const :tag "Shell Script" sh)
263 (const :tag "Shen" shen)
264 (const :tag "Sql" sql)
265 (const :tag "Sqlite" sqlite))
266 :value-type (boolean :tag "Activate" :value t)))
268 ;;;; Customization variables
269 (defcustom org-clone-delete-id nil
270 "Remove ID property of clones of a subtree.
271 When non-nil, clones of a subtree don't inherit the ID property.
272 Otherwise they inherit the ID property with a new unique
273 identifier."
274 :type 'boolean
275 :version "24.1"
276 :group 'org-id)
278 ;;; Version
279 (org-check-version)
281 ;;;###autoload
282 (defun org-version (&optional here full message)
283 "Show the org-mode version in the echo area.
284 With prefix argument HERE, insert it at point.
285 When FULL is non-nil, use a verbose version string.
286 When MESSAGE is non-nil, display a message with the version."
287 (interactive "P")
288 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
289 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
290 (load-suffixes (list ".el"))
291 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
292 (org-trash (or
293 (and (fboundp 'org-release) (fboundp 'org-git-version))
294 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
295 (load-suffixes save-load-suffixes)
296 (org-version (org-release))
297 (git-version (org-git-version))
298 (version (format "Org-mode version %s (%s @ %s)"
299 org-version
300 git-version
301 (if org-install-dir
302 (if (string= org-dir org-install-dir)
303 org-install-dir
304 (concat "mixed installation! " org-install-dir " and " org-dir))
305 "org-loaddefs.el can not be found!")))
306 (_version (if full version org-version)))
307 (if (org-called-interactively-p 'interactive)
308 (if here
309 (insert version)
310 (message version))
311 (if message (message _version))
312 _version)))
314 (defconst org-version (org-version))
316 ;;; Compatibility constants
318 ;;; The custom variables
320 (defgroup org nil
321 "Outline-based notes management and organizer."
322 :tag "Org"
323 :group 'outlines
324 :group 'calendar)
326 (defcustom org-mode-hook nil
327 "Mode hook for Org-mode, run after the mode was turned on."
328 :group 'org
329 :type 'hook)
331 (defcustom org-load-hook nil
332 "Hook that is run after org.el has been loaded."
333 :group 'org
334 :type 'hook)
336 (defcustom org-log-buffer-setup-hook nil
337 "Hook that is run after an Org log buffer is created."
338 :group 'org
339 :version "24.1"
340 :type 'hook)
342 (defvar org-modules) ; defined below
343 (defvar org-modules-loaded nil
344 "Have the modules been loaded already?")
346 (defun org-load-modules-maybe (&optional force)
347 "Load all extensions listed in `org-modules'."
348 (when (or force (not org-modules-loaded))
349 (mapc (lambda (ext)
350 (condition-case nil (require ext)
351 (error (message "Problems while trying to load feature `%s'" ext))))
352 org-modules)
353 (setq org-modules-loaded t)))
355 (defun org-set-modules (var value)
356 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
357 (set var value)
358 (when (featurep 'org)
359 (org-load-modules-maybe 'force)))
361 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
362 "Modules that should always be loaded together with org.el.
364 If a description starts with <C>, the file is not part of Emacs
365 and loading it will require that you have downloaded and properly
366 installed the Org mode distribution.
368 You can also use this system to load external packages (i.e. neither Org
369 core modules, nor modules from the CONTRIB directory). Just add symbols
370 to the end of the list. If the package is called org-xyz.el, then you need
371 to add the symbol `xyz', and the package must have a call to:
373 \(provide 'org-xyz)
375 For export specific modules, see also `org-export-backends'."
376 :group 'org
377 :set 'org-set-modules
378 :version "24.4"
379 :package-version '(Org . "8.0")
380 :type
381 '(set :greedy t
382 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
383 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
384 (const :tag " crypt: Encryption of subtrees" org-crypt)
385 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
386 (const :tag " docview: Links to doc-view buffers" org-docview)
387 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
388 (const :tag " habit: Track your consistency with habits" org-habit)
389 (const :tag " id: Global IDs for identifying entries" org-id)
390 (const :tag " info: Links to Info nodes" org-info)
391 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
392 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
393 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
394 (const :tag " mouse: Additional mouse support" org-mouse)
395 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
396 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
397 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
399 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
400 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
401 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
402 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
403 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
404 (const :tag "C collector: Collect properties into tables" org-collector)
405 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
406 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
407 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
408 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
409 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
410 (const :tag "C eval: Include command output as text" org-eval)
411 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
412 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
413 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
414 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
415 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
416 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
417 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
418 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
419 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
420 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
421 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
422 (const :tag "C mew: Links to Mew folders/messages" org-mew)
423 (const :tag "C mtags: Support for muse-like tags" org-mtags)
424 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
425 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
426 (const :tag "C registry: A registry for Org-mode links" org-registry)
427 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
428 (const :tag "C secretary: Team management with org-mode" org-secretary)
429 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
430 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
431 (const :tag "C track: Keep up with Org-mode development" org-track)
432 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
433 (const :tag "C vm: Links to VM folders/messages" org-vm)
434 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
435 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
436 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
438 (defvar org-export--registered-backends) ; From ox.el.
439 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
440 (declare-function org-export-backend-name "ox" (backend))
441 (defcustom org-export-backends '(ascii html icalendar latex)
442 "List of export back-ends that should be always available.
444 If a description starts with <C>, the file is not part of Emacs
445 and loading it will require that you have downloaded and properly
446 installed the Org mode distribution.
448 Unlike to `org-modules', libraries in this list will not be
449 loaded along with Org, but only once the export framework is
450 needed.
452 This variable needs to be set before org.el is loaded. If you
453 need to make a change while Emacs is running, use the customize
454 interface or run the following code, where VAL stands for the new
455 value of the variable, after updating it:
457 \(progn
458 \(setq org-export--registered-backends
459 \(org-remove-if-not
460 \(lambda (backend)
461 \(let ((name (org-export-backend-name backend)))
462 \(or (memq name val)
463 \(catch 'parentp
464 \(dolist (b val)
465 \(and (org-export-derived-backend-p b name)
466 \(throw 'parentp t)))))))
467 org-export--registered-backends))
468 \(let ((new-list (mapcar 'org-export-backend-name
469 org-export--registered-backends)))
470 \(dolist (backend val)
471 \(cond
472 \((not (load (format \"ox-%s\" backend) t t))
473 \(message \"Problems while trying to load export back-end `%s'\"
474 backend))
475 \((not (memq backend new-list)) (push backend new-list))))
476 \(set-default 'org-export-backends new-list)))
478 Adding a back-end to this list will also pull the back-end it
479 depends on, if any."
480 :group 'org
481 :group 'org-export
482 :version "24.4"
483 :package-version '(Org . "8.0")
484 :initialize 'custom-initialize-set
485 :set (lambda (var val)
486 (if (not (featurep 'ox)) (set-default var val)
487 ;; Any back-end not required anymore (not present in VAL and not
488 ;; a parent of any back-end in the new value) is removed from the
489 ;; list of registered back-ends.
490 (setq org-export--registered-backends
491 (org-remove-if-not
492 (lambda (backend)
493 (let ((name (org-export-backend-name backend)))
494 (or (memq name val)
495 (catch 'parentp
496 (dolist (b val)
497 (and (org-export-derived-backend-p b name)
498 (throw 'parentp t)))))))
499 org-export--registered-backends))
500 ;; Now build NEW-LIST of both new back-ends and required
501 ;; parents.
502 (let ((new-list (mapcar 'org-export-backend-name
503 org-export--registered-backends)))
504 (dolist (backend val)
505 (cond
506 ((not (load (format "ox-%s" backend) t t))
507 (message "Problems while trying to load export back-end `%s'"
508 backend))
509 ((not (memq backend new-list)) (push backend new-list))))
510 ;; Set VAR to that list with fixed dependencies.
511 (set-default var new-list))))
512 :type '(set :greedy t
513 (const :tag " ascii Export buffer to ASCII format" ascii)
514 (const :tag " beamer Export buffer to Beamer presentation" beamer)
515 (const :tag " html Export buffer to HTML format" html)
516 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
517 (const :tag " latex Export buffer to LaTeX format" latex)
518 (const :tag " man Export buffer to MAN format" man)
519 (const :tag " md Export buffer to Markdown format" md)
520 (const :tag " odt Export buffer to ODT format" odt)
521 (const :tag " org Export buffer to Org format" org)
522 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
523 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
524 (const :tag "C deck Export buffer to deck.js presentations" deck)
525 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
526 (const :tag "C groff Export buffer to Groff format" groff)
527 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
528 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
529 (const :tag "C s5 Export buffer to s5 presentations" s5)
530 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
532 (eval-after-load 'ox
533 '(mapc
534 (lambda (backend)
535 (condition-case nil (require (intern (format "ox-%s" backend)))
536 (error (message "Problems while trying to load export back-end `%s'"
537 backend))))
538 org-export-backends))
540 (defcustom org-support-shift-select nil
541 "Non-nil means make shift-cursor commands select text when possible.
543 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
544 start selecting a region, or enlarge regions started in this way.
545 In Org-mode, in special contexts, these same keys are used for
546 other purposes, important enough to compete with shift selection.
547 Org tries to balance these needs by supporting `shift-select-mode'
548 outside these special contexts, under control of this variable.
550 The default of this variable is nil, to avoid confusing behavior. Shifted
551 cursor keys will then execute Org commands in the following contexts:
552 - on a headline, changing TODO state (left/right) and priority (up/down)
553 - on a time stamp, changing the time
554 - in a plain list item, changing the bullet type
555 - in a property definition line, switching between allowed values
556 - in the BEGIN line of a clock table (changing the time block).
557 Outside these contexts, the commands will throw an error.
559 When this variable is t and the cursor is not in a special
560 context, Org-mode will support shift-selection for making and
561 enlarging regions. To make this more effective, the bullet
562 cycling will no longer happen anywhere in an item line, but only
563 if the cursor is exactly on the bullet.
565 If you set this variable to the symbol `always', then the keys
566 will not be special in headlines, property lines, and item lines,
567 to make shift selection work there as well. If this is what you
568 want, you can use the following alternative commands: `C-c C-t'
569 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
570 can be used to switch TODO sets, `C-c -' to cycle item bullet
571 types, and properties can be edited by hand or in column view.
573 However, when the cursor is on a timestamp, shift-cursor commands
574 will still edit the time stamp - this is just too good to give up.
576 XEmacs user should have this variable set to nil, because
577 `shift-select-mode' is in Emacs 23 or later only."
578 :group 'org
579 :type '(choice
580 (const :tag "Never" nil)
581 (const :tag "When outside special context" t)
582 (const :tag "Everywhere except timestamps" always)))
584 (defcustom org-loop-over-headlines-in-active-region nil
585 "Shall some commands act upon headlines in the active region?
587 When set to `t', some commands will be performed in all headlines
588 within the active region.
590 When set to `start-level', some commands will be performed in all
591 headlines within the active region, provided that these headlines
592 are of the same level than the first one.
594 When set to a string, those commands will be performed on the
595 matching headlines within the active region. Such string must be
596 a tags/property/todo match as it is used in the agenda tags view.
598 The list of commands is: `org-schedule', `org-deadline',
599 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
600 `org-archive-to-archive-sibling'. The archiving commands skip
601 already archived entries."
602 :type '(choice (const :tag "Don't loop" nil)
603 (const :tag "All headlines in active region" t)
604 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
605 (string :tag "Tags/Property/Todo matcher"))
606 :version "24.1"
607 :group 'org-todo
608 :group 'org-archive)
610 (defgroup org-startup nil
611 "Options concerning startup of Org-mode."
612 :tag "Org Startup"
613 :group 'org)
615 (defcustom org-startup-folded t
616 "Non-nil means entering Org-mode will switch to OVERVIEW.
617 This can also be configured on a per-file basis by adding one of
618 the following lines anywhere in the buffer:
620 #+STARTUP: fold (or `overview', this is equivalent)
621 #+STARTUP: nofold (or `showall', this is equivalent)
622 #+STARTUP: content
623 #+STARTUP: showeverything
625 By default, this option is ignored when Org opens agenda files
626 for the first time. If you want the agenda to honor the startup
627 option, set `org-agenda-inhibit-startup' to nil."
628 :group 'org-startup
629 :type '(choice
630 (const :tag "nofold: show all" nil)
631 (const :tag "fold: overview" t)
632 (const :tag "content: all headlines" content)
633 (const :tag "show everything, even drawers" showeverything)))
635 (defcustom org-startup-truncated t
636 "Non-nil means entering Org-mode will set `truncate-lines'.
637 This is useful since some lines containing links can be very long and
638 uninteresting. Also tables look terrible when wrapped."
639 :group 'org-startup
640 :type 'boolean)
642 (defcustom org-startup-indented nil
643 "Non-nil means turn on `org-indent-mode' on startup.
644 This can also be configured on a per-file basis by adding one of
645 the following lines anywhere in the buffer:
647 #+STARTUP: indent
648 #+STARTUP: noindent"
649 :group 'org-structure
650 :type '(choice
651 (const :tag "Not" nil)
652 (const :tag "Globally (slow on startup in large files)" t)))
654 (defcustom org-use-sub-superscripts t
655 "Non-nil means interpret \"_\" and \"^\" for display.
656 When this option is turned on, you can use TeX-like syntax for sub- and
657 superscripts. Several characters after \"_\" or \"^\" will be
658 considered as a single item - so grouping with {} is normally not
659 needed. For example, the following things will be parsed as single
660 sub- or superscripts.
662 10^24 or 10^tau several digits will be considered 1 item.
663 10^-12 or 10^-tau a leading sign with digits or a word
664 x^2-y^3 will be read as x^2 - y^3, because items are
665 terminated by almost any nonword/nondigit char.
666 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
668 Still, ambiguity is possible - so when in doubt use {} to enclose
669 the sub/superscript. If you set this variable to the symbol
670 `{}', the braces are *required* in order to trigger
671 interpretations as sub/superscript. This can be helpful in
672 documents that need \"_\" frequently in plain text."
673 :group 'org-startup
674 :version "24.1"
675 :type '(choice
676 (const :tag "Always interpret" t)
677 (const :tag "Only with braces" {})
678 (const :tag "Never interpret" nil)))
680 (defcustom org-startup-with-beamer-mode nil
681 "Non-nil means turn on `org-beamer-mode' on startup.
682 This can also be configured on a per-file basis by adding one of
683 the following lines anywhere in the buffer:
685 #+STARTUP: beamer"
686 :group 'org-startup
687 :version "24.1"
688 :type 'boolean)
690 (defcustom org-startup-align-all-tables nil
691 "Non-nil means align all tables when visiting a file.
692 This is useful when the column width in tables is forced with <N> cookies
693 in table fields. Such tables will look correct only after the first re-align.
694 This can also be configured on a per-file basis by adding one of
695 the following lines anywhere in the buffer:
696 #+STARTUP: align
697 #+STARTUP: noalign"
698 :group 'org-startup
699 :type 'boolean)
701 (defcustom org-startup-with-inline-images nil
702 "Non-nil means show inline images when loading a new Org file.
703 This can also be configured on a per-file basis by adding one of
704 the following lines anywhere in the buffer:
705 #+STARTUP: inlineimages
706 #+STARTUP: noinlineimages"
707 :group 'org-startup
708 :version "24.1"
709 :type 'boolean)
711 (defcustom org-startup-with-latex-preview nil
712 "Non-nil means preview LaTeX fragments when loading a new Org file.
714 This can also be configured on a per-file basis by adding one of
715 the followinglines anywhere in the buffer:
716 #+STARTUP: latexpreview
717 #+STARTUP: nolatexpreview"
718 :group 'org-startup
719 :version "24.4"
720 :package-version '(Org . "8.0")
721 :type 'boolean)
723 (defcustom org-insert-mode-line-in-empty-file nil
724 "Non-nil means insert the first line setting Org-mode in empty files.
725 When the function `org-mode' is called interactively in an empty file, this
726 normally means that the file name does not automatically trigger Org-mode.
727 To ensure that the file will always be in Org-mode in the future, a
728 line enforcing Org-mode will be inserted into the buffer, if this option
729 has been set."
730 :group 'org-startup
731 :type 'boolean)
733 (defcustom org-replace-disputed-keys nil
734 "Non-nil means use alternative key bindings for some keys.
735 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
736 These keys are also used by other packages like shift-selection-mode'
737 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
738 If you want to use Org-mode together with one of these other modes,
739 or more generally if you would like to move some Org-mode commands to
740 other keys, set this variable and configure the keys with the variable
741 `org-disputed-keys'.
743 This option is only relevant at load-time of Org-mode, and must be set
744 *before* org.el is loaded. Changing it requires a restart of Emacs to
745 become effective."
746 :group 'org-startup
747 :type 'boolean)
749 (defcustom org-use-extra-keys nil
750 "Non-nil means use extra key sequence definitions for certain commands.
751 This happens automatically if you run XEmacs or if `window-system'
752 is nil. This variable lets you do the same manually. You must
753 set it before loading org.
755 Example: on Carbon Emacs 22 running graphically, with an external
756 keyboard on a Powerbook, the default way of setting M-left might
757 not work for either Alt or ESC. Setting this variable will make
758 it work for ESC."
759 :group 'org-startup
760 :type 'boolean)
762 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
764 (defcustom org-disputed-keys
765 '(([(shift up)] . [(meta p)])
766 ([(shift down)] . [(meta n)])
767 ([(shift left)] . [(meta -)])
768 ([(shift right)] . [(meta +)])
769 ([(control shift right)] . [(meta shift +)])
770 ([(control shift left)] . [(meta shift -)]))
771 "Keys for which Org-mode and other modes compete.
772 This is an alist, cars are the default keys, second element specifies
773 the alternative to use when `org-replace-disputed-keys' is t.
775 Keys can be specified in any syntax supported by `define-key'.
776 The value of this option takes effect only at Org-mode's startup,
777 therefore you'll have to restart Emacs to apply it after changing."
778 :group 'org-startup
779 :type 'alist)
781 (defun org-key (key)
782 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
783 Or return the original if not disputed.
784 Also apply the translations defined in `org-xemacs-key-equivalents'."
785 (when org-replace-disputed-keys
786 (let* ((nkey (key-description key))
787 (x (org-find-if (lambda (x)
788 (equal (key-description (car x)) nkey))
789 org-disputed-keys)))
790 (setq key (if x (cdr x) key))))
791 (when (featurep 'xemacs)
792 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
793 key)
795 (defun org-find-if (predicate seq)
796 (catch 'exit
797 (while seq
798 (if (funcall predicate (car seq))
799 (throw 'exit (car seq))
800 (pop seq)))))
802 (defun org-defkey (keymap key def)
803 "Define a key, possibly translated, as returned by `org-key'."
804 (define-key keymap (org-key key) def))
806 (defcustom org-ellipsis nil
807 "The ellipsis to use in the Org-mode outline.
808 When nil, just use the standard three dots. When a string, use that instead,
809 When a face, use the standard 3 dots, but with the specified face.
810 The change affects only Org-mode (which will then use its own display table).
811 Changing this requires executing `M-x org-mode' in a buffer to become
812 effective."
813 :group 'org-startup
814 :type '(choice (const :tag "Default" nil)
815 (face :tag "Face" :value org-warning)
816 (string :tag "String" :value "...#")))
818 (defvar org-display-table nil
819 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
821 (defgroup org-keywords nil
822 "Keywords in Org-mode."
823 :tag "Org Keywords"
824 :group 'org)
826 (defcustom org-deadline-string "DEADLINE:"
827 "String to mark deadline entries.
828 A deadline is this string, followed by a time stamp. Should be a word,
829 terminated by a colon. You can insert a schedule keyword and
830 a timestamp with \\[org-deadline].
831 Changes become only effective after restarting Emacs."
832 :group 'org-keywords
833 :type 'string)
835 (defcustom org-scheduled-string "SCHEDULED:"
836 "String to mark scheduled TODO entries.
837 A schedule 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-schedule].
840 Changes become only effective after restarting Emacs."
841 :group 'org-keywords
842 :type 'string)
844 (defcustom org-closed-string "CLOSED:"
845 "String used as the prefix for timestamps logging closing a TODO entry."
846 :group 'org-keywords
847 :type 'string)
849 (defcustom org-clock-string "CLOCK:"
850 "String used as prefix for timestamps clocking work hours on an item."
851 :group 'org-keywords
852 :type 'string)
854 (defcustom org-closed-keep-when-no-todo nil
855 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
856 :group 'org-todo
857 :group 'org-keywords
858 :version "24.4"
859 :package-version '(Org . "8.0")
860 :type 'boolean)
862 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
863 org-scheduled-string "\\|"
864 org-deadline-string "\\|"
865 org-closed-string "\\|"
866 org-clock-string "\\)")
867 "Matches a line with planning or clock info.")
869 (defcustom org-comment-string "COMMENT"
870 "Entries starting with this keyword will never be exported.
871 An entry can be toggled between COMMENT and normal with
872 \\[org-toggle-comment].
873 Changes become only effective after restarting Emacs."
874 :group 'org-keywords
875 :type 'string)
877 (defcustom org-quote-string "QUOTE"
878 "Entries starting with this keyword will be exported in fixed-width font.
879 Quoting applies only to the text in the entry following the headline, and does
880 not extend beyond the next headline, even if that is lower level.
881 An entry can be toggled between QUOTE and normal with
882 \\[org-toggle-fixed-width-section]."
883 :group 'org-keywords
884 :type 'string)
886 (defconst org-repeat-re
887 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
888 "Regular expression for specifying repeated events.
889 After a match, group 1 contains the repeat expression.")
891 (defgroup org-structure nil
892 "Options concerning the general structure of Org-mode files."
893 :tag "Org Structure"
894 :group 'org)
896 (defgroup org-reveal-location nil
897 "Options about how to make context of a location visible."
898 :tag "Org Reveal Location"
899 :group 'org-structure)
901 (defconst org-context-choice
902 '(choice
903 (const :tag "Always" t)
904 (const :tag "Never" nil)
905 (repeat :greedy t :tag "Individual contexts"
906 (cons
907 (choice :tag "Context"
908 (const agenda)
909 (const org-goto)
910 (const occur-tree)
911 (const tags-tree)
912 (const link-search)
913 (const mark-goto)
914 (const bookmark-jump)
915 (const isearch)
916 (const default))
917 (boolean))))
918 "Contexts for the reveal options.")
920 (defcustom org-show-hierarchy-above '((default . t))
921 "Non-nil means show full hierarchy when revealing a location.
922 Org-mode often shows locations in an org-mode file which might have
923 been invisible before. When this is set, the hierarchy of headings
924 above the exposed location is shown.
925 Turning this off for example for sparse trees makes them very compact.
926 Instead of t, this can also be an alist specifying this option for different
927 contexts. Valid contexts are
928 agenda when exposing an entry from the agenda
929 org-goto when using the command `org-goto' on key C-c C-j
930 occur-tree when using the command `org-occur' on key C-c /
931 tags-tree when constructing a sparse tree based on tags matches
932 link-search when exposing search matches associated with a link
933 mark-goto when exposing the jump goal of a mark
934 bookmark-jump when exposing a bookmark location
935 isearch when exiting from an incremental search
936 default default for all contexts not set explicitly"
937 :group 'org-reveal-location
938 :type org-context-choice)
940 (defcustom org-show-following-heading '((default . nil))
941 "Non-nil means show following heading when revealing a location.
942 Org-mode often shows locations in an org-mode file which might have
943 been invisible before. When this is set, the heading following the
944 match is shown.
945 Turning this off for example for sparse trees makes them very compact,
946 but makes it harder to edit the location of the match. In such a case,
947 use the command \\[org-reveal] to show more context.
948 Instead of t, this can also be an alist specifying this option for different
949 contexts. See `org-show-hierarchy-above' for valid contexts."
950 :group 'org-reveal-location
951 :type org-context-choice)
953 (defcustom org-show-siblings '((default . nil) (isearch t) (bookmark-jump t))
954 "Non-nil means show all sibling heading when revealing a location.
955 Org-mode often shows locations in an org-mode file which might have
956 been invisible before. When this is set, the sibling of the current entry
957 heading are all made visible. If `org-show-hierarchy-above' is t,
958 the same happens on each level of the hierarchy above the current entry.
960 By default this is on for the isearch context, off for all other contexts.
961 Turning this off for example for sparse trees makes them very compact,
962 but makes it harder to edit the location of the match. In such a case,
963 use the command \\[org-reveal] to show more context.
964 Instead of t, this can also be an alist specifying this option for different
965 contexts. See `org-show-hierarchy-above' for valid contexts."
966 :group 'org-reveal-location
967 :type org-context-choice
968 :version "24.4"
969 :package-version '(Org . "8.0"))
971 (defcustom org-show-entry-below '((default . nil))
972 "Non-nil means show the entry below a headline when revealing a location.
973 Org-mode often shows locations in an org-mode file which might have
974 been invisible before. When this is set, the text below the headline that is
975 exposed is also shown.
977 By default this is off for all contexts.
978 Instead of t, this can also be an alist specifying this option for different
979 contexts. See `org-show-hierarchy-above' for valid contexts."
980 :group 'org-reveal-location
981 :type org-context-choice)
983 (defcustom org-indirect-buffer-display 'other-window
984 "How should indirect tree buffers be displayed?
985 This applies to indirect buffers created with the commands
986 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
987 Valid values are:
988 current-window Display in the current window
989 other-window Just display in another window.
990 dedicated-frame Create one new frame, and re-use it each time.
991 new-frame Make a new frame each time. Note that in this case
992 previously-made indirect buffers are kept, and you need to
993 kill these buffers yourself."
994 :group 'org-structure
995 :group 'org-agenda-windows
996 :type '(choice
997 (const :tag "In current window" current-window)
998 (const :tag "In current frame, other window" other-window)
999 (const :tag "Each time a new frame" new-frame)
1000 (const :tag "One dedicated frame" dedicated-frame)))
1002 (defcustom org-use-speed-commands nil
1003 "Non-nil means activate single letter commands at beginning of a headline.
1004 This may also be a function to test for appropriate locations where speed
1005 commands should be active."
1006 :group 'org-structure
1007 :type '(choice
1008 (const :tag "Never" nil)
1009 (const :tag "At beginning of headline stars" t)
1010 (function)))
1012 (defcustom org-speed-commands-user nil
1013 "Alist of additional speed commands.
1014 This list will be checked before `org-speed-commands-default'
1015 when the variable `org-use-speed-commands' is non-nil
1016 and when the cursor is at the beginning of a headline.
1017 The car if each entry is a string with a single letter, which must
1018 be assigned to `self-insert-command' in the global map.
1019 The cdr is either a command to be called interactively, a function
1020 to be called, or a form to be evaluated.
1021 An entry that is just a list with a single string will be interpreted
1022 as a descriptive headline that will be added when listing the speed
1023 commands in the Help buffer using the `?' speed command."
1024 :group 'org-structure
1025 :type '(repeat :value ("k" . ignore)
1026 (choice :value ("k" . ignore)
1027 (list :tag "Descriptive Headline" (string :tag "Headline"))
1028 (cons :tag "Letter and Command"
1029 (string :tag "Command letter")
1030 (choice
1031 (function)
1032 (sexp))))))
1034 (defcustom org-bookmark-names-plist
1035 '(:last-capture "org-capture-last-stored"
1036 :last-refile "org-refile-last-stored"
1037 :last-capture-marker "org-capture-last-stored-marker")
1038 "Names for bookmarks automatically set by some Org commands.
1039 This can provide strings as names for a number of bookmakrs Org sets
1040 automatically. The following keys are currently implemented:
1041 :last-capture
1042 :last-capture-marker
1043 :last-refile
1044 When a key does not show up in the property list, the corresponding bookmark
1045 is not set."
1046 :group 'org-structure
1047 :type 'plist)
1049 (defgroup org-cycle nil
1050 "Options concerning visibility cycling in Org-mode."
1051 :tag "Org Cycle"
1052 :group 'org-structure)
1054 (defcustom org-cycle-skip-children-state-if-no-children t
1055 "Non-nil means skip CHILDREN state in entries that don't have any."
1056 :group 'org-cycle
1057 :type 'boolean)
1059 (defcustom org-cycle-max-level nil
1060 "Maximum level which should still be subject to visibility cycling.
1061 Levels higher than this will, for cycling, be treated as text, not a headline.
1062 When `org-odd-levels-only' is set, a value of N in this variable actually
1063 means 2N-1 stars as the limiting headline.
1064 When nil, cycle all levels.
1065 Note that the limiting level of cycling is also influenced by
1066 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1067 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1068 than its value."
1069 :group 'org-cycle
1070 :type '(choice
1071 (const :tag "No limit" nil)
1072 (integer :tag "Maximum level")))
1074 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
1075 "Names of drawers. Drawers are not opened by cycling on the headline above.
1076 Drawers only open with a TAB on the drawer line itself. A drawer looks like
1077 this:
1078 :DRAWERNAME:
1079 .....
1080 :END:
1081 The drawer \"PROPERTIES\" is special for capturing properties through
1082 the property API.
1084 Drawers can be defined on the per-file basis with a line like:
1086 #+DRAWERS: HIDDEN STATE PROPERTIES"
1087 :group 'org-structure
1088 :group 'org-cycle
1089 :type '(repeat (string :tag "Drawer Name")))
1091 (defcustom org-hide-block-startup nil
1092 "Non-nil means entering Org-mode will fold all blocks.
1093 This can also be set in on a per-file basis with
1095 #+STARTUP: hideblocks
1096 #+STARTUP: showblocks"
1097 :group 'org-startup
1098 :group 'org-cycle
1099 :type 'boolean)
1101 (defcustom org-cycle-global-at-bob nil
1102 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1103 This makes it possible to do global cycling without having to use S-TAB or
1104 \\[universal-argument] TAB. For this special case to work, the first line
1105 of the buffer must not be a headline -- it may be empty or some other text.
1106 When used in this way, `org-cycle-hook' is disabled temporarily to make
1107 sure the cursor stays at the beginning of the buffer. When this option is
1108 nil, don't do anything special at the beginning of the buffer."
1109 :group 'org-cycle
1110 :type 'boolean)
1112 (defcustom org-cycle-level-after-item/entry-creation t
1113 "Non-nil means cycle entry level or item indentation in new empty entries.
1115 When the cursor is at the end of an empty headline, i.e., with only stars
1116 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1117 and then all possible ancestor states, before returning to the original state.
1118 This makes data entry extremely fast: M-RET to create a new headline,
1119 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1121 When the cursor is at the end of an empty plain list item, one TAB will
1122 make it a subitem, two or more tabs will back up to make this an item
1123 higher up in the item hierarchy."
1124 :group 'org-cycle
1125 :type 'boolean)
1127 (defcustom org-cycle-emulate-tab t
1128 "Where should `org-cycle' emulate TAB.
1129 nil Never
1130 white Only in completely white lines
1131 whitestart Only at the beginning of lines, before the first non-white char
1132 t Everywhere except in headlines
1133 exc-hl-bol Everywhere except at the start of a headline
1134 If TAB is used in a place where it does not emulate TAB, the current subtree
1135 visibility is cycled."
1136 :group 'org-cycle
1137 :type '(choice (const :tag "Never" nil)
1138 (const :tag "Only in completely white lines" white)
1139 (const :tag "Before first char in a line" whitestart)
1140 (const :tag "Everywhere except in headlines" t)
1141 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1143 (defcustom org-cycle-separator-lines 2
1144 "Number of empty lines needed to keep an empty line between collapsed trees.
1145 If you leave an empty line between the end of a subtree and the following
1146 headline, this empty line is hidden when the subtree is folded.
1147 Org-mode will leave (exactly) one empty line visible if the number of
1148 empty lines is equal or larger to the number given in this variable.
1149 So the default 2 means at least 2 empty lines after the end of a subtree
1150 are needed to produce free space between a collapsed subtree and the
1151 following headline.
1153 If the number is negative, and the number of empty lines is at least -N,
1154 all empty lines are shown.
1156 Special case: when 0, never leave empty lines in collapsed view."
1157 :group 'org-cycle
1158 :type 'integer)
1159 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1161 (defcustom org-pre-cycle-hook nil
1162 "Hook that is run before visibility cycling is happening.
1163 The function(s) in this hook must accept a single argument which indicates
1164 the new state that will be set right after running this hook. The
1165 argument is a symbol. Before a global state change, it can have the values
1166 `overview', `content', or `all'. Before a local state change, it can have
1167 the values `folded', `children', or `subtree'."
1168 :group 'org-cycle
1169 :type 'hook)
1171 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1172 org-cycle-hide-drawers
1173 org-cycle-hide-inline-tasks
1174 org-cycle-show-empty-lines
1175 org-optimize-window-after-visibility-change)
1176 "Hook that is run after `org-cycle' has changed the buffer visibility.
1177 The function(s) in this hook must accept a single argument which indicates
1178 the new state that was set by the most recent `org-cycle' command. The
1179 argument is a symbol. After a global state change, it can have the values
1180 `overview', `contents', or `all'. After a local state change, it can have
1181 the values `folded', `children', or `subtree'."
1182 :group 'org-cycle
1183 :type 'hook)
1185 (defgroup org-edit-structure nil
1186 "Options concerning structure editing in Org-mode."
1187 :tag "Org Edit Structure"
1188 :group 'org-structure)
1190 (defcustom org-odd-levels-only nil
1191 "Non-nil means skip even levels and only use odd levels for the outline.
1192 This has the effect that two stars are being added/taken away in
1193 promotion/demotion commands. It also influences how levels are
1194 handled by the exporters.
1195 Changing it requires restart of `font-lock-mode' to become effective
1196 for fontification also in regions already fontified.
1197 You may also set this on a per-file basis by adding one of the following
1198 lines to the buffer:
1200 #+STARTUP: odd
1201 #+STARTUP: oddeven"
1202 :group 'org-edit-structure
1203 :group 'org-appearance
1204 :type 'boolean)
1206 (defcustom org-adapt-indentation t
1207 "Non-nil means adapt indentation to outline node level.
1209 When this variable is set, Org assumes that you write outlines by
1210 indenting text in each node to align with the headline (after the stars).
1211 The following issues are influenced by this variable:
1213 - When this is set and the *entire* text in an entry is indented, the
1214 indentation is increased by one space in a demotion command, and
1215 decreased by one in a promotion command. If any line in the entry
1216 body starts with text at column 0, indentation is not changed at all.
1218 - Property drawers and planning information is inserted indented when
1219 this variable s set. When nil, they will not be indented.
1221 - TAB indents a line relative to context. The lines below a headline
1222 will be indented when this variable is set.
1224 Note that this is all about true indentation, by adding and removing
1225 space characters. See also `org-indent.el' which does level-dependent
1226 indentation in a virtual way, i.e. at display time in Emacs."
1227 :group 'org-edit-structure
1228 :type 'boolean)
1230 (defcustom org-special-ctrl-a/e nil
1231 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1233 When t, `C-a' will bring back the cursor to the beginning of the
1234 headline text, i.e. after the stars and after a possible TODO
1235 keyword. In an item, this will be the position after bullet and
1236 check-box, if any. When the cursor is already at that position,
1237 another `C-a' will bring it to the beginning of the line.
1239 `C-e' will jump to the end of the headline, ignoring the presence
1240 of tags in the headline. A second `C-e' will then jump to the
1241 true end of the line, after any tags. This also means that, when
1242 this variable is non-nil, `C-e' also will never jump beyond the
1243 end of the heading of a folded section, i.e. not after the
1244 ellipses.
1246 When set to the symbol `reversed', the first `C-a' or `C-e' works
1247 normally, going to the true line boundary first. Only a directly
1248 following, identical keypress will bring the cursor to the
1249 special positions.
1251 This may also be a cons cell where the behavior for `C-a' and
1252 `C-e' is set separately."
1253 :group 'org-edit-structure
1254 :type '(choice
1255 (const :tag "off" nil)
1256 (const :tag "on: after stars/bullet and before tags first" t)
1257 (const :tag "reversed: true line boundary first" reversed)
1258 (cons :tag "Set C-a and C-e separately"
1259 (choice :tag "Special C-a"
1260 (const :tag "off" nil)
1261 (const :tag "on: after stars/bullet first" t)
1262 (const :tag "reversed: before stars/bullet first" reversed))
1263 (choice :tag "Special C-e"
1264 (const :tag "off" nil)
1265 (const :tag "on: before tags first" t)
1266 (const :tag "reversed: after tags first" reversed)))))
1267 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1269 (defcustom org-special-ctrl-k nil
1270 "Non-nil means `C-k' will behave specially in headlines.
1271 When nil, `C-k' will call the default `kill-line' command.
1272 When t, the following will happen while the cursor is in the headline:
1274 - When the cursor is at the beginning of a headline, kill the entire
1275 line and possible the folded subtree below the line.
1276 - When in the middle of the headline text, kill the headline up to the tags.
1277 - When after the headline text, kill the tags."
1278 :group 'org-edit-structure
1279 :type 'boolean)
1281 (defcustom org-ctrl-k-protect-subtree nil
1282 "Non-nil means, do not delete a hidden subtree with C-k.
1283 When set to the symbol `error', simply throw an error when C-k is
1284 used to kill (part-of) a headline that has hidden text behind it.
1285 Any other non-nil value will result in a query to the user, if it is
1286 OK to kill that hidden subtree. When nil, kill without remorse."
1287 :group 'org-edit-structure
1288 :version "24.1"
1289 :type '(choice
1290 (const :tag "Do not protect hidden subtrees" nil)
1291 (const :tag "Protect hidden subtrees with a security query" t)
1292 (const :tag "Never kill a hidden subtree with C-k" error)))
1294 (defcustom org-catch-invisible-edits nil
1295 "Check if in invisible region before inserting or deleting a character.
1296 Valid values are:
1298 nil Do not check, so just do invisible edits.
1299 error Throw an error and do nothing.
1300 show Make point visible, and do the requested edit.
1301 show-and-error Make point visible, then throw an error and abort the edit.
1302 smart Make point visible, and do insertion/deletion if it is
1303 adjacent to visible text and the change feels predictable.
1304 Never delete a previously invisible character or add in the
1305 middle or right after an invisible region. Basically, this
1306 allows insertion and backward-delete right before ellipses.
1307 FIXME: maybe in this case we should not even show?"
1308 :group 'org-edit-structure
1309 :version "24.1"
1310 :type '(choice
1311 (const :tag "Do not check" nil)
1312 (const :tag "Throw error when trying to edit" error)
1313 (const :tag "Unhide, but do not do the edit" show-and-error)
1314 (const :tag "Show invisible part and do the edit" show)
1315 (const :tag "Be smart and do the right thing" smart)))
1317 (defcustom org-yank-folded-subtrees t
1318 "Non-nil means when yanking subtrees, fold them.
1319 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1320 it starts with a heading and all other headings in it are either children
1321 or siblings, then fold all the subtrees. However, do this only if no
1322 text after the yank would be swallowed into a folded tree by this action."
1323 :group 'org-edit-structure
1324 :type 'boolean)
1326 (defcustom org-yank-adjusted-subtrees nil
1327 "Non-nil means when yanking subtrees, adjust the level.
1328 With this setting, `org-paste-subtree' is used to insert the subtree, see
1329 this function for details."
1330 :group 'org-edit-structure
1331 :type 'boolean)
1333 (defcustom org-M-RET-may-split-line '((default . t))
1334 "Non-nil means M-RET will split the line at the cursor position.
1335 When nil, it will go to the end of the line before making a
1336 new line.
1337 You may also set this option in a different way for different
1338 contexts. Valid contexts are:
1340 headline when creating a new headline
1341 item when creating a new item
1342 table in a table field
1343 default the value to be used for all contexts not explicitly
1344 customized"
1345 :group 'org-structure
1346 :group 'org-table
1347 :type '(choice
1348 (const :tag "Always" t)
1349 (const :tag "Never" nil)
1350 (repeat :greedy t :tag "Individual contexts"
1351 (cons
1352 (choice :tag "Context"
1353 (const headline)
1354 (const item)
1355 (const table)
1356 (const default))
1357 (boolean)))))
1360 (defcustom org-insert-heading-respect-content nil
1361 "Non-nil means insert new headings after the current subtree.
1362 When nil, the new heading is created directly after the current line.
1363 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1364 this variable on for the duration of the command."
1365 :group 'org-structure
1366 :type 'boolean)
1368 (defcustom org-blank-before-new-entry '((heading . auto)
1369 (plain-list-item . auto))
1370 "Should `org-insert-heading' leave a blank line before new heading/item?
1371 The value is an alist, with `heading' and `plain-list-item' as CAR,
1372 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1373 which case Org will look at the surrounding headings/items and try to
1374 make an intelligent decision whether to insert a blank line or not.
1376 For plain lists, if `org-list-empty-line-terminates-plain-lists' is set,
1377 the setting here is ignored and no empty line is inserted to avoid breaking
1378 the list structure."
1379 :group 'org-edit-structure
1380 :type '(list
1381 (cons (const heading)
1382 (choice (const :tag "Never" nil)
1383 (const :tag "Always" t)
1384 (const :tag "Auto" auto)))
1385 (cons (const plain-list-item)
1386 (choice (const :tag "Never" nil)
1387 (const :tag "Always" t)
1388 (const :tag "Auto" auto)))))
1390 (defcustom org-insert-heading-hook nil
1391 "Hook being run after inserting a new heading."
1392 :group 'org-edit-structure
1393 :type 'hook)
1395 (defcustom org-enable-fixed-width-editor t
1396 "Non-nil means lines starting with \":\" are treated as fixed-width.
1397 This currently only means they are never auto-wrapped.
1398 When nil, such lines will be treated like ordinary lines.
1399 See also the QUOTE keyword."
1400 :group 'org-edit-structure
1401 :type 'boolean)
1403 (defcustom org-goto-auto-isearch t
1404 "Non-nil means typing characters in `org-goto' starts incremental search.
1405 When nil, you can use these keybindings to navigate the buffer:
1407 q Quit the org-goto interface
1408 n Go to the next visible heading
1409 p Go to the previous visible heading
1410 f Go one heading forward on same level
1411 b Go one heading backward on same level
1412 u Go one heading up"
1413 :group 'org-edit-structure
1414 :type 'boolean)
1416 (defgroup org-sparse-trees nil
1417 "Options concerning sparse trees in Org-mode."
1418 :tag "Org Sparse Trees"
1419 :group 'org-structure)
1421 (defcustom org-highlight-sparse-tree-matches t
1422 "Non-nil means highlight all matches that define a sparse tree.
1423 The highlights will automatically disappear the next time the buffer is
1424 changed by an edit command."
1425 :group 'org-sparse-trees
1426 :type 'boolean)
1428 (defcustom org-remove-highlights-with-change t
1429 "Non-nil means any change to the buffer will remove temporary highlights.
1430 Such highlights are created by `org-occur' and `org-clock-display'.
1431 When nil, `C-c C-c needs to be used to get rid of the highlights.
1432 The highlights created by `org-preview-latex-fragment' always need
1433 `C-c C-c' to be removed."
1434 :group 'org-sparse-trees
1435 :group 'org-time
1436 :type 'boolean)
1439 (defcustom org-occur-hook '(org-first-headline-recenter)
1440 "Hook that is run after `org-occur' has constructed a sparse tree.
1441 This can be used to recenter the window to show as much of the structure
1442 as possible."
1443 :group 'org-sparse-trees
1444 :type 'hook)
1446 (defgroup org-imenu-and-speedbar nil
1447 "Options concerning imenu and speedbar in Org-mode."
1448 :tag "Org Imenu and Speedbar"
1449 :group 'org-structure)
1451 (defcustom org-imenu-depth 2
1452 "The maximum level for Imenu access to Org-mode headlines.
1453 This also applied for speedbar access."
1454 :group 'org-imenu-and-speedbar
1455 :type 'integer)
1457 (defgroup org-table nil
1458 "Options concerning tables in Org-mode."
1459 :tag "Org Table"
1460 :group 'org)
1462 (defcustom org-enable-table-editor 'optimized
1463 "Non-nil means lines starting with \"|\" are handled by the table editor.
1464 When nil, such lines will be treated like ordinary lines.
1466 When equal to the symbol `optimized', the table editor will be optimized to
1467 do the following:
1468 - Automatic overwrite mode in front of whitespace in table fields.
1469 This makes the structure of the table stay in tact as long as the edited
1470 field does not exceed the column width.
1471 - Minimize the number of realigns. Normally, the table is aligned each time
1472 TAB or RET are pressed to move to another field. With optimization this
1473 happens only if changes to a field might have changed the column width.
1474 Optimization requires replacing the functions `self-insert-command',
1475 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1476 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1477 very good at guessing when a re-align will be necessary, but you can always
1478 force one with \\[org-ctrl-c-ctrl-c].
1480 If you would like to use the optimized version in Org-mode, but the
1481 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1483 This variable can be used to turn on and off the table editor during a session,
1484 but in order to toggle optimization, a restart is required.
1486 See also the variable `org-table-auto-blank-field'."
1487 :group 'org-table
1488 :type '(choice
1489 (const :tag "off" nil)
1490 (const :tag "on" t)
1491 (const :tag "on, optimized" optimized)))
1493 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1494 (version<= emacs-version "24.1"))
1495 "Non-nil means cluster self-insert commands for undo when possible.
1496 If this is set, then, like in the Emacs command loop, 20 consecutive
1497 characters will be undone together.
1498 This is configurable, because there is some impact on typing performance."
1499 :group 'org-table
1500 :type 'boolean)
1502 (defcustom org-table-tab-recognizes-table.el t
1503 "Non-nil means TAB will automatically notice a table.el table.
1504 When it sees such a table, it moves point into it and - if necessary -
1505 calls `table-recognize-table'."
1506 :group 'org-table-editing
1507 :type 'boolean)
1509 (defgroup org-link nil
1510 "Options concerning links in Org-mode."
1511 :tag "Org Link"
1512 :group 'org)
1514 (defvar org-link-abbrev-alist-local nil
1515 "Buffer-local version of `org-link-abbrev-alist', which see.
1516 The value of this is taken from the #+LINK lines.")
1517 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1519 (defcustom org-link-abbrev-alist nil
1520 "Alist of link abbreviations.
1521 The car of each element is a string, to be replaced at the start of a link.
1522 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1523 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1525 [[linkkey:tag][description]]
1527 The 'linkkey' must be a word word, starting with a letter, followed
1528 by letters, numbers, '-' or '_'.
1530 If REPLACE is a string, the tag will simply be appended to create the link.
1531 If the string contains \"%s\", the tag will be inserted there. If the string
1532 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1533 at that point (see the function `url-hexify-string'). If the string contains
1534 the specifier \"%(my-function)\", then the custom function `my-function' will
1535 be invoked: this function takes the tag as its only argument and must return
1536 a string.
1538 REPLACE may also be a function that will be called with the tag as the
1539 only argument to create the link, which should be returned as a string.
1541 See the manual for examples."
1542 :group 'org-link
1543 :type '(repeat
1544 (cons
1545 (string :tag "Protocol")
1546 (choice
1547 (string :tag "Format")
1548 (function)))))
1550 (defcustom org-descriptive-links t
1551 "Non-nil means Org will display descriptive links.
1552 E.g. [[http://orgmode.org][Org website]] will be displayed as
1553 \"Org Website\", hiding the link itself and just displaying its
1554 description. When set to `nil', Org will display the full links
1555 literally.
1557 You can interactively set the value of this variable by calling
1558 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1559 :group 'org-link
1560 :type 'boolean)
1562 (defcustom org-link-file-path-type 'adaptive
1563 "How the path name in file links should be stored.
1564 Valid values are:
1566 relative Relative to the current directory, i.e. the directory of the file
1567 into which the link is being inserted.
1568 absolute Absolute path, if possible with ~ for home directory.
1569 noabbrev Absolute path, no abbreviation of home directory.
1570 adaptive Use relative path for files in the current directory and sub-
1571 directories of it. For other files, use an absolute path."
1572 :group 'org-link
1573 :type '(choice
1574 (const relative)
1575 (const absolute)
1576 (const noabbrev)
1577 (const adaptive)))
1579 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1580 "Types of links that should be activated in Org-mode files.
1581 This is a list of symbols, each leading to the activation of a certain link
1582 type. In principle, it does not hurt to turn on most link types - there may
1583 be a small gain when turning off unused link types. The types are:
1585 bracket The recommended [[link][description]] or [[link]] links with hiding.
1586 angle Links in angular brackets that may contain whitespace like
1587 <bbdb:Carsten Dominik>.
1588 plain Plain links in normal text, no whitespace, like http://google.com.
1589 radio Text that is matched by a radio target, see manual for details.
1590 tag Tag settings in a headline (link to tag search).
1591 date Time stamps (link to calendar).
1592 footnote Footnote labels.
1594 Changing this variable requires a restart of Emacs to become effective."
1595 :group 'org-link
1596 :type '(set :greedy t
1597 (const :tag "Double bracket links" bracket)
1598 (const :tag "Angular bracket links" angle)
1599 (const :tag "Plain text links" plain)
1600 (const :tag "Radio target matches" radio)
1601 (const :tag "Tags" tag)
1602 (const :tag "Timestamps" date)
1603 (const :tag "Footnotes" footnote)))
1605 (defcustom org-make-link-description-function nil
1606 "Function to use for generating link descriptions from links.
1607 When nil, the link location will be used. This function must take
1608 two parameters: the first one is the link, the second one is the
1609 description generated by `org-insert-link'. The function should
1610 return the description to use."
1611 :group 'org-link
1612 :type '(choice (const nil) (function)))
1614 (defgroup org-link-store nil
1615 "Options concerning storing links in Org-mode."
1616 :tag "Org Store Link"
1617 :group 'org-link)
1619 (defcustom org-url-hexify-p t
1620 "When non-nil, hexify URL when creating a link."
1621 :type 'boolean
1622 :version "24.3"
1623 :group 'org-link-store)
1625 (defcustom org-email-link-description-format "Email %c: %.30s"
1626 "Format of the description part of a link to an email or usenet message.
1627 The following %-escapes will be replaced by corresponding information:
1629 %F full \"From\" field
1630 %f name, taken from \"From\" field, address if no name
1631 %T full \"To\" field
1632 %t first name in \"To\" field, address if no name
1633 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1634 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1635 %s subject
1636 %d date
1637 %m message-id.
1639 You may use normal field width specification between the % and the letter.
1640 This is for example useful to limit the length of the subject.
1642 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1643 :group 'org-link-store
1644 :type 'string)
1646 (defcustom org-from-is-user-regexp
1647 (let (r1 r2)
1648 (when (and user-mail-address (not (string= user-mail-address "")))
1649 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1650 (when (and user-full-name (not (string= user-full-name "")))
1651 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1652 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1653 "Regexp matched against the \"From:\" header of an email or usenet message.
1654 It should match if the message is from the user him/herself."
1655 :group 'org-link-store
1656 :type 'regexp)
1658 (defcustom org-context-in-file-links t
1659 "Non-nil means file links from `org-store-link' contain context.
1660 A search string will be added to the file name with :: as separator and
1661 used to find the context when the link is activated by the command
1662 `org-open-at-point'. When this option is t, the entire active region
1663 will be placed in the search string of the file link. If set to a
1664 positive integer, only the first n lines of context will be stored.
1666 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1667 negates this setting for the duration of the command."
1668 :group 'org-link-store
1669 :type '(choice boolean integer))
1671 (defcustom org-keep-stored-link-after-insertion nil
1672 "Non-nil means keep link in list for entire session.
1674 The command `org-store-link' adds a link pointing to the current
1675 location to an internal list. These links accumulate during a session.
1676 The command `org-insert-link' can be used to insert links into any
1677 Org-mode file (offering completion for all stored links). When this
1678 option is nil, every link which has been inserted once using \\[org-insert-link]
1679 will be removed from the list, to make completing the unused links
1680 more efficient."
1681 :group 'org-link-store
1682 :type 'boolean)
1684 (defgroup org-link-follow nil
1685 "Options concerning following links in Org-mode."
1686 :tag "Org Follow Link"
1687 :group 'org-link)
1689 (defcustom org-link-translation-function nil
1690 "Function to translate links with different syntax to Org syntax.
1691 This can be used to translate links created for example by the Planner
1692 or emacs-wiki packages to Org syntax.
1693 The function must accept two parameters, a TYPE containing the link
1694 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1695 which is everything after the link protocol. It should return a cons
1696 with possibly modified values of type and path.
1697 Org contains a function for this, so if you set this variable to
1698 `org-translate-link-from-planner', you should be able follow many
1699 links created by planner."
1700 :group 'org-link-follow
1701 :type '(choice (const nil) (function)))
1703 (defcustom org-follow-link-hook nil
1704 "Hook that is run after a link has been followed."
1705 :group 'org-link-follow
1706 :type 'hook)
1708 (defcustom org-tab-follows-link nil
1709 "Non-nil means on links TAB will follow the link.
1710 Needs to be set before org.el is loaded.
1711 This really should not be used, it does not make sense, and the
1712 implementation is bad."
1713 :group 'org-link-follow
1714 :type 'boolean)
1716 (defcustom org-return-follows-link nil
1717 "Non-nil means on links RET will follow the link.
1718 In tables, the special behavior of RET has precedence."
1719 :group 'org-link-follow
1720 :type 'boolean)
1722 (defcustom org-mouse-1-follows-link
1723 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1724 "Non-nil means mouse-1 on a link will follow the link.
1725 A longer mouse click will still set point. Does not work on XEmacs.
1726 Needs to be set before org.el is loaded."
1727 :group 'org-link-follow
1728 :type 'boolean)
1730 (defcustom org-mark-ring-length 4
1731 "Number of different positions to be recorded in the ring.
1732 Changing this requires a restart of Emacs to work correctly."
1733 :group 'org-link-follow
1734 :type 'integer)
1736 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1737 "Non-nil means internal links in Org files must exactly match a headline.
1738 When nil, the link search tries to match a phrase with all words
1739 in the search text."
1740 :group 'org-link-follow
1741 :version "24.1"
1742 :type '(choice
1743 (const :tag "Use fuzzy text search" nil)
1744 (const :tag "Match only exact headline" t)
1745 (const :tag "Match exact headline or query to create it"
1746 query-to-create)))
1748 (defcustom org-link-frame-setup
1749 '((vm . vm-visit-folder-other-frame)
1750 (vm-imap . vm-visit-imap-folder-other-frame)
1751 (gnus . org-gnus-no-new-news)
1752 (file . find-file-other-window)
1753 (wl . wl-other-frame))
1754 "Setup the frame configuration for following links.
1755 When following a link with Emacs, it may often be useful to display
1756 this link in another window or frame. This variable can be used to
1757 set this up for the different types of links.
1758 For VM, use any of
1759 `vm-visit-folder'
1760 `vm-visit-folder-other-window'
1761 `vm-visit-folder-other-frame'
1762 For Gnus, use any of
1763 `gnus'
1764 `gnus-other-frame'
1765 `org-gnus-no-new-news'
1766 For FILE, use any of
1767 `find-file'
1768 `find-file-other-window'
1769 `find-file-other-frame'
1770 For Wanderlust use any of
1771 `wl'
1772 `wl-other-frame'
1773 For the calendar, use the variable `calendar-setup'.
1774 For BBDB, it is currently only possible to display the matches in
1775 another window."
1776 :group 'org-link-follow
1777 :type '(list
1778 (cons (const vm)
1779 (choice
1780 (const vm-visit-folder)
1781 (const vm-visit-folder-other-window)
1782 (const vm-visit-folder-other-frame)))
1783 (cons (const vm-imap)
1784 (choice
1785 (const vm-visit-imap-folder)
1786 (const vm-visit-imap-folder-other-window)
1787 (const vm-visit-imap-folder-other-frame)))
1788 (cons (const gnus)
1789 (choice
1790 (const gnus)
1791 (const gnus-other-frame)
1792 (const org-gnus-no-new-news)))
1793 (cons (const file)
1794 (choice
1795 (const find-file)
1796 (const find-file-other-window)
1797 (const find-file-other-frame)))
1798 (cons (const wl)
1799 (choice
1800 (const wl)
1801 (const wl-other-frame)))))
1803 (defcustom org-display-internal-link-with-indirect-buffer nil
1804 "Non-nil means use indirect buffer to display infile links.
1805 Activating internal links (from one location in a file to another location
1806 in the same file) normally just jumps to the location. When the link is
1807 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1808 is displayed in
1809 another window. When this option is set, the other window actually displays
1810 an indirect buffer clone of the current buffer, to avoid any visibility
1811 changes to the current buffer."
1812 :group 'org-link-follow
1813 :type 'boolean)
1815 (defcustom org-open-non-existing-files nil
1816 "Non-nil means `org-open-file' will open non-existing files.
1817 When nil, an error will be generated.
1818 This variable applies only to external applications because they
1819 might choke on non-existing files. If the link is to a file that
1820 will be opened in Emacs, the variable is ignored."
1821 :group 'org-link-follow
1822 :type 'boolean)
1824 (defcustom org-open-directory-means-index-dot-org nil
1825 "Non-nil means a link to a directory really means to index.org.
1826 When nil, following a directory link will run dired or open a finder/explorer
1827 window on that directory."
1828 :group 'org-link-follow
1829 :type 'boolean)
1831 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1832 "Function and arguments to call for following mailto links.
1833 This is a list with the first element being a Lisp function, and the
1834 remaining elements being arguments to the function. In string arguments,
1835 %a will be replaced by the address, and %s will be replaced by the subject
1836 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1837 :group 'org-link-follow
1838 :type '(choice
1839 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1840 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1841 (const :tag "message-mail" (message-mail "%a" "%s"))
1842 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1844 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1845 "Non-nil means ask for confirmation before executing shell links.
1846 Shell links can be dangerous: just think about a link
1848 [[shell:rm -rf ~/*][Google Search]]
1850 This link would show up in your Org-mode document as \"Google Search\",
1851 but really it would remove your entire home directory.
1852 Therefore we advise against setting this variable to nil.
1853 Just change it to `y-or-n-p' if you want to confirm with a
1854 single keystroke rather than having to type \"yes\"."
1855 :group 'org-link-follow
1856 :type '(choice
1857 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1858 (const :tag "with y-or-n (faster)" y-or-n-p)
1859 (const :tag "no confirmation (dangerous)" nil)))
1860 (put 'org-confirm-shell-link-function
1861 'safe-local-variable
1862 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1864 (defcustom org-confirm-shell-link-not-regexp ""
1865 "A regexp to skip confirmation for shell links."
1866 :group 'org-link-follow
1867 :version "24.1"
1868 :type 'regexp)
1870 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1871 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1872 Elisp links can be dangerous: just think about a link
1874 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1876 This link would show up in your Org-mode document as \"Google Search\",
1877 but really it would remove your entire home directory.
1878 Therefore we advise against setting this variable to nil.
1879 Just change it to `y-or-n-p' if you want to confirm with a
1880 single keystroke rather than having to type \"yes\"."
1881 :group 'org-link-follow
1882 :type '(choice
1883 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1884 (const :tag "with y-or-n (faster)" y-or-n-p)
1885 (const :tag "no confirmation (dangerous)" nil)))
1886 (put 'org-confirm-shell-link-function
1887 'safe-local-variable
1888 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1890 (defcustom org-confirm-elisp-link-not-regexp ""
1891 "A regexp to skip confirmation for Elisp links."
1892 :group 'org-link-follow
1893 :version "24.1"
1894 :type 'regexp)
1896 (defconst org-file-apps-defaults-gnu
1897 (append
1898 '((remote . emacs))
1899 (if (executable-find "xdg-open")
1900 '((system . "xdg-open %s")
1901 (t . "xdg-open %s"))
1902 '((system . mailcap)
1903 (t . mailcap))))
1904 "Default file applications on a UNIX or GNU/Linux system.
1905 See `org-file-apps'.")
1907 (defconst org-file-apps-defaults-macosx
1908 '((remote . emacs)
1909 (t . "open %s")
1910 (system . "open %s")
1911 ("ps.gz" . "gv %s")
1912 ("eps.gz" . "gv %s")
1913 ("dvi" . "xdvi %s")
1914 ("fig" . "xfig %s"))
1915 "Default file applications on a MacOS X system.
1916 The system \"open\" is known as a default, but we use X11 applications
1917 for some files for which the OS does not have a good default.
1918 See `org-file-apps'.")
1920 (defconst org-file-apps-defaults-windowsnt
1921 (list
1922 '(remote . emacs)
1923 (cons t
1924 (list (if (featurep 'xemacs)
1925 'mswindows-shell-execute
1926 'w32-shell-execute)
1927 "open" 'file))
1928 (cons 'system
1929 (list (if (featurep 'xemacs)
1930 'mswindows-shell-execute
1931 'w32-shell-execute)
1932 "open" 'file)))
1933 "Default file applications on a Windows NT system.
1934 The system \"open\" is used for most files.
1935 See `org-file-apps'.")
1937 (defcustom org-file-apps
1938 '((auto-mode . emacs)
1939 ("\\.mm\\'" . default)
1940 ("\\.x?html?\\'" . default)
1941 ("\\.pdf\\'" . default))
1942 "External applications for opening `file:path' items in a document.
1943 Org-mode uses system defaults for different file types, but
1944 you can use this variable to set the application for a given file
1945 extension. The entries in this list are cons cells where the car identifies
1946 files and the cdr the corresponding command. Possible values for the
1947 file identifier are
1948 \"string\" A string as a file identifier can be interpreted in different
1949 ways, depending on its contents:
1951 - Alphanumeric characters only:
1952 Match links with this file extension.
1953 Example: (\"pdf\" . \"evince %s\")
1954 to open PDFs with evince.
1956 - Regular expression: Match links where the
1957 filename matches the regexp. If you want to
1958 use groups here, use shy groups.
1960 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1961 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1962 to open *.html and *.xhtml with firefox.
1964 - Regular expression which contains (non-shy) groups:
1965 Match links where the whole link, including \"::\", and
1966 anything after that, matches the regexp.
1967 In a custom command string, %1, %2, etc. are replaced with
1968 the parts of the link that were matched by the groups.
1969 For backwards compatibility, if a command string is given
1970 that does not use any of the group matches, this case is
1971 handled identically to the second one (i.e. match against
1972 file name only).
1973 In a custom lisp form, you can access the group matches with
1974 (match-string n link).
1976 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1977 to open [[file:document.pdf::5]] with evince at page 5.
1979 `directory' Matches a directory
1980 `remote' Matches a remote file, accessible through tramp or efs.
1981 Remote files most likely should be visited through Emacs
1982 because external applications cannot handle such paths.
1983 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1984 so all files Emacs knows how to handle. Using this with
1985 command `emacs' will open most files in Emacs. Beware that this
1986 will also open html files inside Emacs, unless you add
1987 (\"html\" . default) to the list as well.
1988 t Default for files not matched by any of the other options.
1989 `system' The system command to open files, like `open' on Windows
1990 and Mac OS X, and mailcap under GNU/Linux. This is the command
1991 that will be selected if you call `C-c C-o' with a double
1992 \\[universal-argument] \\[universal-argument] prefix.
1994 Possible values for the command are:
1995 `emacs' The file will be visited by the current Emacs process.
1996 `default' Use the default application for this file type, which is the
1997 association for t in the list, most likely in the system-specific
1998 part.
1999 This can be used to overrule an unwanted setting in the
2000 system-specific variable.
2001 `system' Use the system command for opening files, like \"open\".
2002 This command is specified by the entry whose car is `system'.
2003 Most likely, the system-specific version of this variable
2004 does define this command, but you can overrule/replace it
2005 here.
2006 string A command to be executed by a shell; %s will be replaced
2007 by the path to the file.
2008 sexp A Lisp form which will be evaluated. The file path will
2009 be available in the Lisp variable `file'.
2010 For more examples, see the system specific constants
2011 `org-file-apps-defaults-macosx'
2012 `org-file-apps-defaults-windowsnt'
2013 `org-file-apps-defaults-gnu'."
2014 :group 'org-link-follow
2015 :type '(repeat
2016 (cons (choice :value ""
2017 (string :tag "Extension")
2018 (const :tag "System command to open files" system)
2019 (const :tag "Default for unrecognized files" t)
2020 (const :tag "Remote file" remote)
2021 (const :tag "Links to a directory" directory)
2022 (const :tag "Any files that have Emacs modes"
2023 auto-mode))
2024 (choice :value ""
2025 (const :tag "Visit with Emacs" emacs)
2026 (const :tag "Use default" default)
2027 (const :tag "Use the system command" system)
2028 (string :tag "Command")
2029 (sexp :tag "Lisp form")))))
2031 (defcustom org-doi-server-url "http://dx.doi.org/"
2032 "The URL of the DOI server."
2033 :type 'string
2034 :version "24.3"
2035 :group 'org-link-follow)
2037 (defgroup org-refile nil
2038 "Options concerning refiling entries in Org-mode."
2039 :tag "Org Refile"
2040 :group 'org)
2042 (defcustom org-directory "~/org"
2043 "Directory with org files.
2044 This is just a default location to look for Org files. There is no need
2045 at all to put your files into this directory. It is only used in the
2046 following situations:
2048 1. When a capture template specifies a target file that is not an
2049 absolute path. The path will then be interpreted relative to
2050 `org-directory'
2051 2. When a capture note is filed away in an interactive way (when exiting the
2052 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2053 with `org-directory' as the default path."
2054 :group 'org-refile
2055 :group 'org-remember
2056 :group 'org-capture
2057 :type 'directory)
2059 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2060 "Default target for storing notes.
2061 Used as a fall back file for org-remember.el and org-capture.el, for
2062 templates that do not specify a target file."
2063 :group 'org-refile
2064 :group 'org-remember
2065 :group 'org-capture
2066 :type '(choice
2067 (const :tag "Default from remember-data-file" nil)
2068 file))
2070 (defcustom org-goto-interface 'outline
2071 "The default interface to be used for `org-goto'.
2072 Allowed values are:
2073 outline The interface shows an outline of the relevant file
2074 and the correct heading is found by moving through
2075 the outline or by searching with incremental search.
2076 outline-path-completion Headlines in the current buffer are offered via
2077 completion. This is the interface also used by
2078 the refile command."
2079 :group 'org-refile
2080 :type '(choice
2081 (const :tag "Outline" outline)
2082 (const :tag "Outline-path-completion" outline-path-completion)))
2084 (defcustom org-goto-max-level 5
2085 "Maximum target level when running `org-goto' with refile interface."
2086 :group 'org-refile
2087 :type 'integer)
2089 (defcustom org-reverse-note-order nil
2090 "Non-nil means store new notes at the beginning of a file or entry.
2091 When nil, new notes will be filed to the end of a file or entry.
2092 This can also be a list with cons cells of regular expressions that
2093 are matched against file names, and values."
2094 :group 'org-remember
2095 :group 'org-capture
2096 :group 'org-refile
2097 :type '(choice
2098 (const :tag "Reverse always" t)
2099 (const :tag "Reverse never" nil)
2100 (repeat :tag "By file name regexp"
2101 (cons regexp boolean))))
2103 (defcustom org-log-refile nil
2104 "Information to record when a task is refiled.
2106 Possible values are:
2108 nil Don't add anything
2109 time Add a time stamp to the task
2110 note Prompt for a note and add it with template `org-log-note-headings'
2112 This option can also be set with on a per-file-basis with
2114 #+STARTUP: nologrefile
2115 #+STARTUP: logrefile
2116 #+STARTUP: lognoterefile
2118 You can have local logging settings for a subtree by setting the LOGGING
2119 property to one or more of these keywords.
2121 When bulk-refiling from the agenda, the value `note' is forbidden and
2122 will temporarily be changed to `time'."
2123 :group 'org-refile
2124 :group 'org-progress
2125 :version "24.1"
2126 :type '(choice
2127 (const :tag "No logging" nil)
2128 (const :tag "Record timestamp" time)
2129 (const :tag "Record timestamp with note." note)))
2131 (defcustom org-refile-targets nil
2132 "Targets for refiling entries with \\[org-refile].
2133 This is a list of cons cells. Each cell contains:
2134 - a specification of the files to be considered, either a list of files,
2135 or a symbol whose function or variable value will be used to retrieve
2136 a file name or a list of file names. If you use `org-agenda-files' for
2137 that, all agenda files will be scanned for targets. Nil means consider
2138 headings in the current buffer.
2139 - A specification of how to find candidate refile targets. This may be
2140 any of:
2141 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2142 This tag has to be present in all target headlines, inheritance will
2143 not be considered.
2144 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2145 todo keyword.
2146 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2147 headlines that are refiling targets.
2148 - a cons cell (:level . N). Any headline of level N is considered a target.
2149 Note that, when `org-odd-levels-only' is set, level corresponds to
2150 order in hierarchy, not to the number of stars.
2151 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2152 Note that, when `org-odd-levels-only' is set, level corresponds to
2153 order in hierarchy, not to the number of stars.
2155 Each element of this list generates a set of possible targets.
2156 The union of these sets is presented (with completion) to
2157 the user by `org-refile'.
2159 You can set the variable `org-refile-target-verify-function' to a function
2160 to verify each headline found by the simple criteria above.
2162 When this variable is nil, all top-level headlines in the current buffer
2163 are used, equivalent to the value `((nil . (:level . 1))'."
2164 :group 'org-refile
2165 :type '(repeat
2166 (cons
2167 (choice :value org-agenda-files
2168 (const :tag "All agenda files" org-agenda-files)
2169 (const :tag "Current buffer" nil)
2170 (function) (variable) (file))
2171 (choice :tag "Identify target headline by"
2172 (cons :tag "Specific tag" (const :value :tag) (string))
2173 (cons :tag "TODO keyword" (const :value :todo) (string))
2174 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2175 (cons :tag "Level number" (const :value :level) (integer))
2176 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2178 (defcustom org-refile-target-verify-function nil
2179 "Function to verify if the headline at point should be a refile target.
2180 The function will be called without arguments, with point at the
2181 beginning of the headline. It should return t and leave point
2182 where it is if the headline is a valid target for refiling.
2184 If the target should not be selected, the function must return nil.
2185 In addition to this, it may move point to a place from where the search
2186 should be continued. For example, the function may decide that the entire
2187 subtree of the current entry should be excluded and move point to the end
2188 of the subtree."
2189 :group 'org-refile
2190 :type '(choice
2191 (const nil)
2192 (function)))
2194 (defcustom org-refile-use-cache nil
2195 "Non-nil means cache refile targets to speed up the process.
2196 The cache for a particular file will be updated automatically when
2197 the buffer has been killed, or when any of the marker used for flagging
2198 refile targets no longer points at a live buffer.
2199 If you have added new entries to a buffer that might themselves be targets,
2200 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2201 find that easier, `C-u C-u C-u C-c C-w'."
2202 :group 'org-refile
2203 :version "24.1"
2204 :type 'boolean)
2206 (defcustom org-refile-use-outline-path nil
2207 "Non-nil means provide refile targets as paths.
2208 So a level 3 headline will be available as level1/level2/level3.
2210 When the value is `file', also include the file name (without directory)
2211 into the path. In this case, you can also stop the completion after
2212 the file name, to get entries inserted as top level in the file.
2214 When `full-file-path', include the full file path."
2215 :group 'org-refile
2216 :type '(choice
2217 (const :tag "Not" nil)
2218 (const :tag "Yes" t)
2219 (const :tag "Start with file name" file)
2220 (const :tag "Start with full file path" full-file-path)))
2222 (defcustom org-outline-path-complete-in-steps t
2223 "Non-nil means complete the outline path in hierarchical steps.
2224 When Org-mode uses the refile interface to select an outline path
2225 \(see variable `org-refile-use-outline-path'), the completion of
2226 the path can be done is a single go, or if can be done in steps down
2227 the headline hierarchy. Going in steps is probably the best if you
2228 do not use a special completion package like `ido' or `icicles'.
2229 However, when using these packages, going in one step can be very
2230 fast, while still showing the whole path to the entry."
2231 :group 'org-refile
2232 :type 'boolean)
2234 (defcustom org-refile-allow-creating-parent-nodes nil
2235 "Non-nil means allow to create new nodes as refile targets.
2236 New nodes are then created by adding \"/new node name\" to the completion
2237 of an existing node. When the value of this variable is `confirm',
2238 new node creation must be confirmed by the user (recommended)
2239 When nil, the completion must match an existing entry.
2241 Note that, if the new heading is not seen by the criteria
2242 listed in `org-refile-targets', multiple instances of the same
2243 heading would be created by trying again to file under the new
2244 heading."
2245 :group 'org-refile
2246 :type '(choice
2247 (const :tag "Never" nil)
2248 (const :tag "Always" t)
2249 (const :tag "Prompt for confirmation" confirm)))
2251 (defcustom org-refile-active-region-within-subtree nil
2252 "Non-nil means also refile active region within a subtree.
2254 By default `org-refile' doesn't allow refiling regions if they
2255 don't contain a set of subtrees, but it might be convenient to
2256 do so sometimes: in that case, the first line of the region is
2257 converted to a headline before refiling."
2258 :group 'org-refile
2259 :version "24.1"
2260 :type 'boolean)
2262 (defgroup org-todo nil
2263 "Options concerning TODO items in Org-mode."
2264 :tag "Org TODO"
2265 :group 'org)
2267 (defgroup org-progress nil
2268 "Options concerning Progress logging in Org-mode."
2269 :tag "Org Progress"
2270 :group 'org-time)
2272 (defvar org-todo-interpretation-widgets
2273 '((:tag "Sequence (cycling hits every state)" sequence)
2274 (:tag "Type (cycling directly to DONE)" type))
2275 "The available interpretation symbols for customizing `org-todo-keywords'.
2276 Interested libraries should add to this list.")
2278 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2279 "List of TODO entry keyword sequences and their interpretation.
2280 \\<org-mode-map>This is a list of sequences.
2282 Each sequence starts with a symbol, either `sequence' or `type',
2283 indicating if the keywords should be interpreted as a sequence of
2284 action steps, or as different types of TODO items. The first
2285 keywords are states requiring action - these states will select a headline
2286 for inclusion into the global TODO list Org-mode produces. If one of
2287 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2288 signify that no further action is necessary. If \"|\" is not found,
2289 the last keyword is treated as the only DONE state of the sequence.
2291 The command \\[org-todo] cycles an entry through these states, and one
2292 additional state where no keyword is present. For details about this
2293 cycling, see the manual.
2295 TODO keywords and interpretation can also be set on a per-file basis with
2296 the special #+SEQ_TODO and #+TYP_TODO lines.
2298 Each keyword can optionally specify a character for fast state selection
2299 \(in combination with the variable `org-use-fast-todo-selection')
2300 and specifiers for state change logging, using the same syntax that
2301 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2302 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2303 indicates to record a time stamp each time this state is selected.
2305 Each keyword may also specify if a timestamp or a note should be
2306 recorded when entering or leaving the state, by adding additional
2307 characters in the parenthesis after the keyword. This looks like this:
2308 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2309 record only the time of the state change. With X and Y being either
2310 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2311 Y when leaving the state if and only if the *target* state does not
2312 define X. You may omit any of the fast-selection key or X or /Y,
2313 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2315 For backward compatibility, this variable may also be just a list
2316 of keywords. In this case the interpretation (sequence or type) will be
2317 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2318 :group 'org-todo
2319 :group 'org-keywords
2320 :type '(choice
2321 (repeat :tag "Old syntax, just keywords"
2322 (string :tag "Keyword"))
2323 (repeat :tag "New syntax"
2324 (cons
2325 (choice
2326 :tag "Interpretation"
2327 ;;Quick and dirty way to see
2328 ;;`org-todo-interpretations'. This takes the
2329 ;;place of item arguments
2330 :convert-widget
2331 (lambda (widget)
2332 (widget-put widget
2333 :args (mapcar
2334 #'(lambda (x)
2335 (widget-convert
2336 (cons 'const x)))
2337 org-todo-interpretation-widgets))
2338 widget))
2339 (repeat
2340 (string :tag "Keyword"))))))
2342 (defvar org-todo-keywords-1 nil
2343 "All TODO and DONE keywords active in a buffer.")
2344 (make-variable-buffer-local 'org-todo-keywords-1)
2345 (defvar org-todo-keywords-for-agenda nil)
2346 (defvar org-done-keywords-for-agenda nil)
2347 (defvar org-drawers-for-agenda nil)
2348 (defvar org-todo-keyword-alist-for-agenda nil)
2349 (defvar org-tag-alist-for-agenda nil
2350 "Alist of all tags from all agenda files.")
2351 (defvar org-tag-groups-alist-for-agenda nil
2352 "Alist of all groups tags from all current agenda files.")
2353 (defvar org-tag-groups-alist nil)
2354 (make-variable-buffer-local 'org-tag-groups-alist)
2355 (defvar org-agenda-contributing-files nil)
2356 (defvar org-not-done-keywords nil)
2357 (make-variable-buffer-local 'org-not-done-keywords)
2358 (defvar org-done-keywords nil)
2359 (make-variable-buffer-local 'org-done-keywords)
2360 (defvar org-todo-heads nil)
2361 (make-variable-buffer-local 'org-todo-heads)
2362 (defvar org-todo-sets nil)
2363 (make-variable-buffer-local 'org-todo-sets)
2364 (defvar org-todo-log-states nil)
2365 (make-variable-buffer-local 'org-todo-log-states)
2366 (defvar org-todo-kwd-alist nil)
2367 (make-variable-buffer-local 'org-todo-kwd-alist)
2368 (defvar org-todo-key-alist nil)
2369 (make-variable-buffer-local 'org-todo-key-alist)
2370 (defvar org-todo-key-trigger nil)
2371 (make-variable-buffer-local 'org-todo-key-trigger)
2373 (defcustom org-todo-interpretation 'sequence
2374 "Controls how TODO keywords are interpreted.
2375 This variable is in principle obsolete and is only used for
2376 backward compatibility, if the interpretation of todo keywords is
2377 not given already in `org-todo-keywords'. See that variable for
2378 more information."
2379 :group 'org-todo
2380 :group 'org-keywords
2381 :type '(choice (const sequence)
2382 (const type)))
2384 (defcustom org-use-fast-todo-selection t
2385 "Non-nil means use the fast todo selection scheme with C-c C-t.
2386 This variable describes if and under what circumstances the cycling
2387 mechanism for TODO keywords will be replaced by a single-key, direct
2388 selection scheme.
2390 When nil, fast selection is never used.
2392 When the symbol `prefix', it will be used when `org-todo' is called
2393 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2394 `C-u t' in an agenda buffer.
2396 When t, fast selection is used by default. In this case, the prefix
2397 argument forces cycling instead.
2399 In all cases, the special interface is only used if access keys have
2400 actually been assigned by the user, i.e. if keywords in the configuration
2401 are followed by a letter in parenthesis, like TODO(t)."
2402 :group 'org-todo
2403 :type '(choice
2404 (const :tag "Never" nil)
2405 (const :tag "By default" t)
2406 (const :tag "Only with C-u C-c C-t" prefix)))
2408 (defcustom org-provide-todo-statistics t
2409 "Non-nil means update todo statistics after insert and toggle.
2410 ALL-HEADLINES means update todo statistics by including headlines
2411 with no TODO keyword as well, counting them as not done.
2412 A list of TODO keywords means the same, but skip keywords that are
2413 not in this list.
2415 When this is set, todo statistics is updated in the parent of the
2416 current entry each time a todo state is changed."
2417 :group 'org-todo
2418 :type '(choice
2419 (const :tag "Yes, only for TODO entries" t)
2420 (const :tag "Yes, including all entries" 'all-headlines)
2421 (repeat :tag "Yes, for TODOs in this list"
2422 (string :tag "TODO keyword"))
2423 (other :tag "No TODO statistics" nil)))
2425 (defcustom org-hierarchical-todo-statistics t
2426 "Non-nil means TODO statistics covers just direct children.
2427 When nil, all entries in the subtree are considered.
2428 This has only an effect if `org-provide-todo-statistics' is set.
2429 To set this to nil for only a single subtree, use a COOKIE_DATA
2430 property and include the word \"recursive\" into the value."
2431 :group 'org-todo
2432 :type 'boolean)
2434 (defcustom org-after-todo-state-change-hook nil
2435 "Hook which is run after the state of a TODO item was changed.
2436 The new state (a string with a TODO keyword, or nil) is available in the
2437 Lisp variable `org-state'."
2438 :group 'org-todo
2439 :type 'hook)
2441 (defvar org-blocker-hook nil
2442 "Hook for functions that are allowed to block a state change.
2444 Functions in this hook should not modify the buffer.
2445 Each function gets as its single argument a property list,
2446 see `org-trigger-hook' for more information about this list.
2448 If any of the functions in this hook returns nil, the state change
2449 is blocked.")
2451 (defvar org-trigger-hook nil
2452 "Hook for functions that are triggered by a state change.
2454 Each function gets as its single argument a property list with at
2455 least the following elements:
2457 (:type type-of-change :position pos-at-entry-start
2458 :from old-state :to new-state)
2460 Depending on the type, more properties may be present.
2462 This mechanism is currently implemented for:
2464 TODO state changes
2465 ------------------
2466 :type todo-state-change
2467 :from previous state (keyword as a string), or nil, or a symbol
2468 'todo' or 'done', to indicate the general type of state.
2469 :to new state, like in :from")
2471 (defcustom org-enforce-todo-dependencies nil
2472 "Non-nil means undone TODO entries will block switching the parent to DONE.
2473 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2474 be blocked if any prior sibling is not yet done.
2475 Finally, if the parent is blocked because of ordered siblings of its own,
2476 the child will also be blocked."
2477 :set (lambda (var val)
2478 (set var val)
2479 (if val
2480 (add-hook 'org-blocker-hook
2481 'org-block-todo-from-children-or-siblings-or-parent)
2482 (remove-hook 'org-blocker-hook
2483 'org-block-todo-from-children-or-siblings-or-parent)))
2484 :group 'org-todo
2485 :type 'boolean)
2487 (defcustom org-enforce-todo-checkbox-dependencies nil
2488 "Non-nil means unchecked boxes will block switching the parent to DONE.
2489 When this is nil, checkboxes have no influence on switching TODO states.
2490 When non-nil, you first need to check off all check boxes before the TODO
2491 entry can be switched to DONE.
2492 This variable needs to be set before org.el is loaded, and you need to
2493 restart Emacs after a change to make the change effective. The only way
2494 to change is while Emacs is running is through the customize interface."
2495 :set (lambda (var val)
2496 (set var val)
2497 (if val
2498 (add-hook 'org-blocker-hook
2499 'org-block-todo-from-checkboxes)
2500 (remove-hook 'org-blocker-hook
2501 'org-block-todo-from-checkboxes)))
2502 :group 'org-todo
2503 :type 'boolean)
2505 (defcustom org-treat-insert-todo-heading-as-state-change nil
2506 "Non-nil means inserting a TODO heading is treated as state change.
2507 So when the command \\[org-insert-todo-heading] is used, state change
2508 logging will apply if appropriate. When nil, the new TODO item will
2509 be inserted directly, and no logging will take place."
2510 :group 'org-todo
2511 :type 'boolean)
2513 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2514 "Non-nil means switching TODO states with S-cursor counts as state change.
2515 This is the default behavior. However, setting this to nil allows a
2516 convenient way to select a TODO state and bypass any logging associated
2517 with that."
2518 :group 'org-todo
2519 :type 'boolean)
2521 (defcustom org-todo-state-tags-triggers nil
2522 "Tag changes that should be triggered by TODO state changes.
2523 This is a list. Each entry is
2525 (state-change (tag . flag) .......)
2527 State-change can be a string with a state, and empty string to indicate the
2528 state that has no TODO keyword, or it can be one of the symbols `todo'
2529 or `done', meaning any not-done or done state, respectively."
2530 :group 'org-todo
2531 :group 'org-tags
2532 :type '(repeat
2533 (cons (choice :tag "When changing to"
2534 (const :tag "Not-done state" todo)
2535 (const :tag "Done state" done)
2536 (string :tag "State"))
2537 (repeat
2538 (cons :tag "Tag action"
2539 (string :tag "Tag")
2540 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2542 (defcustom org-log-done nil
2543 "Information to record when a task moves to the DONE state.
2545 Possible values are:
2547 nil Don't add anything, just change the keyword
2548 time Add a time stamp to the task
2549 note Prompt for a note and add it with template `org-log-note-headings'
2551 This option can also be set with on a per-file-basis with
2553 #+STARTUP: nologdone
2554 #+STARTUP: logdone
2555 #+STARTUP: lognotedone
2557 You can have local logging settings for a subtree by setting the LOGGING
2558 property to one or more of these keywords."
2559 :group 'org-todo
2560 :group 'org-progress
2561 :type '(choice
2562 (const :tag "No logging" nil)
2563 (const :tag "Record CLOSED timestamp" time)
2564 (const :tag "Record CLOSED timestamp with note." note)))
2566 ;; Normalize old uses of org-log-done.
2567 (cond
2568 ((eq org-log-done t) (setq org-log-done 'time))
2569 ((and (listp org-log-done) (memq 'done org-log-done))
2570 (setq org-log-done 'note)))
2572 (defcustom org-log-reschedule nil
2573 "Information to record when the scheduling date of a tasks is modified.
2575 Possible values are:
2577 nil Don't add anything, just change the date
2578 time Add a time stamp to the task
2579 note Prompt for a note and add it with template `org-log-note-headings'
2581 This option can also be set with on a per-file-basis with
2583 #+STARTUP: nologreschedule
2584 #+STARTUP: logreschedule
2585 #+STARTUP: lognotereschedule"
2586 :group 'org-todo
2587 :group 'org-progress
2588 :type '(choice
2589 (const :tag "No logging" nil)
2590 (const :tag "Record timestamp" time)
2591 (const :tag "Record timestamp with note." note)))
2593 (defcustom org-log-redeadline nil
2594 "Information to record when the deadline date of a tasks is modified.
2596 Possible values are:
2598 nil Don't add anything, just change the date
2599 time Add a time stamp to the task
2600 note Prompt for a note and add it with template `org-log-note-headings'
2602 This option can also be set with on a per-file-basis with
2604 #+STARTUP: nologredeadline
2605 #+STARTUP: logredeadline
2606 #+STARTUP: lognoteredeadline
2608 You can have local logging settings for a subtree by setting the LOGGING
2609 property to one or more of these keywords."
2610 :group 'org-todo
2611 :group 'org-progress
2612 :type '(choice
2613 (const :tag "No logging" nil)
2614 (const :tag "Record timestamp" time)
2615 (const :tag "Record timestamp with note." note)))
2617 (defcustom org-log-note-clock-out nil
2618 "Non-nil means record a note when clocking out of an item.
2619 This can also be configured on a per-file basis by adding one of
2620 the following lines anywhere in the buffer:
2622 #+STARTUP: lognoteclock-out
2623 #+STARTUP: nolognoteclock-out"
2624 :group 'org-todo
2625 :group 'org-progress
2626 :type 'boolean)
2628 (defcustom org-log-done-with-time t
2629 "Non-nil means the CLOSED time stamp will contain date and time.
2630 When nil, only the date will be recorded."
2631 :group 'org-progress
2632 :type 'boolean)
2634 (defcustom org-log-note-headings
2635 '((done . "CLOSING NOTE %t")
2636 (state . "State %-12s from %-12S %t")
2637 (note . "Note taken on %t")
2638 (reschedule . "Rescheduled from %S on %t")
2639 (delschedule . "Not scheduled, was %S on %t")
2640 (redeadline . "New deadline from %S on %t")
2641 (deldeadline . "Removed deadline, was %S on %t")
2642 (refile . "Refiled on %t")
2643 (clock-out . ""))
2644 "Headings for notes added to entries.
2645 The value is an alist, with the car being a symbol indicating the note
2646 context, and the cdr is the heading to be used. The heading may also be the
2647 empty string.
2648 %t in the heading will be replaced by a time stamp.
2649 %T will be an active time stamp instead the default inactive one
2650 %d will be replaced by a short-format time stamp.
2651 %D will be replaced by an active short-format time stamp.
2652 %s will be replaced by the new TODO state, in double quotes.
2653 %S will be replaced by the old TODO state, in double quotes.
2654 %u will be replaced by the user name.
2655 %U will be replaced by the full user name.
2657 In fact, it is not a good idea to change the `state' entry, because
2658 agenda log mode depends on the format of these entries."
2659 :group 'org-todo
2660 :group 'org-progress
2661 :type '(list :greedy t
2662 (cons (const :tag "Heading when closing an item" done) string)
2663 (cons (const :tag
2664 "Heading when changing todo state (todo sequence only)"
2665 state) string)
2666 (cons (const :tag "Heading when just taking a note" note) string)
2667 (cons (const :tag "Heading when clocking out" clock-out) string)
2668 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2669 (cons (const :tag "Heading when rescheduling" reschedule) string)
2670 (cons (const :tag "Heading when changing deadline" redeadline) string)
2671 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2672 (cons (const :tag "Heading when refiling" refile) string)))
2674 (unless (assq 'note org-log-note-headings)
2675 (push '(note . "%t") org-log-note-headings))
2677 (defcustom org-log-into-drawer nil
2678 "Non-nil means insert state change notes and time stamps into a drawer.
2679 When nil, state changes notes will be inserted after the headline and
2680 any scheduling and clock lines, but not inside a drawer.
2682 The value of this variable should be the name of the drawer to use.
2683 LOGBOOK is proposed as the default drawer for this purpose, you can
2684 also set this to a string to define the drawer of your choice.
2686 A value of t is also allowed, representing \"LOGBOOK\".
2688 A value of t or nil can also be set with on a per-file-basis with
2690 #+STARTUP: logdrawer
2691 #+STARTUP: nologdrawer
2693 If this variable is set, `org-log-state-notes-insert-after-drawers'
2694 will be ignored.
2696 You can set the property LOG_INTO_DRAWER to overrule this setting for
2697 a subtree."
2698 :group 'org-todo
2699 :group 'org-progress
2700 :type '(choice
2701 (const :tag "Not into a drawer" nil)
2702 (const :tag "LOGBOOK" t)
2703 (string :tag "Other")))
2705 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2707 (defun org-log-into-drawer ()
2708 "Return the value of `org-log-into-drawer', but let properties overrule.
2709 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2710 used instead of the default value."
2711 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2712 (cond
2713 ((not p) org-log-into-drawer)
2714 ((equal p "nil") nil)
2715 ((equal p "t") "LOGBOOK")
2716 (t p))))
2718 (defcustom org-log-state-notes-insert-after-drawers nil
2719 "Non-nil means insert state change notes after any drawers in entry.
2720 Only the drawers that *immediately* follow the headline and the
2721 deadline/scheduled line are skipped.
2722 When nil, insert notes right after the heading and perhaps the line
2723 with deadline/scheduling if present.
2725 This variable will have no effect if `org-log-into-drawer' is
2726 set."
2727 :group 'org-todo
2728 :group 'org-progress
2729 :type 'boolean)
2731 (defcustom org-log-states-order-reversed t
2732 "Non-nil means the latest state note will be directly after heading.
2733 When nil, the state change notes will be ordered according to time.
2735 This option can also be set with on a per-file-basis with
2737 #+STARTUP: logstatesreversed
2738 #+STARTUP: nologstatesreversed"
2739 :group 'org-todo
2740 :group 'org-progress
2741 :type 'boolean)
2743 (defcustom org-todo-repeat-to-state nil
2744 "The TODO state to which a repeater should return the repeating task.
2745 By default this is the first task in a TODO sequence, or the previous state
2746 in a TODO_TYP set. But you can specify another task here.
2747 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2748 :group 'org-todo
2749 :version "24.1"
2750 :type '(choice (const :tag "Head of sequence" nil)
2751 (string :tag "Specific state")))
2753 (defcustom org-log-repeat 'time
2754 "Non-nil means record moving through the DONE state when triggering repeat.
2755 An auto-repeating task is immediately switched back to TODO when
2756 marked DONE. If you are not logging state changes (by adding \"@\"
2757 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2758 record a closing note, there will be no record of the task moving
2759 through DONE. This variable forces taking a note anyway.
2761 nil Don't force a record
2762 time Record a time stamp
2763 note Prompt for a note and add it with template `org-log-note-headings'
2765 This option can also be set with on a per-file-basis with
2767 #+STARTUP: nologrepeat
2768 #+STARTUP: logrepeat
2769 #+STARTUP: lognoterepeat
2771 You can have local logging settings for a subtree by setting the LOGGING
2772 property to one or more of these keywords."
2773 :group 'org-todo
2774 :group 'org-progress
2775 :type '(choice
2776 (const :tag "Don't force a record" nil)
2777 (const :tag "Force recording the DONE state" time)
2778 (const :tag "Force recording a note with the DONE state" note)))
2781 (defgroup org-priorities nil
2782 "Priorities in Org-mode."
2783 :tag "Org Priorities"
2784 :group 'org-todo)
2786 (defcustom org-enable-priority-commands t
2787 "Non-nil means priority commands are active.
2788 When nil, these commands will be disabled, so that you never accidentally
2789 set a priority."
2790 :group 'org-priorities
2791 :type 'boolean)
2793 (defcustom org-highest-priority ?A
2794 "The highest priority of TODO items. A character like ?A, ?B etc.
2795 Must have a smaller ASCII number than `org-lowest-priority'."
2796 :group 'org-priorities
2797 :type 'character)
2799 (defcustom org-lowest-priority ?C
2800 "The lowest priority of TODO items. A character like ?A, ?B etc.
2801 Must have a larger ASCII number than `org-highest-priority'."
2802 :group 'org-priorities
2803 :type 'character)
2805 (defcustom org-default-priority ?B
2806 "The default priority of TODO items.
2807 This is the priority an item gets if no explicit priority is given.
2808 When starting to cycle on an empty priority the first step in the cycle
2809 depends on `org-priority-start-cycle-with-default'. The resulting first
2810 step priority must not exceed the range from `org-highest-priority' to
2811 `org-lowest-priority' which means that `org-default-priority' has to be
2812 in this range exclusive or inclusive the range boundaries. Else the
2813 first step refuses to set the default and the second will fall back
2814 to (depending on the command used) the highest or lowest priority."
2815 :group 'org-priorities
2816 :type 'character)
2818 (defcustom org-priority-start-cycle-with-default t
2819 "Non-nil means start with default priority when starting to cycle.
2820 When this is nil, the first step in the cycle will be (depending on the
2821 command used) one higher or lower than the default priority.
2822 See also `org-default-priority'."
2823 :group 'org-priorities
2824 :type 'boolean)
2826 (defcustom org-get-priority-function nil
2827 "Function to extract the priority from a string.
2828 The string is normally the headline. If this is nil Org computes the
2829 priority from the priority cookie like [#A] in the headline. It returns
2830 an integer, increasing by 1000 for each priority level.
2831 The user can set a different function here, which should take a string
2832 as an argument and return the numeric priority."
2833 :group 'org-priorities
2834 :version "24.1"
2835 :type '(choice
2836 (const nil)
2837 (function)))
2839 (defgroup org-time nil
2840 "Options concerning time stamps and deadlines in Org-mode."
2841 :tag "Org Time"
2842 :group 'org)
2844 (defcustom org-insert-labeled-timestamps-at-point nil
2845 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2846 When nil, these labeled time stamps are forces into the second line of an
2847 entry, just after the headline. When scheduling from the global TODO list,
2848 the time stamp will always be forced into the second line."
2849 :group 'org-time
2850 :type 'boolean)
2852 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2853 "Formats for `format-time-string' which are used for time stamps.
2854 It is not recommended to change this constant.")
2856 (defcustom org-time-stamp-rounding-minutes '(0 5)
2857 "Number of minutes to round time stamps to.
2858 These are two values, the first applies when first creating a time stamp.
2859 The second applies when changing it with the commands `S-up' and `S-down'.
2860 When changing the time stamp, this means that it will change in steps
2861 of N minutes, as given by the second value.
2863 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2864 numbers should be factors of 60, so for example 5, 10, 15.
2866 When this is larger than 1, you can still force an exact time stamp by using
2867 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2868 and by using a prefix arg to `S-up/down' to specify the exact number
2869 of minutes to shift."
2870 :group 'org-time
2871 :get #'(lambda (var) ; Make sure both elements are there
2872 (if (integerp (default-value var))
2873 (list (default-value var) 5)
2874 (default-value var)))
2875 :type '(list
2876 (integer :tag "when inserting times")
2877 (integer :tag "when modifying times")))
2879 ;; Normalize old customizations of this variable.
2880 (when (integerp org-time-stamp-rounding-minutes)
2881 (setq org-time-stamp-rounding-minutes
2882 (list org-time-stamp-rounding-minutes
2883 org-time-stamp-rounding-minutes)))
2885 (defcustom org-display-custom-times nil
2886 "Non-nil means overlay custom formats over all time stamps.
2887 The formats are defined through the variable `org-time-stamp-custom-formats'.
2888 To turn this on on a per-file basis, insert anywhere in the file:
2889 #+STARTUP: customtime"
2890 :group 'org-time
2891 :set 'set-default
2892 :type 'sexp)
2893 (make-variable-buffer-local 'org-display-custom-times)
2895 (defcustom org-time-stamp-custom-formats
2896 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2897 "Custom formats for time stamps. See `format-time-string' for the syntax.
2898 These are overlaid over the default ISO format if the variable
2899 `org-display-custom-times' is set. Time like %H:%M should be at the
2900 end of the second format. The custom formats are also honored by export
2901 commands, if custom time display is turned on at the time of export."
2902 :group 'org-time
2903 :type 'sexp)
2905 (defun org-time-stamp-format (&optional long inactive)
2906 "Get the right format for a time string."
2907 (let ((f (if long (cdr org-time-stamp-formats)
2908 (car org-time-stamp-formats))))
2909 (if inactive
2910 (concat "[" (substring f 1 -1) "]")
2911 f)))
2913 (defcustom org-time-clocksum-format
2914 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2915 "The format string used when creating CLOCKSUM lines.
2916 This is also used when Org mode generates a time duration.
2918 The value can be a single format string containing two
2919 %-sequences, which will be filled with the number of hours and
2920 minutes in that order.
2922 Alternatively, the value can be a plist associating any of the
2923 keys :years, :months, :weeks, :days, :hours or :minutes with
2924 format strings. The time duration is formatted using only the
2925 time components that are needed and concatenating the results.
2926 If a time unit in absent, it falls back to the next smallest
2927 unit.
2929 The keys :require-years, :require-months, :require-days,
2930 :require-weeks, :require-hours, :require-minutes are also
2931 meaningful. A non-nil value for these keys indicates that the
2932 corresponding time component should always be included, even if
2933 its value is 0.
2936 For example,
2938 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2939 :require-minutes t)
2941 means durations longer than a day will be expressed in days,
2942 hours and minutes, and durations less than a day will always be
2943 expressed in hours and minutes (even for durations less than an
2944 hour).
2946 The value
2948 \(:days \"%dd\" :minutes \"%dm\")
2950 means durations longer than a day will be expressed in days and
2951 minutes, and durations less than a day will be expressed entirely
2952 in minutes (even for durations longer than an hour)."
2953 :group 'org-time
2954 :group 'org-clock
2955 :version "24.4"
2956 :package-version '(Org . "8.0")
2957 :type '(choice (string :tag "Format string")
2958 (set :tag "Plist"
2959 (group :inline t (const :tag "Years" :years)
2960 (string :tag "Format string"))
2961 (group :inline t
2962 (const :tag "Always show years" :require-years)
2963 (const t))
2964 (group :inline t (const :tag "Months" :months)
2965 (string :tag "Format string"))
2966 (group :inline t
2967 (const :tag "Always show months" :require-months)
2968 (const t))
2969 (group :inline t (const :tag "Weeks" :weeks)
2970 (string :tag "Format string"))
2971 (group :inline t
2972 (const :tag "Always show weeks" :require-weeks)
2973 (const t))
2974 (group :inline t (const :tag "Days" :days)
2975 (string :tag "Format string"))
2976 (group :inline t
2977 (const :tag "Always show days" :require-days)
2978 (const t))
2979 (group :inline t (const :tag "Hours" :hours)
2980 (string :tag "Format string"))
2981 (group :inline t
2982 (const :tag "Always show hours" :require-hours)
2983 (const t))
2984 (group :inline t (const :tag "Minutes" :minutes)
2985 (string :tag "Format string"))
2986 (group :inline t
2987 (const :tag "Always show minutes" :require-minutes)
2988 (const t)))))
2990 (defcustom org-time-clocksum-use-fractional nil
2991 "When non-nil, \\[org-clock-display] uses fractional times.
2992 See `org-time-clocksum-format' for more on time clock formats."
2993 :group 'org-time
2994 :group 'org-clock
2995 :version "24.3"
2996 :type 'boolean)
2998 (defcustom org-time-clocksum-use-effort-durations nil
2999 "When non-nil, \\[org-clock-display] uses effort durations.
3000 E.g. by default, one day is considered to be a 8 hours effort,
3001 so a task that has been clocked for 16 hours will be displayed
3002 as during 2 days in the clock display or in the clocktable.
3004 See `org-effort-durations' on how to set effort durations
3005 and `org-time-clocksum-format' for more on time clock formats."
3006 :group 'org-time
3007 :group 'org-clock
3008 :version "24.4"
3009 :package-version '(Org . "8.0")
3010 :type 'boolean)
3012 (defcustom org-time-clocksum-fractional-format "%.2f"
3013 "The format string used when creating CLOCKSUM lines,
3014 or when Org mode generates a time duration, if
3015 `org-time-clocksum-use-fractional' is enabled.
3017 The value can be a single format string containing one
3018 %-sequence, which will be filled with the number of hours as
3019 a float.
3021 Alternatively, the value can be a plist associating any of the
3022 keys :years, :months, :weeks, :days, :hours or :minutes with
3023 a format string. The time duration is formatted using the
3024 largest time unit which gives a non-zero integer part. If all
3025 specified formats have zero integer part, the smallest time unit
3026 is used."
3027 :group 'org-time
3028 :type '(choice (string :tag "Format string")
3029 (set (group :inline t (const :tag "Years" :years)
3030 (string :tag "Format string"))
3031 (group :inline t (const :tag "Months" :months)
3032 (string :tag "Format string"))
3033 (group :inline t (const :tag "Weeks" :weeks)
3034 (string :tag "Format string"))
3035 (group :inline t (const :tag "Days" :days)
3036 (string :tag "Format string"))
3037 (group :inline t (const :tag "Hours" :hours)
3038 (string :tag "Format string"))
3039 (group :inline t (const :tag "Minutes" :minutes)
3040 (string :tag "Format string")))))
3042 (defcustom org-deadline-warning-days 14
3043 "Number of days before expiration during which a deadline becomes active.
3044 This variable governs the display in sparse trees and in the agenda.
3045 When 0 or negative, it means use this number (the absolute value of it)
3046 even if a deadline has a different individual lead time specified.
3048 Custom commands can set this variable in the options section."
3049 :group 'org-time
3050 :group 'org-agenda-daily/weekly
3051 :type 'integer)
3053 (defcustom org-scheduled-delay-days 0
3054 "Number of days before a scheduled item becomes active.
3055 This variable governs the display in sparse trees and in the agenda.
3056 The default value (i.e. 0) means: don't delay scheduled item.
3057 When negative, it means use this number (the absolute value of it)
3058 even if a scheduled item has a different individual delay time
3059 specified.
3061 Custom commands can set this variable in the options section."
3062 :group 'org-time
3063 :group 'org-agenda-daily/weekly
3064 :version "24.4"
3065 :package-version '(Org . "8.0")
3066 :type 'integer)
3068 (defcustom org-read-date-prefer-future t
3069 "Non-nil means assume future for incomplete date input from user.
3070 This affects the following situations:
3071 1. The user gives a month but not a year.
3072 For example, if it is April and you enter \"feb 2\", this will be read
3073 as Feb 2, *next* year. \"May 5\", however, will be this year.
3074 2. The user gives a day, but no month.
3075 For example, if today is the 15th, and you enter \"3\", Org-mode will
3076 read this as the third of *next* month. However, if you enter \"17\",
3077 it will be considered as *this* month.
3079 If you set this variable to the symbol `time', then also the following
3080 will work:
3082 3. If the user gives a time.
3083 If the time is before now, it will be interpreted as tomorrow.
3085 Currently none of this works for ISO week specifications.
3087 When this option is nil, the current day, month and year will always be
3088 used as defaults.
3090 See also `org-agenda-jump-prefer-future'."
3091 :group 'org-time
3092 :type '(choice
3093 (const :tag "Never" nil)
3094 (const :tag "Check month and day" t)
3095 (const :tag "Check month, day, and time" time)))
3097 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3098 "Should the agenda jump command prefer the future for incomplete dates?
3099 The default is to do the same as configured in `org-read-date-prefer-future'.
3100 But you can also set a deviating value here.
3101 This may t or nil, or the symbol `org-read-date-prefer-future'."
3102 :group 'org-agenda
3103 :group 'org-time
3104 :version "24.1"
3105 :type '(choice
3106 (const :tag "Use org-read-date-prefer-future"
3107 org-read-date-prefer-future)
3108 (const :tag "Never" nil)
3109 (const :tag "Always" t)))
3111 (defcustom org-read-date-force-compatible-dates t
3112 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3114 Depending on the system Emacs is running on, certain dates cannot
3115 be represented with the type used internally to represent time.
3116 Dates between 1970-1-1 and 2038-1-1 can always be represented
3117 correctly. Some systems allow for earlier dates, some for later,
3118 some for both. One way to find out it to insert any date into an
3119 Org buffer, putting the cursor on the year and hitting S-up and
3120 S-down to test the range.
3122 When this variable is set to t, the date/time prompt will not let
3123 you specify dates outside the 1970-2037 range, so it is certain that
3124 these dates will work in whatever version of Emacs you are
3125 running, and also that you can move a file from one Emacs implementation
3126 to another. WHenever Org is forcing the year for you, it will display
3127 a message and beep.
3129 When this variable is nil, Org will check if the date is
3130 representable in the specific Emacs implementation you are using.
3131 If not, it will force a year, usually the current year, and beep
3132 to remind you. Currently this setting is not recommended because
3133 the likelihood that you will open your Org files in an Emacs that
3134 has limited date range is not negligible.
3136 A workaround for this problem is to use diary sexp dates for time
3137 stamps outside of this range."
3138 :group 'org-time
3139 :version "24.1"
3140 :type 'boolean)
3142 (defcustom org-read-date-display-live t
3143 "Non-nil means display current interpretation of date prompt live.
3144 This display will be in an overlay, in the minibuffer."
3145 :group 'org-time
3146 :type 'boolean)
3148 (defcustom org-read-date-popup-calendar t
3149 "Non-nil means pop up a calendar when prompting for a date.
3150 In the calendar, the date can be selected with mouse-1. However, the
3151 minibuffer will also be active, and you can simply enter the date as well.
3152 When nil, only the minibuffer will be available."
3153 :group 'org-time
3154 :type 'boolean)
3155 (org-defvaralias 'org-popup-calendar-for-date-prompt
3156 'org-read-date-popup-calendar)
3158 (make-obsolete-variable
3159 'org-read-date-minibuffer-setup-hook
3160 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3161 (defcustom org-read-date-minibuffer-setup-hook nil
3162 "Hook to be used to set up keys for the date/time interface.
3163 Add key definitions to `minibuffer-local-map', which will be a
3164 temporary copy.
3166 WARNING: This option is obsolete, you should use
3167 `org-read-date-minibuffer-local-map' to set up keys."
3168 :group 'org-time
3169 :type 'hook)
3171 (defcustom org-extend-today-until 0
3172 "The hour when your day really ends. Must be an integer.
3173 This has influence for the following applications:
3174 - When switching the agenda to \"today\". It it is still earlier than
3175 the time given here, the day recognized as TODAY is actually yesterday.
3176 - When a date is read from the user and it is still before the time given
3177 here, the current date and time will be assumed to be yesterday, 23:59.
3178 Also, timestamps inserted in capture templates follow this rule.
3180 IMPORTANT: This is a feature whose implementation is and likely will
3181 remain incomplete. Really, it is only here because past midnight seems to
3182 be the favorite working time of John Wiegley :-)"
3183 :group 'org-time
3184 :type 'integer)
3186 (defcustom org-use-effective-time nil
3187 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3188 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3189 \"effective time\" of any timestamps between midnight and 8am will be
3190 23:59 of the previous day."
3191 :group 'org-time
3192 :version "24.1"
3193 :type 'boolean)
3195 (defcustom org-use-last-clock-out-time-as-effective-time nil
3196 "When non-nil, use the last clock out time for `org-todo'.
3197 Note that this option has precedence over the combined use of
3198 `org-use-effective-time' and `org-extend-today-until'."
3199 :group 'org-time
3200 :version "24.4"
3201 :package-version '(Org . "8.0")
3202 :type 'boolean)
3204 (defcustom org-edit-timestamp-down-means-later nil
3205 "Non-nil means S-down will increase the time in a time stamp.
3206 When nil, S-up will increase."
3207 :group 'org-time
3208 :type 'boolean)
3210 (defcustom org-calendar-follow-timestamp-change t
3211 "Non-nil means make the calendar window follow timestamp changes.
3212 When a timestamp is modified and the calendar window is visible, it will be
3213 moved to the new date."
3214 :group 'org-time
3215 :type 'boolean)
3217 (defgroup org-tags nil
3218 "Options concerning tags in Org-mode."
3219 :tag "Org Tags"
3220 :group 'org)
3222 (defcustom org-tag-alist nil
3223 "List of tags allowed in Org-mode files.
3224 When this list is nil, Org-mode will base TAG input on what is already in the
3225 buffer.
3226 The value of this variable is an alist, the car of each entry must be a
3227 keyword as a string, the cdr may be a character that is used to select
3228 that tag through the fast-tag-selection interface.
3229 See the manual for details."
3230 :group 'org-tags
3231 :type '(repeat
3232 (choice
3233 (cons (string :tag "Tag name")
3234 (character :tag "Access char"))
3235 (list :tag "Start radio group"
3236 (const :startgroup)
3237 (option (string :tag "Group description")))
3238 (list :tag "Group tags delimiter"
3239 (const :grouptags))
3240 (list :tag "End radio group"
3241 (const :endgroup)
3242 (option (string :tag "Group description")))
3243 (const :tag "New line" (:newline)))))
3245 (defcustom org-tag-persistent-alist nil
3246 "List of tags that will always appear in all Org-mode files.
3247 This is in addition to any in buffer settings or customizations
3248 of `org-tag-alist'.
3249 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3250 The value of this variable is an alist, the car of each entry must be a
3251 keyword as a string, the cdr may be a character that is used to select
3252 that tag through the fast-tag-selection interface.
3253 See the manual for details.
3254 To disable these tags on a per-file basis, insert anywhere in the file:
3255 #+STARTUP: noptag"
3256 :group 'org-tags
3257 :type '(repeat
3258 (choice
3259 (cons (string :tag "Tag name")
3260 (character :tag "Access char"))
3261 (const :tag "Start radio group" (:startgroup))
3262 (const :tag "Group tags delimiter" (:grouptags))
3263 (const :tag "End radio group" (:endgroup))
3264 (const :tag "New line" (:newline)))))
3266 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3267 "If non-nil, always offer completion for all tags of all agenda files.
3268 Instead of customizing this variable directly, you might want to
3269 set it locally for capture buffers, because there no list of
3270 tags in that file can be created dynamically (there are none).
3272 (add-hook 'org-capture-mode-hook
3273 (lambda ()
3274 (set (make-local-variable
3275 'org-complete-tags-always-offer-all-agenda-tags)
3276 t)))"
3277 :group 'org-tags
3278 :version "24.1"
3279 :type 'boolean)
3281 (defvar org-file-tags nil
3282 "List of tags that can be inherited by all entries in the file.
3283 The tags will be inherited if the variable `org-use-tag-inheritance'
3284 says they should be.
3285 This variable is populated from #+FILETAGS lines.")
3287 (defcustom org-use-fast-tag-selection 'auto
3288 "Non-nil means use fast tag selection scheme.
3289 This is a special interface to select and deselect tags with single keys.
3290 When nil, fast selection is never used.
3291 When the symbol `auto', fast selection is used if and only if selection
3292 characters for tags have been configured, either through the variable
3293 `org-tag-alist' or through a #+TAGS line in the buffer.
3294 When t, fast selection is always used and selection keys are assigned
3295 automatically if necessary."
3296 :group 'org-tags
3297 :type '(choice
3298 (const :tag "Always" t)
3299 (const :tag "Never" nil)
3300 (const :tag "When selection characters are configured" auto)))
3302 (defcustom org-fast-tag-selection-single-key nil
3303 "Non-nil means fast tag selection exits after first change.
3304 When nil, you have to press RET to exit it.
3305 During fast tag selection, you can toggle this flag with `C-c'.
3306 This variable can also have the value `expert'. In this case, the window
3307 displaying the tags menu is not even shown, until you press C-c again."
3308 :group 'org-tags
3309 :type '(choice
3310 (const :tag "No" nil)
3311 (const :tag "Yes" t)
3312 (const :tag "Expert" expert)))
3314 (defvar org-fast-tag-selection-include-todo nil
3315 "Non-nil means fast tags selection interface will also offer TODO states.
3316 This is an undocumented feature, you should not rely on it.")
3318 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3319 "The column to which tags should be indented in a headline.
3320 If this number is positive, it specifies the column. If it is negative,
3321 it means that the tags should be flushright to that column. For example,
3322 -80 works well for a normal 80 character screen.
3323 When 0, place tags directly after headline text, with only one space in
3324 between."
3325 :group 'org-tags
3326 :type 'integer)
3328 (defcustom org-auto-align-tags t
3329 "Non-nil keeps tags aligned when modifying headlines.
3330 Some operations (i.e. demoting) change the length of a headline and
3331 therefore shift the tags around. With this option turned on, after
3332 each such operation the tags are again aligned to `org-tags-column'."
3333 :group 'org-tags
3334 :type 'boolean)
3336 (defcustom org-use-tag-inheritance t
3337 "Non-nil means tags in levels apply also for sublevels.
3338 When nil, only the tags directly given in a specific line apply there.
3339 This may also be a list of tags that should be inherited, or a regexp that
3340 matches tags that should be inherited. Additional control is possible
3341 with the variable `org-tags-exclude-from-inheritance' which gives an
3342 explicit list of tags to be excluded from inheritance, even if the value of
3343 `org-use-tag-inheritance' would select it for inheritance.
3345 If this option is t, a match early-on in a tree can lead to a large
3346 number of matches in the subtree when constructing the agenda or creating
3347 a sparse tree. If you only want to see the first match in a tree during
3348 a search, check out the variable `org-tags-match-list-sublevels'."
3349 :group 'org-tags
3350 :type '(choice
3351 (const :tag "Not" nil)
3352 (const :tag "Always" t)
3353 (repeat :tag "Specific tags" (string :tag "Tag"))
3354 (regexp :tag "Tags matched by regexp")))
3356 (defcustom org-tags-exclude-from-inheritance nil
3357 "List of tags that should never be inherited.
3358 This is a way to exclude a few tags from inheritance. For way to do
3359 the opposite, to actively allow inheritance for selected tags,
3360 see the variable `org-use-tag-inheritance'."
3361 :group 'org-tags
3362 :type '(repeat (string :tag "Tag")))
3364 (defun org-tag-inherit-p (tag)
3365 "Check if TAG is one that should be inherited."
3366 (cond
3367 ((member tag org-tags-exclude-from-inheritance) nil)
3368 ((eq org-use-tag-inheritance t) t)
3369 ((not org-use-tag-inheritance) nil)
3370 ((stringp org-use-tag-inheritance)
3371 (string-match org-use-tag-inheritance tag))
3372 ((listp org-use-tag-inheritance)
3373 (member tag org-use-tag-inheritance))
3374 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3376 (defcustom org-tags-match-list-sublevels t
3377 "Non-nil means list also sublevels of headlines matching a search.
3378 This variable applies to tags/property searches, and also to stuck
3379 projects because this search is based on a tags match as well.
3381 When set to the symbol `indented', sublevels are indented with
3382 leading dots.
3384 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3385 the sublevels of a headline matching a tag search often also match
3386 the same search. Listing all of them can create very long lists.
3387 Setting this variable to nil causes subtrees of a match to be skipped.
3389 This variable is semi-obsolete and probably should always be true. It
3390 is better to limit inheritance to certain tags using the variables
3391 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3392 :group 'org-tags
3393 :type '(choice
3394 (const :tag "No, don't list them" nil)
3395 (const :tag "Yes, do list them" t)
3396 (const :tag "List them, indented with leading dots" indented)))
3398 (defcustom org-tags-sort-function nil
3399 "When set, tags are sorted using this function as a comparator."
3400 :group 'org-tags
3401 :type '(choice
3402 (const :tag "No sorting" nil)
3403 (const :tag "Alphabetical" string<)
3404 (const :tag "Reverse alphabetical" string>)
3405 (function :tag "Custom function" nil)))
3407 (defvar org-tags-history nil
3408 "History of minibuffer reads for tags.")
3409 (defvar org-last-tags-completion-table nil
3410 "The last used completion table for tags.")
3411 (defvar org-after-tags-change-hook nil
3412 "Hook that is run after the tags in a line have changed.")
3414 (defgroup org-properties nil
3415 "Options concerning properties in Org-mode."
3416 :tag "Org Properties"
3417 :group 'org)
3419 (defcustom org-property-format "%-10s %s"
3420 "How property key/value pairs should be formatted by `indent-line'.
3421 When `indent-line' hits a property definition, it will format the line
3422 according to this format, mainly to make sure that the values are
3423 lined-up with respect to each other."
3424 :group 'org-properties
3425 :type 'string)
3427 (defcustom org-properties-postprocess-alist nil
3428 "Alist of properties and functions to adjust inserted values.
3429 Elements of this alist must be of the form
3431 ([string] [function])
3433 where [string] must be a property name and [function] must be a
3434 lambda expression: this lambda expression must take one argument,
3435 the value to adjust, and return the new value as a string.
3437 For example, this element will allow the property \"Remaining\"
3438 to be updated wrt the relation between the \"Effort\" property
3439 and the clock summary:
3441 ((\"Remaining\" (lambda(value)
3442 (let ((clocksum (org-clock-sum-current-item))
3443 (effort (org-duration-string-to-minutes
3444 (org-entry-get (point) \"Effort\"))))
3445 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3446 :group 'org-properties
3447 :version "24.1"
3448 :type '(alist :key-type (string :tag "Property")
3449 :value-type (function :tag "Function")))
3451 (defcustom org-use-property-inheritance nil
3452 "Non-nil means properties apply also for sublevels.
3454 This setting is chiefly used during property searches. Turning it on can
3455 cause significant overhead when doing a search, which is why it is not
3456 on by default.
3458 When nil, only the properties directly given in the current entry count.
3459 When t, every property is inherited. The value may also be a list of
3460 properties that should have inheritance, or a regular expression matching
3461 properties that should be inherited.
3463 However, note that some special properties use inheritance under special
3464 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3465 and the properties ending in \"_ALL\" when they are used as descriptor
3466 for valid values of a property.
3468 Note for programmers:
3469 When querying an entry with `org-entry-get', you can control if inheritance
3470 should be used. By default, `org-entry-get' looks only at the local
3471 properties. You can request inheritance by setting the inherit argument
3472 to t (to force inheritance) or to `selective' (to respect the setting
3473 in this variable)."
3474 :group 'org-properties
3475 :type '(choice
3476 (const :tag "Not" nil)
3477 (const :tag "Always" t)
3478 (repeat :tag "Specific properties" (string :tag "Property"))
3479 (regexp :tag "Properties matched by regexp")))
3481 (defun org-property-inherit-p (property)
3482 "Check if PROPERTY is one that should be inherited."
3483 (cond
3484 ((eq org-use-property-inheritance t) t)
3485 ((not org-use-property-inheritance) nil)
3486 ((stringp org-use-property-inheritance)
3487 (string-match org-use-property-inheritance property))
3488 ((listp org-use-property-inheritance)
3489 (member property org-use-property-inheritance))
3490 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3492 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3493 "The default column format, if no other format has been defined.
3494 This variable can be set on the per-file basis by inserting a line
3496 #+COLUMNS: %25ITEM ....."
3497 :group 'org-properties
3498 :type 'string)
3500 (defcustom org-columns-ellipses ".."
3501 "The ellipses to be used when a field in column view is truncated.
3502 When this is the empty string, as many characters as possible are shown,
3503 but then there will be no visual indication that the field has been truncated.
3504 When this is a string of length N, the last N characters of a truncated
3505 field are replaced by this string. If the column is narrower than the
3506 ellipses string, only part of the ellipses string will be shown."
3507 :group 'org-properties
3508 :type 'string)
3510 (defcustom org-columns-modify-value-for-display-function nil
3511 "Function that modifies values for display in column view.
3512 For example, it can be used to cut out a certain part from a time stamp.
3513 The function must take 2 arguments:
3515 column-title The title of the column (*not* the property name)
3516 value The value that should be modified.
3518 The function should return the value that should be displayed,
3519 or nil if the normal value should be used."
3520 :group 'org-properties
3521 :type '(choice (const nil) (function)))
3523 (defcustom org-effort-property "Effort"
3524 "The property that is being used to keep track of effort estimates.
3525 Effort estimates given in this property need to have the format H:MM."
3526 :group 'org-properties
3527 :group 'org-progress
3528 :type '(string :tag "Property"))
3530 (defconst org-global-properties-fixed
3531 '(("VISIBILITY_ALL" . "folded children content all")
3532 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3533 "List of property/value pairs that can be inherited by any entry.
3535 These are fixed values, for the preset properties. The user variable
3536 that can be used to add to this list is `org-global-properties'.
3538 The entries in this list are cons cells where the car is a property
3539 name and cdr is a string with the value. If the value represents
3540 multiple items like an \"_ALL\" property, separate the items by
3541 spaces.")
3543 (defcustom org-global-properties nil
3544 "List of property/value pairs that can be inherited by any entry.
3546 This list will be combined with the constant `org-global-properties-fixed'.
3548 The entries in this list are cons cells where the car is a property
3549 name and cdr is a string with the value.
3551 You can set buffer-local values for the same purpose in the variable
3552 `org-file-properties' this by adding lines like
3554 #+PROPERTY: NAME VALUE"
3555 :group 'org-properties
3556 :type '(repeat
3557 (cons (string :tag "Property")
3558 (string :tag "Value"))))
3560 (defvar org-file-properties nil
3561 "List of property/value pairs that can be inherited by any entry.
3562 Valid for the current buffer.
3563 This variable is populated from #+PROPERTY lines.")
3564 (make-variable-buffer-local 'org-file-properties)
3566 (defgroup org-agenda nil
3567 "Options concerning agenda views in Org-mode."
3568 :tag "Org Agenda"
3569 :group 'org)
3571 (defvar org-category nil
3572 "Variable used by org files to set a category for agenda display.
3573 Such files should use a file variable to set it, for example
3575 # -*- mode: org; org-category: \"ELisp\"
3577 or contain a special line
3579 #+CATEGORY: ELisp
3581 If the file does not specify a category, then file's base name
3582 is used instead.")
3583 (make-variable-buffer-local 'org-category)
3584 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3586 (defcustom org-agenda-files nil
3587 "The files to be used for agenda display.
3588 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3589 \\[org-remove-file]. You can also use customize to edit the list.
3591 If an entry is a directory, all files in that directory that are matched by
3592 `org-agenda-file-regexp' will be part of the file list.
3594 If the value of the variable is not a list but a single file name, then
3595 the list of agenda files is actually stored and maintained in that file, one
3596 agenda file per line. In this file paths can be given relative to
3597 `org-directory'. Tilde expansion and environment variable substitution
3598 are also made."
3599 :group 'org-agenda
3600 :type '(choice
3601 (repeat :tag "List of files and directories" file)
3602 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3604 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3605 "Regular expression to match files for `org-agenda-files'.
3606 If any element in the list in that variable contains a directory instead
3607 of a normal file, all files in that directory that are matched by this
3608 regular expression will be included."
3609 :group 'org-agenda
3610 :type 'regexp)
3612 (defcustom org-agenda-text-search-extra-files nil
3613 "List of extra files to be searched by text search commands.
3614 These files will be searched in addition to the agenda files by the
3615 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3616 Note that these files will only be searched for text search commands,
3617 not for the other agenda views like todo lists, tag searches or the weekly
3618 agenda. This variable is intended to list notes and possibly archive files
3619 that should also be searched by these two commands.
3620 In fact, if the first element in the list is the symbol `agenda-archives',
3621 then all archive files of all agenda files will be added to the search
3622 scope."
3623 :group 'org-agenda
3624 :type '(set :greedy t
3625 (const :tag "Agenda Archives" agenda-archives)
3626 (repeat :inline t (file))))
3628 (org-defvaralias 'org-agenda-multi-occur-extra-files
3629 'org-agenda-text-search-extra-files)
3631 (defcustom org-agenda-skip-unavailable-files nil
3632 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3633 A nil value means to remove them, after a query, from the list."
3634 :group 'org-agenda
3635 :type 'boolean)
3637 (defcustom org-calendar-to-agenda-key [?c]
3638 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3639 The command `org-calendar-goto-agenda' will be bound to this key. The
3640 default is the character `c' because then `c' can be used to switch back and
3641 forth between agenda and calendar."
3642 :group 'org-agenda
3643 :type 'sexp)
3645 (defcustom org-calendar-insert-diary-entry-key [?i]
3646 "The key to be installed in `calendar-mode-map' for adding diary entries.
3647 This option is irrelevant until `org-agenda-diary-file' has been configured
3648 to point to an Org-mode file. When that is the case, the command
3649 `org-agenda-diary-entry' will be bound to the key given here, by default
3650 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3651 if you want to continue doing this, you need to change this to a different
3652 key."
3653 :group 'org-agenda
3654 :type 'sexp)
3656 (defcustom org-agenda-diary-file 'diary-file
3657 "File to which to add new entries with the `i' key in agenda and calendar.
3658 When this is the symbol `diary-file', the functionality in the Emacs
3659 calendar will be used to add entries to the `diary-file'. But when this
3660 points to a file, `org-agenda-diary-entry' will be used instead."
3661 :group 'org-agenda
3662 :type '(choice
3663 (const :tag "The standard Emacs diary file" diary-file)
3664 (file :tag "Special Org file diary entries")))
3666 (eval-after-load "calendar"
3667 '(progn
3668 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3669 'org-calendar-goto-agenda)
3670 (add-hook 'calendar-mode-hook
3671 (lambda ()
3672 (unless (eq org-agenda-diary-file 'diary-file)
3673 (define-key calendar-mode-map
3674 org-calendar-insert-diary-entry-key
3675 'org-agenda-diary-entry))))))
3677 (defgroup org-latex nil
3678 "Options for embedding LaTeX code into Org-mode."
3679 :tag "Org LaTeX"
3680 :group 'org)
3682 (defcustom org-format-latex-options
3683 '(:foreground default :background default :scale 1.0
3684 :html-foreground "Black" :html-background "Transparent"
3685 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3686 "Options for creating images from LaTeX fragments.
3687 This is a property list with the following properties:
3688 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3689 `default' means use the foreground of the default face.
3690 `auto' means use the foreground from the text face.
3691 :background the background color, or \"Transparent\".
3692 `default' means use the background of the default face.
3693 `auto' means use the background from the text face.
3694 :scale a scaling factor for the size of the images, to get more pixels
3695 :html-foreground, :html-background, :html-scale
3696 the same numbers for HTML export.
3697 :matchers a list indicating which matchers should be used to
3698 find LaTeX fragments. Valid members of this list are:
3699 \"begin\" find environments
3700 \"$1\" find single characters surrounded by $.$
3701 \"$\" find math expressions surrounded by $...$
3702 \"$$\" find math expressions surrounded by $$....$$
3703 \"\\(\" find math expressions surrounded by \\(...\\)
3704 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3705 :group 'org-latex
3706 :type 'plist)
3708 (defcustom org-format-latex-signal-error t
3709 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3710 When nil, just push out a message."
3711 :group 'org-latex
3712 :version "24.1"
3713 :type 'boolean)
3715 (defcustom org-latex-to-mathml-jar-file nil
3716 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3717 Use this to specify additional executable file say a jar file.
3719 When using MathToWeb as the converter, specify the full-path to
3720 your mathtoweb.jar file."
3721 :group 'org-latex
3722 :version "24.1"
3723 :type '(choice
3724 (const :tag "None" nil)
3725 (file :tag "JAR file" :must-match t)))
3727 (defcustom org-latex-to-mathml-convert-command nil
3728 "Command to convert LaTeX fragments to MathML.
3729 Replace format-specifiers in the command as noted below and use
3730 `shell-command' to convert LaTeX to MathML.
3731 %j: Executable file in fully expanded form as specified by
3732 `org-latex-to-mathml-jar-file'.
3733 %I: Input LaTeX file in fully expanded form
3734 %o: Output MathML file
3735 This command is used by `org-create-math-formula'.
3737 When using MathToWeb as the converter, set this to
3738 \"java -jar %j -unicode -force -df %o %I\"."
3739 :group 'org-latex
3740 :version "24.1"
3741 :type '(choice
3742 (const :tag "None" nil)
3743 (string :tag "\nShell command")))
3745 (defcustom org-latex-create-formula-image-program 'dvipng
3746 "Program to convert LaTeX fragments with.
3748 dvipng Process the LaTeX fragments to dvi file, then convert
3749 dvi files to png files using dvipng.
3750 This will also include processing of non-math environments.
3751 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3752 to convert pdf files to png files"
3753 :group 'org-latex
3754 :version "24.1"
3755 :type '(choice
3756 (const :tag "dvipng" dvipng)
3757 (const :tag "imagemagick" imagemagick)))
3759 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3760 "Path to store latex preview images.
3761 A relative path here creates many directories relative to the
3762 processed org files paths. An absolute path puts all preview
3763 images at the same place."
3764 :group 'org-latex
3765 :version "24.3"
3766 :type 'string)
3768 (defun org-format-latex-mathml-available-p ()
3769 "Return t if `org-latex-to-mathml-convert-command' is usable."
3770 (save-match-data
3771 (when (and (boundp 'org-latex-to-mathml-convert-command)
3772 org-latex-to-mathml-convert-command)
3773 (let ((executable (car (split-string
3774 org-latex-to-mathml-convert-command))))
3775 (when (executable-find executable)
3776 (if (string-match
3777 "%j" org-latex-to-mathml-convert-command)
3778 (file-readable-p org-latex-to-mathml-jar-file)
3779 t))))))
3781 (defcustom org-format-latex-header "\\documentclass{article}
3782 \\usepackage[usenames]{color}
3783 \\usepackage{amsmath}
3784 \\usepackage[mathscr]{eucal}
3785 \[PACKAGES]
3786 \[DEFAULT-PACKAGES]
3787 \\pagestyle{empty} % do not remove
3788 % The settings below are copied from fullpage.sty
3789 \\setlength{\\textwidth}{\\paperwidth}
3790 \\addtolength{\\textwidth}{-3cm}
3791 \\setlength{\\oddsidemargin}{1.5cm}
3792 \\addtolength{\\oddsidemargin}{-2.54cm}
3793 \\setlength{\\evensidemargin}{\\oddsidemargin}
3794 \\setlength{\\textheight}{\\paperheight}
3795 \\addtolength{\\textheight}{-\\headheight}
3796 \\addtolength{\\textheight}{-\\headsep}
3797 \\addtolength{\\textheight}{-\\footskip}
3798 \\addtolength{\\textheight}{-3cm}
3799 \\setlength{\\topmargin}{1.5cm}
3800 \\addtolength{\\topmargin}{-2.54cm}"
3801 "The document header used for processing LaTeX fragments.
3802 It is imperative that this header make sure that no page number
3803 appears on the page. The package defined in the variables
3804 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3805 will either replace the placeholder \"[PACKAGES]\" in this
3806 header, or they will be appended."
3807 :group 'org-latex
3808 :type 'string)
3810 (defun org-set-packages-alist (var val)
3811 "Set the packages alist and make sure it has 3 elements per entry."
3812 (set var (mapcar (lambda (x)
3813 (if (and (consp x) (= (length x) 2))
3814 (list (car x) (nth 1 x) t)
3816 val)))
3818 (defun org-get-packages-alist (var)
3819 "Get the packages alist and make sure it has 3 elements per entry."
3820 (mapcar (lambda (x)
3821 (if (and (consp x) (= (length x) 2))
3822 (list (car x) (nth 1 x) t)
3824 (default-value var)))
3826 (defcustom org-latex-default-packages-alist
3827 '(("AUTO" "inputenc" t)
3828 ("T1" "fontenc" t)
3829 ("" "fixltx2e" nil)
3830 ("" "graphicx" t)
3831 ("" "longtable" nil)
3832 ("" "float" nil)
3833 ("" "wrapfig" nil)
3834 ("normalem" "ulem" t)
3835 ("" "textcomp" t)
3836 ("" "marvosym" t)
3837 ("" "wasysym" t)
3838 ("" "amssymb" t)
3839 ("" "amstext" nil)
3840 ("" "hyperref" nil)
3841 "\\tolerance=1000")
3842 "Alist of default packages to be inserted in the header.
3844 Change this only if one of the packages here causes an
3845 incompatibility with another package you are using.
3847 The packages in this list are needed by one part or another of
3848 Org mode to function properly:
3850 - inputenc, fontenc: for basic font and character selection
3851 - amstext: for subscript and superscript
3852 - textcomp, marvosymb, wasysym, amssymb: for various symbols used
3853 for interpreting the entities in `org-entities'. You can skip
3854 some of these packages if you don't use any of their symbols.
3855 - ulem: for underline and strike-through
3856 - graphicx: for including images
3857 - float, wrapfig: for figure placement
3858 - longtable: for long tables
3859 - hyperref: for cross references
3861 Therefore you should not modify this variable unless you know
3862 what you are doing. The one reason to change it anyway is that
3863 you might be loading some other package that conflicts with one
3864 of the default packages. Each cell is of the format
3865 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
3866 the package also needs to be included when compiling LaTeX
3867 snippets into images for inclusion into non-LaTeX output."
3868 :group 'org-latex
3869 :group 'org-export-latex
3870 :set 'org-set-packages-alist
3871 :get 'org-get-packages-alist
3872 :version "24.1"
3873 :type '(repeat
3874 (choice
3875 (list :tag "options/package pair"
3876 (string :tag "options")
3877 (string :tag "package")
3878 (boolean :tag "Snippet"))
3879 (string :tag "A line of LaTeX"))))
3881 (defcustom org-latex-packages-alist nil
3882 "Alist of packages to be inserted in every LaTeX header.
3884 These will be inserted after `org-latex-default-packages-alist'.
3885 Each cell is of the format:
3887 \(\"options\" \"package\" snippet-flag)
3889 SNIPPET-FLAG, when t, indicates that this package is also needed
3890 when turning LaTeX snippets into images for inclusion into
3891 non-LaTeX output.
3893 Make sure that you only list packages here which:
3895 - you want in every file
3896 - do not conflict with the setup in `org-format-latex-header'.
3897 - do not conflict with the default packages in
3898 `org-latex-default-packages-alist'."
3899 :group 'org-latex
3900 :group 'org-export-latex
3901 :set 'org-set-packages-alist
3902 :get 'org-get-packages-alist
3903 :type '(repeat
3904 (choice
3905 (list :tag "options/package pair"
3906 (string :tag "options")
3907 (string :tag "package")
3908 (boolean :tag "Snippet"))
3909 (string :tag "A line of LaTeX"))))
3911 (defgroup org-appearance nil
3912 "Settings for Org-mode appearance."
3913 :tag "Org Appearance"
3914 :group 'org)
3916 (defcustom org-level-color-stars-only nil
3917 "Non-nil means fontify only the stars in each headline.
3918 When nil, the entire headline is fontified.
3919 Changing it requires restart of `font-lock-mode' to become effective
3920 also in regions already fontified."
3921 :group 'org-appearance
3922 :type 'boolean)
3924 (defcustom org-hide-leading-stars nil
3925 "Non-nil means hide the first N-1 stars in a headline.
3926 This works by using the face `org-hide' for these stars. This
3927 face is white for a light background, and black for a dark
3928 background. You may have to customize the face `org-hide' to
3929 make this work.
3930 Changing it requires restart of `font-lock-mode' to become effective
3931 also in regions already fontified.
3932 You may also set this on a per-file basis by adding one of the following
3933 lines to the buffer:
3935 #+STARTUP: hidestars
3936 #+STARTUP: showstars"
3937 :group 'org-appearance
3938 :type 'boolean)
3940 (defcustom org-hidden-keywords nil
3941 "List of symbols corresponding to keywords to be hidden the org buffer.
3942 For example, a value '(title) for this list will make the document's title
3943 appear in the buffer without the initial #+TITLE: keyword."
3944 :group 'org-appearance
3945 :version "24.1"
3946 :type '(set (const :tag "#+AUTHOR" author)
3947 (const :tag "#+DATE" date)
3948 (const :tag "#+EMAIL" email)
3949 (const :tag "#+TITLE" title)))
3951 (defcustom org-custom-properties nil
3952 "List of properties (as strings) with a special meaning.
3953 The default use of these custom properties is to let the user
3954 hide them with `org-toggle-custom-properties-visibility'."
3955 :group 'org-properties
3956 :group 'org-appearance
3957 :version "24.3"
3958 :type '(repeat (string :tag "Property Name")))
3960 (defcustom org-fontify-done-headline nil
3961 "Non-nil means change the face of a headline if it is marked DONE.
3962 Normally, only the TODO/DONE keyword indicates the state of a headline.
3963 When this is non-nil, the headline after the keyword is set to the
3964 `org-headline-done' as an additional indication."
3965 :group 'org-appearance
3966 :type 'boolean)
3968 (defcustom org-fontify-emphasized-text t
3969 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3970 Changing this variable requires a restart of Emacs to take effect."
3971 :group 'org-appearance
3972 :type 'boolean)
3974 (defcustom org-fontify-whole-heading-line nil
3975 "Non-nil means fontify the whole line for headings.
3976 This is useful when setting a background color for the
3977 org-level-* faces."
3978 :group 'org-appearance
3979 :type 'boolean)
3981 (defcustom org-highlight-latex-and-related nil
3982 "Non-nil means highlight LaTeX related syntax in the buffer.
3983 When non nil, the value should be a list containing any of the
3984 following symbols:
3985 `latex' Highlight LaTeX snippets and environments.
3986 `script' Highlight subscript and superscript.
3987 `entities' Highlight entities."
3988 :group 'org-appearance
3989 :version "24.4"
3990 :package-version '(Org . "8.0")
3991 :type '(choice
3992 (const :tag "No highlighting" nil)
3993 (set :greedy t :tag "Highlight"
3994 (const :tag "LaTeX snippets and environments" latex)
3995 (const :tag "Subscript and superscript" script)
3996 (const :tag "Entities" entities))))
3998 (defcustom org-hide-emphasis-markers nil
3999 "Non-nil mean font-lock should hide the emphasis marker characters."
4000 :group 'org-appearance
4001 :type 'boolean)
4003 (defcustom org-pretty-entities nil
4004 "Non-nil means show entities as UTF8 characters.
4005 When nil, the \\name form remains in the buffer."
4006 :group 'org-appearance
4007 :version "24.1"
4008 :type 'boolean)
4010 (defcustom org-pretty-entities-include-sub-superscripts t
4011 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4012 :group 'org-appearance
4013 :version "24.1"
4014 :type 'boolean)
4016 (defvar org-emph-re nil
4017 "Regular expression for matching emphasis.
4018 After a match, the match groups contain these elements:
4019 0 The match of the full regular expression, including the characters
4020 before and after the proper match
4021 1 The character before the proper match, or empty at beginning of line
4022 2 The proper match, including the leading and trailing markers
4023 3 The leading marker like * or /, indicating the type of highlighting
4024 4 The text between the emphasis markers, not including the markers
4025 5 The character after the match, empty at the end of a line")
4026 (defvar org-verbatim-re nil
4027 "Regular expression for matching verbatim text.")
4028 (defvar org-emphasis-regexp-components) ; defined just below
4029 (defvar org-emphasis-alist) ; defined just below
4030 (defun org-set-emph-re (var val)
4031 "Set variable and compute the emphasis regular expression."
4032 (set var val)
4033 (when (and (boundp 'org-emphasis-alist)
4034 (boundp 'org-emphasis-regexp-components)
4035 org-emphasis-alist org-emphasis-regexp-components)
4036 (let* ((e org-emphasis-regexp-components)
4037 (pre (car e))
4038 (post (nth 1 e))
4039 (border (nth 2 e))
4040 (body (nth 3 e))
4041 (nl (nth 4 e))
4042 (body1 (concat body "*?"))
4043 (markers (mapconcat 'car org-emphasis-alist ""))
4044 (vmarkers (mapconcat
4045 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4046 org-emphasis-alist "")))
4047 ;; make sure special characters appear at the right position in the class
4048 (if (string-match "\\^" markers)
4049 (setq markers (concat (replace-match "" t t markers) "^")))
4050 (if (string-match "-" markers)
4051 (setq markers (concat (replace-match "" t t markers) "-")))
4052 (if (string-match "\\^" vmarkers)
4053 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4054 (if (string-match "-" vmarkers)
4055 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4056 (if (> nl 0)
4057 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4058 (int-to-string nl) "\\}")))
4059 ;; Make the regexp
4060 (setq org-emph-re
4061 (concat "\\([" pre "]\\|^\\)"
4062 "\\("
4063 "\\([" markers "]\\)"
4064 "\\("
4065 "[^" border "]\\|"
4066 "[^" border "]"
4067 body1
4068 "[^" border "]"
4069 "\\)"
4070 "\\3\\)"
4071 "\\([" post "]\\|$\\)"))
4072 (setq org-verbatim-re
4073 (concat "\\([" pre "]\\|^\\)"
4074 "\\("
4075 "\\([" vmarkers "]\\)"
4076 "\\("
4077 "[^" border "]\\|"
4078 "[^" border "]"
4079 body1
4080 "[^" border "]"
4081 "\\)"
4082 "\\3\\)"
4083 "\\([" post "]\\|$\\)")))))
4085 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4086 ;; set this option proved cumbersome. See this message/thread:
4087 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4088 (defvar org-emphasis-regexp-components
4089 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4090 "Components used to build the regular expression for emphasis.
4091 This is a list with five entries. Terminology: In an emphasis string
4092 like \" *strong word* \", we call the initial space PREMATCH, the final
4093 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4094 and \"trong wor\" is the body. The different components in this variable
4095 specify what is allowed/forbidden in each part:
4097 pre Chars allowed as prematch. Beginning of line will be allowed too.
4098 post Chars allowed as postmatch. End of line will be allowed too.
4099 border The chars *forbidden* as border characters.
4100 body-regexp A regexp like \".\" to match a body character. Don't use
4101 non-shy groups here, and don't allow newline here.
4102 newline The maximum number of newlines allowed in an emphasis exp.
4104 You need to reload Org or to restart Emacs after customizing this.")
4106 (defcustom org-emphasis-alist
4107 `(("*" bold)
4108 ("/" italic)
4109 ("_" underline)
4110 ("=" org-code verbatim)
4111 ("~" org-verbatim verbatim)
4112 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4113 "Alist of characters and faces to emphasize text.
4114 Text starting and ending with a special character will be emphasized,
4115 for example *bold*, _underlined_ and /italic/. This variable sets the
4116 marker characters and the face to be used by font-lock for highlighting
4117 in Org-mode Emacs buffers.
4119 You need to reload Org or to restart Emacs after customizing this."
4120 :group 'org-appearance
4121 :set 'org-set-emph-re
4122 :version "24.4"
4123 :package-version '(Org . "8.0")
4124 :type '(repeat
4125 (list
4126 (string :tag "Marker character")
4127 (choice
4128 (face :tag "Font-lock-face")
4129 (plist :tag "Face property list"))
4130 (option (const verbatim)))))
4132 (defvar org-protecting-blocks
4133 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4134 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4135 This is needed for font-lock setup.")
4137 ;;; Miscellaneous options
4139 (defgroup org-completion nil
4140 "Completion in Org-mode."
4141 :tag "Org Completion"
4142 :group 'org)
4144 (defcustom org-completion-use-ido nil
4145 "Non-nil means use ido completion wherever possible.
4146 Note that `ido-mode' must be active for this variable to be relevant.
4147 If you decide to turn this variable on, you might well want to turn off
4148 `org-outline-path-complete-in-steps'.
4149 See also `org-completion-use-iswitchb'."
4150 :group 'org-completion
4151 :type 'boolean)
4153 (defcustom org-completion-use-iswitchb nil
4154 "Non-nil means use iswitchb completion wherever possible.
4155 Note that `iswitchb-mode' must be active for this variable to be relevant.
4156 If you decide to turn this variable on, you might well want to turn off
4157 `org-outline-path-complete-in-steps'.
4158 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4159 :group 'org-completion
4160 :type 'boolean)
4162 (defcustom org-completion-fallback-command 'hippie-expand
4163 "The expansion command called by \\[pcomplete] in normal context.
4164 Normal means, no org-mode-specific context."
4165 :group 'org-completion
4166 :type 'function)
4168 ;;; Functions and variables from their packages
4169 ;; Declared here to avoid compiler warnings
4171 ;; XEmacs only
4172 (defvar outline-mode-menu-heading)
4173 (defvar outline-mode-menu-show)
4174 (defvar outline-mode-menu-hide)
4175 (defvar zmacs-regions) ; XEmacs regions
4177 ;; Emacs only
4178 (defvar mark-active)
4180 ;; Various packages
4181 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4182 (declare-function calendar-forward-day "cal-move" (arg))
4183 (declare-function calendar-goto-date "cal-move" (date))
4184 (declare-function calendar-goto-today "cal-move" ())
4185 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4186 (defvar calc-embedded-close-formula)
4187 (defvar calc-embedded-open-formula)
4188 (declare-function cdlatex-tab "ext:cdlatex" ())
4189 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4190 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4191 (defvar font-lock-unfontify-region-function)
4192 (declare-function iswitchb-read-buffer "iswitchb"
4193 (prompt &optional default require-match start matches-set))
4194 (defvar iswitchb-temp-buflist)
4195 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4196 (defvar org-agenda-tags-todo-honor-ignore-options)
4197 (declare-function org-agenda-skip "org-agenda" ())
4198 (declare-function
4199 org-agenda-format-item "org-agenda"
4200 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4201 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4202 (declare-function org-agenda-change-all-lines "org-agenda"
4203 (newhead hdmarker &optional fixface just-this))
4204 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4205 (declare-function org-agenda-maybe-redo "org-agenda" ())
4206 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4207 (beg end))
4208 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4209 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4210 "org-agenda" (&optional end))
4211 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4212 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4213 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4214 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4215 (declare-function org-indent-mode "org-indent" (&optional arg))
4216 (declare-function parse-time-string "parse-time" (string))
4217 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4218 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4219 (defvar remember-data-file)
4220 (defvar texmathp-why)
4221 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4222 (declare-function table--at-cell-p "table" (position &optional object at-column))
4224 (defvar org-latex-regexps)
4226 ;;; Autoload and prepare some org modules
4228 ;; Some table stuff that needs to be defined here, because it is used
4229 ;; by the functions setting up org-mode or checking for table context.
4231 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4232 "Detect an org-type or table-type table.")
4233 (defconst org-table-line-regexp "^[ \t]*|"
4234 "Detect an org-type table line.")
4235 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4236 "Detect an org-type table line.")
4237 (defconst org-table-hline-regexp "^[ \t]*|-"
4238 "Detect an org-type table hline.")
4239 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4240 "Detect a table-type table hline.")
4241 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4242 "Detect the first line outside a table when searching from within it.
4243 This works for both table types.")
4245 ;; Autoload the functions in org-table.el that are needed by functions here.
4247 (eval-and-compile
4248 (org-autoload "org-table"
4249 '(org-table-begin org-table-blank-field org-table-end)))
4251 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
4252 "Detect a #+TBLFM line.")
4254 ;;;###autoload
4255 (defun turn-on-orgtbl ()
4256 "Unconditionally turn on `orgtbl-mode'."
4257 (require 'org-table)
4258 (orgtbl-mode 1))
4260 (defun org-at-table-p (&optional table-type)
4261 "Return t if the cursor is inside an org-type table.
4262 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4263 (if org-enable-table-editor
4264 (save-excursion
4265 (beginning-of-line 1)
4266 (looking-at (if table-type org-table-any-line-regexp
4267 org-table-line-regexp)))
4268 nil))
4269 (defsubst org-table-p () (org-at-table-p))
4271 (defun org-at-table.el-p ()
4272 "Return t if and only if we are at a table.el table."
4273 (and (org-at-table-p 'any)
4274 (save-excursion
4275 (goto-char (org-table-begin 'any))
4276 (looking-at org-table1-hline-regexp))))
4278 (defun org-table-recognize-table.el ()
4279 "If there is a table.el table nearby, recognize it and move into it."
4280 (if org-table-tab-recognizes-table.el
4281 (if (org-at-table.el-p)
4282 (progn
4283 (beginning-of-line 1)
4284 (if (looking-at org-table-dataline-regexp)
4286 (if (looking-at org-table1-hline-regexp)
4287 (progn
4288 (beginning-of-line 2)
4289 (if (looking-at org-table-any-border-regexp)
4290 (beginning-of-line -1)))))
4291 (if (re-search-forward "|" (org-table-end t) t)
4292 (progn
4293 (require 'table)
4294 (if (table--at-cell-p (point))
4296 (message "recognizing table.el table...")
4297 (table-recognize-table)
4298 (message "recognizing table.el table...done")))
4299 (error "This should not happen"))
4301 nil)
4302 nil))
4304 (defun org-at-table-hline-p ()
4305 "Return t if the cursor is inside a hline in a table."
4306 (if org-enable-table-editor
4307 (save-excursion
4308 (beginning-of-line 1)
4309 (looking-at org-table-hline-regexp))
4310 nil))
4312 (defun org-table-map-tables (function &optional quietly)
4313 "Apply FUNCTION to the start of all tables in the buffer."
4314 (save-excursion
4315 (save-restriction
4316 (widen)
4317 (goto-char (point-min))
4318 (while (re-search-forward org-table-any-line-regexp nil t)
4319 (unless quietly
4320 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4321 (beginning-of-line 1)
4322 (when (and (looking-at org-table-line-regexp)
4323 ;; Exclude tables in src/example/verbatim/clocktable blocks
4324 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4325 (save-excursion (funcall function))
4326 (or (looking-at org-table-line-regexp)
4327 (forward-char 1)))
4328 (re-search-forward org-table-any-border-regexp nil 1))))
4329 (unless quietly (message "Mapping tables: done")))
4331 ;; Declare and autoload functions from org-agenda.el
4333 (eval-and-compile
4334 (org-autoload "org-agenda"
4335 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4337 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4338 (declare-function org-clock-update-mode-line "org-clock" ())
4339 (declare-function org-resolve-clocks "org-clock"
4340 (&optional also-non-dangling-p prompt last-valid))
4342 (defun org-at-TBLFM-p (&optional pos)
4343 "Return t when point (or POS) is in #+TBLFM line."
4344 (save-excursion
4345 (let ((pos pos)))
4346 (goto-char (or pos (point)))
4347 (beginning-of-line 1)
4348 (looking-at org-TBLFM-regexp)))
4350 (defvar org-clock-start-time)
4351 (defvar org-clock-marker (make-marker)
4352 "Marker recording the last clock-in.")
4353 (defvar org-clock-hd-marker (make-marker)
4354 "Marker recording the last clock-in, but the headline position.")
4355 (defvar org-clock-heading ""
4356 "The heading of the current clock entry.")
4357 (defun org-clock-is-active ()
4358 "Return the buffer where the clock is currently running.
4359 Return nil if no clock is running."
4360 (marker-buffer org-clock-marker))
4362 (eval-and-compile
4363 (org-autoload "org-clock" '(org-clock-remove-overlays
4364 org-clock-update-time-maybe
4365 org-clocktable-shift)))
4367 (defun org-check-running-clock ()
4368 "Check if the current buffer contains the running clock.
4369 If yes, offer to stop it and to save the buffer with the changes."
4370 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4371 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4372 (buffer-name))))
4373 (org-clock-out)
4374 (when (y-or-n-p "Save changed buffer?")
4375 (save-buffer))))
4377 (defun org-clocktable-try-shift (dir n)
4378 "Check if this line starts a clock table, if yes, shift the time block."
4379 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4380 (org-clocktable-shift dir n)))
4382 ;;;###autoload
4383 (defun org-clock-persistence-insinuate ()
4384 "Set up hooks for clock persistence."
4385 (require 'org-clock)
4386 (add-hook 'org-mode-hook 'org-clock-load)
4387 (add-hook 'kill-emacs-hook 'org-clock-save))
4389 ;; Define the variable already here, to make sure we have it.
4390 (defvar org-indent-mode nil
4391 "Non-nil if Org-Indent mode is enabled.
4392 Use the command `org-indent-mode' to change this variable.")
4394 ;; Autoload archiving code
4395 ;; The stuff that is needed for cycling and tags has to be defined here.
4397 (defgroup org-archive nil
4398 "Options concerning archiving in Org-mode."
4399 :tag "Org Archive"
4400 :group 'org-structure)
4402 (defcustom org-archive-location "%s_archive::"
4403 "The location where subtrees should be archived.
4405 The value of this variable is a string, consisting of two parts,
4406 separated by a double-colon. The first part is a filename and
4407 the second part is a headline.
4409 When the filename is omitted, archiving happens in the same file.
4410 %s in the filename will be replaced by the current file
4411 name (without the directory part). Archiving to a different file
4412 is useful to keep archived entries from contributing to the
4413 Org-mode Agenda.
4415 The archived entries will be filed as subtrees of the specified
4416 headline. When the headline is omitted, the subtrees are simply
4417 filed away at the end of the file, as top-level entries. Also in
4418 the heading you can use %s to represent the file name, this can be
4419 useful when using the same archive for a number of different files.
4421 Here are a few examples:
4422 \"%s_archive::\"
4423 If the current file is Projects.org, archive in file
4424 Projects.org_archive, as top-level trees. This is the default.
4426 \"::* Archived Tasks\"
4427 Archive in the current file, under the top-level headline
4428 \"* Archived Tasks\".
4430 \"~/org/archive.org::\"
4431 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4433 \"~/org/archive.org::* From %s\"
4434 Archive in file ~/org/archive.org (absolute path), under headlines
4435 \"From FILENAME\" where file name is the current file name.
4437 \"~/org/datetree.org::datetree/* Finished Tasks\"
4438 The \"datetree/\" string is special, signifying to archive
4439 items to the datetree. Items are placed in either the CLOSED
4440 date of the item, or the current date if there is no CLOSED date.
4441 The heading will be a subentry to the current date. There doesn't
4442 need to be a heading, but there always needs to be a slash after
4443 datetree. For example, to store archived items directly in the
4444 datetree, use \"~/org/datetree.org::datetree/\".
4446 \"basement::** Finished Tasks\"
4447 Archive in file ./basement (relative path), as level 3 trees
4448 below the level 2 heading \"** Finished Tasks\".
4450 You may set this option on a per-file basis by adding to the buffer a
4451 line like
4453 #+ARCHIVE: basement::** Finished Tasks
4455 You may also define it locally for a subtree by setting an ARCHIVE property
4456 in the entry. If such a property is found in an entry, or anywhere up
4457 the hierarchy, it will be used."
4458 :group 'org-archive
4459 :type 'string)
4461 (defcustom org-archive-tag "ARCHIVE"
4462 "The tag that marks a subtree as archived.
4463 An archived subtree does not open during visibility cycling, and does
4464 not contribute to the agenda listings.
4465 After changing this, font-lock must be restarted in the relevant buffers to
4466 get the proper fontification."
4467 :group 'org-archive
4468 :group 'org-keywords
4469 :type 'string)
4471 (defcustom org-agenda-skip-archived-trees t
4472 "Non-nil means the agenda will skip any items located in archived trees.
4473 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4474 variable is no longer recommended, you should leave it at the value t.
4475 Instead, use the key `v' to cycle the archives-mode in the agenda."
4476 :group 'org-archive
4477 :group 'org-agenda-skip
4478 :type 'boolean)
4480 (defcustom org-columns-skip-archived-trees t
4481 "Non-nil means ignore archived trees when creating column view."
4482 :group 'org-archive
4483 :group 'org-properties
4484 :type 'boolean)
4486 (defcustom org-cycle-open-archived-trees nil
4487 "Non-nil means `org-cycle' will open archived trees.
4488 An archived tree is a tree marked with the tag ARCHIVE.
4489 When nil, archived trees will stay folded. You can still open them with
4490 normal outline commands like `show-all', but not with the cycling commands."
4491 :group 'org-archive
4492 :group 'org-cycle
4493 :type 'boolean)
4495 (defcustom org-sparse-tree-open-archived-trees nil
4496 "Non-nil means sparse tree construction shows matches in archived trees.
4497 When nil, matches in these trees are highlighted, but the trees are kept in
4498 collapsed state."
4499 :group 'org-archive
4500 :group 'org-sparse-trees
4501 :type 'boolean)
4503 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4504 "The default date type when building a sparse tree.
4505 When this is nil, a date is a scheduled or a deadline timestamp.
4506 Otherwise, these types are allowed:
4508 all: all timestamps
4509 active: only active timestamps (<...>)
4510 inactive: only inactive timestamps (<...)
4511 scheduled: only scheduled timestamps
4512 deadline: only deadline timestamps"
4513 :type '(choice (const :tag "Scheduled or deadline" scheduled-or-deadline)
4514 (const :tag "All timestamps" all)
4515 (const :tag "Only active timestamps" active)
4516 (const :tag "Only inactive timestamps" inactive)
4517 (const :tag "Only scheduled timestamps" scheduled)
4518 (const :tag "Only deadline timestamps" deadline)
4519 (const :tag "Only closed timestamps" closed))
4520 :version "24.3"
4521 :group 'org-sparse-trees)
4523 (defun org-cycle-hide-archived-subtrees (state)
4524 "Re-hide all archived subtrees after a visibility state change."
4525 (when (and (not org-cycle-open-archived-trees)
4526 (not (memq state '(overview folded))))
4527 (save-excursion
4528 (let* ((globalp (memq state '(contents all)))
4529 (beg (if globalp (point-min) (point)))
4530 (end (if globalp (point-max) (org-end-of-subtree t))))
4531 (org-hide-archived-subtrees beg end)
4532 (goto-char beg)
4533 (if (looking-at (concat ".*:" org-archive-tag ":"))
4534 (message "%s" (substitute-command-keys
4535 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4537 (defun org-force-cycle-archived ()
4538 "Cycle subtree even if it is archived."
4539 (interactive)
4540 (setq this-command 'org-cycle)
4541 (let ((org-cycle-open-archived-trees t))
4542 (call-interactively 'org-cycle)))
4544 (defun org-hide-archived-subtrees (beg end)
4545 "Re-hide all archived subtrees after a visibility state change."
4546 (save-excursion
4547 (let* ((re (concat ":" org-archive-tag ":")))
4548 (goto-char beg)
4549 (while (re-search-forward re end t)
4550 (when (org-at-heading-p)
4551 (org-flag-subtree t)
4552 (org-end-of-subtree t))))))
4554 (declare-function outline-end-of-heading "outline" ())
4555 (declare-function outline-flag-region "outline" (from to flag))
4556 (defun org-flag-subtree (flag)
4557 (save-excursion
4558 (org-back-to-heading t)
4559 (outline-end-of-heading)
4560 (outline-flag-region (point)
4561 (progn (org-end-of-subtree t) (point))
4562 flag)))
4564 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4566 (eval-and-compile
4567 (org-autoload "org-archive"
4568 '(org-add-archive-files)))
4570 ;; Autoload Column View Code
4572 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4573 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4574 (declare-function org-columns-compute "org-colview" (property))
4576 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4577 '(org-columns-number-to-string
4578 org-columns-get-format-and-top-level
4579 org-columns-compute
4580 org-columns-remove-overlays))
4582 ;; Autoload ID code
4584 (declare-function org-id-store-link "org-id")
4585 (declare-function org-id-locations-load "org-id")
4586 (declare-function org-id-locations-save "org-id")
4587 (defvar org-id-track-globally)
4588 (org-autoload "org-id"
4589 '(org-id-new
4590 org-id-copy
4591 org-id-get-with-outline-path-completion
4592 org-id-get-with-outline-drilling))
4594 ;;; Variables for pre-computed regular expressions, all buffer local
4596 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4597 "Matches first line of a hidden block.")
4598 (make-variable-buffer-local 'org-drawer-regexp)
4599 (defvar org-todo-regexp nil
4600 "Matches any of the TODO state keywords.")
4601 (make-variable-buffer-local 'org-todo-regexp)
4602 (defvar org-not-done-regexp nil
4603 "Matches any of the TODO state keywords except the last one.")
4604 (make-variable-buffer-local 'org-not-done-regexp)
4605 (defvar org-not-done-heading-regexp nil
4606 "Matches a TODO headline that is not done.")
4607 (make-variable-buffer-local 'org-not-done-regexp)
4608 (defvar org-todo-line-regexp nil
4609 "Matches a headline and puts TODO state into group 2 if present.")
4610 (make-variable-buffer-local 'org-todo-line-regexp)
4611 (defvar org-complex-heading-regexp nil
4612 "Matches a headline and puts everything into groups:
4613 group 1: the stars
4614 group 2: The todo keyword, maybe
4615 group 3: Priority cookie
4616 group 4: True headline
4617 group 5: Tags")
4618 (make-variable-buffer-local 'org-complex-heading-regexp)
4619 (defvar org-complex-heading-regexp-format nil
4620 "Printf format to make regexp to match an exact headline.
4621 This regexp will match the headline of any node which has the
4622 exact headline text that is put into the format, but may have any
4623 TODO state, priority and tags.")
4624 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4625 (defvar org-todo-line-tags-regexp nil
4626 "Matches a headline and puts TODO state into group 2 if present.
4627 Also put tags into group 4 if tags are present.")
4628 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4629 (defvar org-ds-keyword-length 12
4630 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4631 (make-variable-buffer-local 'org-ds-keyword-length)
4632 (defvar org-deadline-regexp nil
4633 "Matches the DEADLINE keyword.")
4634 (make-variable-buffer-local 'org-deadline-regexp)
4635 (defvar org-deadline-time-regexp nil
4636 "Matches the DEADLINE keyword together with a time stamp.")
4637 (make-variable-buffer-local 'org-deadline-time-regexp)
4638 (defvar org-deadline-time-hour-regexp nil
4639 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4640 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4641 (defvar org-deadline-line-regexp nil
4642 "Matches the DEADLINE keyword and the rest of the line.")
4643 (make-variable-buffer-local 'org-deadline-line-regexp)
4644 (defvar org-scheduled-regexp nil
4645 "Matches the SCHEDULED keyword.")
4646 (make-variable-buffer-local 'org-scheduled-regexp)
4647 (defvar org-scheduled-time-regexp nil
4648 "Matches the SCHEDULED keyword together with a time stamp.")
4649 (make-variable-buffer-local 'org-scheduled-time-regexp)
4650 (defvar org-scheduled-time-hour-regexp nil
4651 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4652 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4653 (defvar org-closed-time-regexp nil
4654 "Matches the CLOSED keyword together with a time stamp.")
4655 (make-variable-buffer-local 'org-closed-time-regexp)
4657 (defvar org-keyword-time-regexp nil
4658 "Matches any of the 4 keywords, together with the time stamp.")
4659 (make-variable-buffer-local 'org-keyword-time-regexp)
4660 (defvar org-keyword-time-not-clock-regexp nil
4661 "Matches any of the 3 keywords, together with the time stamp.")
4662 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4663 (defvar org-maybe-keyword-time-regexp nil
4664 "Matches a timestamp, possibly preceded by a keyword.")
4665 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4666 (defvar org-all-time-keywords nil
4667 "List of time keywords.")
4668 (make-variable-buffer-local 'org-all-time-keywords)
4670 (defconst org-plain-time-of-day-regexp
4671 (concat
4672 "\\(\\<[012]?[0-9]"
4673 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4674 "\\(--?"
4675 "\\(\\<[012]?[0-9]"
4676 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4677 "\\)?")
4678 "Regular expression to match a plain time or time range.
4679 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4680 groups carry important information:
4681 0 the full match
4682 1 the first time, range or not
4683 8 the second time, if it is a range.")
4685 (defconst org-plain-time-extension-regexp
4686 (concat
4687 "\\(\\<[012]?[0-9]"
4688 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4689 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4690 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4691 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4692 groups carry important information:
4693 0 the full match
4694 7 hours of duration
4695 9 minutes of duration")
4697 (defconst org-stamp-time-of-day-regexp
4698 (concat
4699 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4700 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4701 "\\(--?"
4702 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4703 "Regular expression to match a timestamp time or time range.
4704 After a match, the following groups carry important information:
4705 0 the full match
4706 1 date plus weekday, for back referencing to make sure both times are on the same day
4707 2 the first time, range or not
4708 4 the second time, if it is a range.")
4710 (defconst org-startup-options
4711 '(("fold" org-startup-folded t)
4712 ("overview" org-startup-folded t)
4713 ("nofold" org-startup-folded nil)
4714 ("showall" org-startup-folded nil)
4715 ("showeverything" org-startup-folded showeverything)
4716 ("content" org-startup-folded content)
4717 ("indent" org-startup-indented t)
4718 ("noindent" org-startup-indented nil)
4719 ("hidestars" org-hide-leading-stars t)
4720 ("showstars" org-hide-leading-stars nil)
4721 ("odd" org-odd-levels-only t)
4722 ("oddeven" org-odd-levels-only nil)
4723 ("align" org-startup-align-all-tables t)
4724 ("noalign" org-startup-align-all-tables nil)
4725 ("inlineimages" org-startup-with-inline-images t)
4726 ("noinlineimages" org-startup-with-inline-images nil)
4727 ("latexpreview" org-startup-with-latex-preview t)
4728 ("nolatexpreview" org-startup-with-latex-preview nil)
4729 ("customtime" org-display-custom-times t)
4730 ("logdone" org-log-done time)
4731 ("lognotedone" org-log-done note)
4732 ("nologdone" org-log-done nil)
4733 ("lognoteclock-out" org-log-note-clock-out t)
4734 ("nolognoteclock-out" org-log-note-clock-out nil)
4735 ("logrepeat" org-log-repeat state)
4736 ("lognoterepeat" org-log-repeat note)
4737 ("logdrawer" org-log-into-drawer t)
4738 ("nologdrawer" org-log-into-drawer nil)
4739 ("logstatesreversed" org-log-states-order-reversed t)
4740 ("nologstatesreversed" org-log-states-order-reversed nil)
4741 ("nologrepeat" org-log-repeat nil)
4742 ("logreschedule" org-log-reschedule time)
4743 ("lognotereschedule" org-log-reschedule note)
4744 ("nologreschedule" org-log-reschedule nil)
4745 ("logredeadline" org-log-redeadline time)
4746 ("lognoteredeadline" org-log-redeadline note)
4747 ("nologredeadline" org-log-redeadline nil)
4748 ("logrefile" org-log-refile time)
4749 ("lognoterefile" org-log-refile note)
4750 ("nologrefile" org-log-refile nil)
4751 ("fninline" org-footnote-define-inline t)
4752 ("nofninline" org-footnote-define-inline nil)
4753 ("fnlocal" org-footnote-section nil)
4754 ("fnauto" org-footnote-auto-label t)
4755 ("fnprompt" org-footnote-auto-label nil)
4756 ("fnconfirm" org-footnote-auto-label confirm)
4757 ("fnplain" org-footnote-auto-label plain)
4758 ("fnadjust" org-footnote-auto-adjust t)
4759 ("nofnadjust" org-footnote-auto-adjust nil)
4760 ("constcgs" constants-unit-system cgs)
4761 ("constSI" constants-unit-system SI)
4762 ("noptag" org-tag-persistent-alist nil)
4763 ("hideblocks" org-hide-block-startup t)
4764 ("nohideblocks" org-hide-block-startup nil)
4765 ("beamer" org-startup-with-beamer-mode t)
4766 ("entitiespretty" org-pretty-entities t)
4767 ("entitiesplain" org-pretty-entities nil))
4768 "Variable associated with STARTUP options for org-mode.
4769 Each element is a list of three items: the startup options (as written
4770 in the #+STARTUP line), the corresponding variable, and the value to set
4771 this variable to if the option is found. An optional forth element PUSH
4772 means to push this value onto the list in the variable.")
4774 (defun org-update-property-plist (key val props)
4775 "Update PROPS with KEY and VAL."
4776 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4777 (key (if appending (substring key 0 (- (length key) 1)) key))
4778 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4779 (previous (cdr (assoc key props))))
4780 (if appending
4781 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4782 (cons (cons key val) remainder))))
4784 (defconst org-block-regexp
4785 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4786 "Regular expression for hiding blocks.")
4787 (defconst org-heading-keyword-regexp-format
4788 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4789 "Printf format for a regexp matching a headline with some keyword.
4790 This regexp will match the headline of any node which has the
4791 exact keyword that is put into the format. The keyword isn't in
4792 any group by default, but the stars and the body are.")
4793 (defconst org-heading-keyword-maybe-regexp-format
4794 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4795 "Printf format for a regexp matching a headline, possibly with some keyword.
4796 This regexp can match any headline with the specified keyword, or
4797 without a keyword. The keyword isn't in any group by default,
4798 but the stars and the body are.")
4800 (defcustom org-group-tags t
4801 "When non-nil (the default), use group tags.
4802 This can be turned on/off through `org-toggle-tags-groups'."
4803 :group 'org-tags
4804 :group 'org-startup
4805 :type 'boolean)
4807 (defun org-toggle-tags-groups ()
4808 "Toggle support for group tags.
4809 Support for group tags is controlled by the option
4810 `org-group-tags', which is non-nil by default."
4811 (interactive)
4812 (setq org-group-tags (not org-group-tags))
4813 (cond ((and (derived-mode-p 'org-agenda-mode)
4814 org-group-tags)
4815 (org-agenda-redo))
4816 ((derived-mode-p 'org-mode)
4817 (let ((org-inhibit-startup t)) (org-mode))))
4818 (message "Groups tags support has been turned %s"
4819 (if org-group-tags "on" "off")))
4821 (defun org-set-regexps-and-options-for-tags ()
4822 "Precompute variables used for tags."
4823 (when (derived-mode-p 'org-mode)
4824 (org-set-local 'org-file-tags nil)
4825 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4826 (splitre "[ \t]+")
4827 (start 0)
4828 tags ftags key value)
4829 (save-excursion
4830 (save-restriction
4831 (widen)
4832 (goto-char (point-min))
4833 (while (re-search-forward re nil t)
4834 (setq key (upcase (org-match-string-no-properties 1))
4835 value (org-match-string-no-properties 2))
4836 (if (stringp value) (setq value (org-trim value)))
4837 (cond
4838 ((equal key "TAGS")
4839 (setq tags (append tags (if tags '("\\n") nil)
4840 (org-split-string value splitre))))
4841 ((equal key "FILETAGS")
4842 (when (string-match "\\S-" value)
4843 (setq ftags
4844 (append
4845 ftags
4846 (apply 'append
4847 (mapcar (lambda (x) (org-split-string x ":"))
4848 (org-split-string value)))))))))))
4849 ;; Process the file tags.
4850 (and ftags (org-set-local 'org-file-tags
4851 (mapcar 'org-add-prop-inherited ftags)))
4852 (org-set-local 'org-tag-groups-alist nil)
4853 ;; Process the tags.
4854 (when (and (not tags) org-tag-alist)
4855 (setq tags
4856 (mapcar
4857 (lambda (tg) (cond ((eq (car tg) :startgroup) "{")
4858 ((eq (car tg) :endgroup) "}")
4859 ((eq (car tg) :grouptags) ":")
4860 ((eq (car tg) :newline) "\n")
4861 (t (concat (car tg)
4862 (if (characterp (cdr tg))
4863 (format "(%s)" (char-to-string (cdr tg))) "")))))
4864 org-tag-alist)))
4865 (let (e tgs g)
4866 (while (setq e (pop tags))
4867 (cond
4868 ((equal e "{")
4869 (progn (push '(:startgroup) tgs)
4870 (when (equal (nth 1 tags) ":")
4871 (push (list (replace-regexp-in-string
4872 "(.+)$" "" (nth 0 tags)))
4873 org-tag-groups-alist)
4874 (setq g 0))))
4875 ((equal e ":") (push '(:grouptags) tgs))
4876 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4877 ((equal e "\\n") (push '(:newline) tgs))
4878 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4879 (push (cons (match-string 1 e)
4880 (string-to-char (match-string 2 e))) tgs)
4881 (if (and g (> g 0))
4882 (setcar org-tag-groups-alist
4883 (append (car org-tag-groups-alist)
4884 (list (match-string 1 e)))))
4885 (if g (setq g (1+ g))))
4886 (t (push (list e) tgs)
4887 (if (and g (> g 0))
4888 (setcar org-tag-groups-alist
4889 (append (car org-tag-groups-alist) (list e))))
4890 (if g (setq g (1+ g))))))
4891 (org-set-local 'org-tag-alist nil)
4892 (while (setq e (pop tgs))
4893 (or (and (stringp (car e))
4894 (assoc (car e) org-tag-alist))
4895 (push e org-tag-alist)))
4896 ;; Return a list with tag variables
4897 (list org-file-tags org-tag-alist org-tag-groups-alist)))))
4899 (defvar org-ota nil)
4900 (defun org-set-regexps-and-options ()
4901 "Precompute regular expressions used in the current buffer."
4902 (when (derived-mode-p 'org-mode)
4903 (org-set-local 'org-todo-kwd-alist nil)
4904 (org-set-local 'org-todo-key-alist nil)
4905 (org-set-local 'org-todo-key-trigger nil)
4906 (org-set-local 'org-todo-keywords-1 nil)
4907 (org-set-local 'org-done-keywords nil)
4908 (org-set-local 'org-todo-heads nil)
4909 (org-set-local 'org-todo-sets nil)
4910 (org-set-local 'org-todo-log-states nil)
4911 (org-set-local 'org-file-properties nil)
4912 (let ((re (org-make-options-regexp
4913 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
4914 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4915 "SETUPFILE" "OPTIONS")
4916 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4917 (splitre "[ \t]+")
4918 (scripts org-use-sub-superscripts)
4919 kwds kws0 kwsa key log value cat arch const links hw dws
4920 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
4921 (start 0))
4922 (save-excursion
4923 (save-restriction
4924 (widen)
4925 (goto-char (point-min))
4926 (while
4927 (or (and
4928 ext-setup-or-nil
4929 (not org-ota)
4930 (let (ret)
4931 (with-temp-buffer
4932 (insert ext-setup-or-nil)
4933 (let ((major-mode 'org-mode) org-ota)
4934 (setq ret (save-match-data
4935 (org-set-regexps-and-options-for-tags)))))
4936 ;; Append setupfile tags to existing tags
4937 (setq org-ota t)
4938 (setq org-file-tags
4939 (delq nil (append org-file-tags (nth 0 ret)))
4940 org-tag-alist
4941 (delq nil (append org-tag-alist (nth 1 ret)))
4942 org-tag-groups-alist
4943 (delq nil (append org-tag-groups-alist (nth 2 ret))))))
4944 (and ext-setup-or-nil
4945 (string-match re ext-setup-or-nil start)
4946 (setq start (match-end 0)))
4947 (and (setq ext-setup-or-nil nil start 0)
4948 (re-search-forward re nil t)))
4949 (setq key (upcase (match-string 1 ext-setup-or-nil))
4950 value (org-match-string-no-properties 2 ext-setup-or-nil))
4951 (if (stringp value) (setq value (org-trim value)))
4952 (cond
4953 ((equal key "CATEGORY")
4954 (setq cat value))
4955 ((member key '("SEQ_TODO" "TODO"))
4956 (push (cons 'sequence (org-split-string value splitre)) kwds))
4957 ((equal key "TYP_TODO")
4958 (push (cons 'type (org-split-string value splitre)) kwds))
4959 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4960 ;; general TODO-like setup
4961 (push (cons (intern (downcase (match-string 1 key)))
4962 (org-split-string value splitre)) kwds))
4963 ((equal key "COLUMNS")
4964 (org-set-local 'org-columns-default-format value))
4965 ((equal key "LINK")
4966 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4967 (push (cons (match-string 1 value)
4968 (org-trim (match-string 2 value)))
4969 links)))
4970 ((equal key "PRIORITIES")
4971 (setq prio (org-split-string value " +")))
4972 ((equal key "PROPERTY")
4973 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4974 (setq props (org-update-property-plist (match-string 1 value)
4975 (match-string 2 value)
4976 props))))
4977 ((equal key "DRAWERS")
4978 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4979 ((equal key "CONSTANTS")
4980 (org-table-set-constants))
4981 ((equal key "STARTUP")
4982 (let ((opts (org-split-string value splitre))
4983 l var val)
4984 (while (setq l (pop opts))
4985 (when (setq l (assoc l org-startup-options))
4986 (setq var (nth 1 l) val (nth 2 l))
4987 (if (not (nth 3 l))
4988 (set (make-local-variable var) val)
4989 (if (not (listp (symbol-value var)))
4990 (set (make-local-variable var) nil))
4991 (set (make-local-variable var) (symbol-value var))
4992 (add-to-list var val))))))
4993 ((equal key "ARCHIVE")
4994 (setq arch value)
4995 (remove-text-properties 0 (length arch)
4996 '(face t fontified t) arch))
4997 ((equal key "OPTIONS")
4998 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4999 (setq scripts (read (match-string 2 value)))))
5000 ((and (equal key "SETUPFILE")
5001 ;; Prevent checking in Gnus messages
5002 (not buffer-read-only))
5003 (setq setup-contents (org-file-contents
5004 (expand-file-name
5005 (org-remove-double-quotes value))
5006 'noerror))
5007 (if (not ext-setup-or-nil)
5008 (setq ext-setup-or-nil setup-contents start 0)
5009 (setq ext-setup-or-nil
5010 (concat (substring ext-setup-or-nil 0 start)
5011 "\n" setup-contents "\n"
5012 (substring ext-setup-or-nil start)))))))
5013 ;; search for property blocks
5014 (goto-char (point-min))
5015 (while (re-search-forward org-block-regexp nil t)
5016 (when (equal "PROPERTY" (upcase (match-string 1)))
5017 (setq value (replace-regexp-in-string
5018 "[\n\r]" " " (match-string 4)))
5019 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
5020 (setq props (org-update-property-plist (match-string 1 value)
5021 (match-string 2 value)
5022 props)))))))
5023 (org-set-local 'org-use-sub-superscripts scripts)
5024 (when cat
5025 (org-set-local 'org-category (intern cat))
5026 (push (cons "CATEGORY" cat) props))
5027 (when prio
5028 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
5029 (setq prio (mapcar 'string-to-char prio))
5030 (org-set-local 'org-highest-priority (nth 0 prio))
5031 (org-set-local 'org-lowest-priority (nth 1 prio))
5032 (org-set-local 'org-default-priority (nth 2 prio)))
5033 (and props (org-set-local 'org-file-properties (nreverse props)))
5034 (and drawers (org-set-local 'org-drawers drawers))
5035 (and arch (org-set-local 'org-archive-location arch))
5036 (and links (setq org-link-abbrev-alist-local (nreverse links)))
5037 ;; Process the TODO keywords
5038 (unless kwds
5039 ;; Use the global values as if they had been given locally.
5040 (setq kwds (default-value 'org-todo-keywords))
5041 (if (stringp (car kwds))
5042 (setq kwds (list (cons org-todo-interpretation
5043 (default-value 'org-todo-keywords)))))
5044 (setq kwds (reverse kwds)))
5045 (setq kwds (nreverse kwds))
5046 (let (inter kws kw)
5047 (while (setq kws (pop kwds))
5048 (let ((kws (or
5049 (run-hook-with-args-until-success
5050 'org-todo-setup-filter-hook kws)
5051 kws)))
5052 (setq inter (pop kws) sep (member "|" kws)
5053 kws0 (delete "|" (copy-sequence kws))
5054 kwsa nil
5055 kws1 (mapcar
5056 (lambda (x)
5057 ;; 1 2
5058 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
5059 (progn
5060 (setq kw (match-string 1 x)
5061 key (and (match-end 2) (match-string 2 x))
5062 log (org-extract-log-state-settings x))
5063 (push (cons kw (and key (string-to-char key))) kwsa)
5064 (and log (push log org-todo-log-states))
5066 (error "Invalid TODO keyword %s" x)))
5067 kws0)
5068 kwsa (if kwsa (append '((:startgroup))
5069 (nreverse kwsa)
5070 '((:endgroup))))
5071 hw (car kws1)
5072 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
5073 tail (list inter hw (car dws) (org-last dws))))
5074 (add-to-list 'org-todo-heads hw 'append)
5075 (push kws1 org-todo-sets)
5076 (setq org-done-keywords (append org-done-keywords dws nil))
5077 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
5078 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
5079 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
5080 (setq org-todo-sets (nreverse org-todo-sets)
5081 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5082 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
5083 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
5084 ;; Compute the regular expressions and other local variables.
5085 ;; Using `org-outline-regexp-bol' would complicate them much,
5086 ;; because of the fixed white space at the end of that string.
5087 (if (not org-done-keywords)
5088 (setq org-done-keywords (and org-todo-keywords-1
5089 (list (org-last org-todo-keywords-1)))))
5090 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5091 (length org-scheduled-string)
5092 (length org-clock-string)
5093 (length org-closed-string)))
5094 org-drawer-regexp
5095 (concat "^[ \t]*:\\("
5096 (mapconcat 'regexp-quote org-drawers "\\|")
5097 "\\):[ \t]*$")
5098 org-not-done-keywords
5099 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5100 org-todo-regexp
5101 (concat "\\("
5102 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5103 "\\)")
5104 org-not-done-regexp
5105 (concat "\\("
5106 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5107 "\\)")
5108 org-not-done-heading-regexp
5109 (format org-heading-keyword-regexp-format org-not-done-regexp)
5110 org-todo-line-regexp
5111 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5112 org-complex-heading-regexp
5113 (concat "^\\(\\*+\\)"
5114 "\\(?: +" org-todo-regexp "\\)?"
5115 "\\(?: +\\(\\[#.\\]\\)\\)?"
5116 "\\(?: +\\(.*?\\)\\)??"
5117 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5118 "[ \t]*$")
5119 org-complex-heading-regexp-format
5120 (concat "^\\(\\*+\\)"
5121 "\\(?: +" org-todo-regexp "\\)?"
5122 "\\(?: +\\(\\[#.\\]\\)\\)?"
5123 "\\(?: +"
5124 ;; Stats cookies can be stuck to body.
5125 "\\(?:\\[[0-9%%/]+\\] *\\)?"
5126 "\\(%s\\)"
5127 "\\(?: *\\[[0-9%%/]+\\]\\)?"
5128 "\\)"
5129 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5130 "[ \t]*$")
5131 org-todo-line-tags-regexp
5132 (concat "^\\(\\*+\\)"
5133 "\\(?: +" org-todo-regexp "\\)?"
5134 "\\(?: +\\(.*?\\)\\)??"
5135 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5136 "[ \t]*$")
5137 org-deadline-regexp (concat "\\<" org-deadline-string)
5138 org-deadline-time-regexp
5139 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5140 org-deadline-time-hour-regexp
5141 (concat "\\<" org-deadline-string
5142 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5143 org-deadline-line-regexp
5144 (concat "\\<\\(" org-deadline-string "\\).*")
5145 org-scheduled-regexp
5146 (concat "\\<" org-scheduled-string)
5147 org-scheduled-time-regexp
5148 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5149 org-scheduled-time-hour-regexp
5150 (concat "\\<" org-scheduled-string
5151 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5152 org-closed-time-regexp
5153 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5154 org-keyword-time-regexp
5155 (concat "\\<\\(" org-scheduled-string
5156 "\\|" org-deadline-string
5157 "\\|" org-closed-string
5158 "\\|" org-clock-string "\\)"
5159 " *[[<]\\([^]>]+\\)[]>]")
5160 org-keyword-time-not-clock-regexp
5161 (concat "\\<\\(" org-scheduled-string
5162 "\\|" org-deadline-string
5163 "\\|" org-closed-string
5164 "\\)"
5165 " *[[<]\\([^]>]+\\)[]>]")
5166 org-maybe-keyword-time-regexp
5167 (concat "\\(\\<\\(" org-scheduled-string
5168 "\\|" org-deadline-string
5169 "\\|" org-closed-string
5170 "\\|" org-clock-string "\\)\\)?"
5171 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5172 org-all-time-keywords
5173 (mapcar (lambda (w) (substring w 0 -1))
5174 (list org-scheduled-string org-deadline-string
5175 org-clock-string org-closed-string)))
5176 (setq org-ota nil)
5177 (org-compute-latex-and-related-regexp))))
5179 (defun org-file-contents (file &optional noerror)
5180 "Return the contents of FILE, as a string."
5181 (if (or (not file)
5182 (not (file-readable-p file)))
5183 (if noerror
5184 (message "Cannot read file \"%s\"" file)
5185 (error "Cannot read file \"%s\"" file))
5186 (with-temp-buffer
5187 (insert-file-contents file)
5188 (buffer-string))))
5190 (defun org-extract-log-state-settings (x)
5191 "Extract the log state setting from a TODO keyword string.
5192 This will extract info from a string like \"WAIT(w@/!)\"."
5193 (let (kw key log1 log2)
5194 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5195 (setq kw (match-string 1 x)
5196 key (and (match-end 2) (match-string 2 x))
5197 log1 (and (match-end 3) (match-string 3 x))
5198 log2 (and (match-end 4) (match-string 4 x)))
5199 (and (or log1 log2)
5200 (list kw
5201 (and log1 (if (equal log1 "!") 'time 'note))
5202 (and log2 (if (equal log2 "!") 'time 'note)))))))
5204 (defun org-remove-keyword-keys (list)
5205 "Remove a pair of parenthesis at the end of each string in LIST."
5206 (mapcar (lambda (x)
5207 (if (string-match "(.*)$" x)
5208 (substring x 0 (match-beginning 0))
5210 list))
5212 (defun org-assign-fast-keys (alist)
5213 "Assign fast keys to a keyword-key alist.
5214 Respect keys that are already there."
5215 (let (new e (alt ?0))
5216 (while (setq e (pop alist))
5217 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5218 (cdr e)) ;; Key already assigned.
5219 (push e new)
5220 (let ((clist (string-to-list (downcase (car e))))
5221 (used (append new alist)))
5222 (when (= (car clist) ?@)
5223 (pop clist))
5224 (while (and clist (rassoc (car clist) used))
5225 (pop clist))
5226 (unless clist
5227 (while (rassoc alt used)
5228 (incf alt)))
5229 (push (cons (car e) (or (car clist) alt)) new))))
5230 (nreverse new)))
5232 ;;; Some variables used in various places
5234 (defvar org-window-configuration nil
5235 "Used in various places to store a window configuration.")
5236 (defvar org-selected-window nil
5237 "Used in various places to store a window configuration.")
5238 (defvar org-finish-function nil
5239 "Function to be called when `C-c C-c' is used.
5240 This is for getting out of special buffers like capture.")
5243 ;; FIXME: Occasionally check by commenting these, to make sure
5244 ;; no other functions uses these, forgetting to let-bind them.
5245 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5246 (defvar org-last-state)
5247 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5249 ;; Defined somewhere in this file, but used before definition.
5250 (defvar org-entities) ;; defined in org-entities.el
5251 (defvar org-struct-menu)
5252 (defvar org-org-menu)
5253 (defvar org-tbl-menu)
5255 ;;;; Define the Org-mode
5257 ;; We use a before-change function to check if a table might need
5258 ;; an update.
5259 (defvar org-table-may-need-update t
5260 "Indicates that a table might need an update.
5261 This variable is set by `org-before-change-function'.
5262 `org-table-align' sets it back to nil.")
5263 (defun org-before-change-function (beg end)
5264 "Every change indicates that a table might need an update."
5265 (setq org-table-may-need-update t))
5266 (defvar org-mode-map)
5267 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5268 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5269 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5270 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5271 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5272 (defvar org-table-buffer-is-an nil)
5274 (defvar bidi-paragraph-direction)
5275 (defvar buffer-face-mode-face)
5277 (require 'outline)
5278 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5279 (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"))
5280 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5282 ;; Other stuff we need.
5283 (require 'time-date)
5284 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5285 (require 'easymenu)
5286 (require 'overlay)
5288 ;; (require 'org-macs) moved higher up in the file before it is first used
5289 (require 'org-entities)
5290 ;; (require 'org-compat) moved higher up in the file before it is first used
5291 (require 'org-faces)
5292 (require 'org-list)
5293 (require 'org-pcomplete)
5294 (require 'org-src)
5295 (require 'org-footnote)
5296 (require 'org-macro)
5298 ;; babel
5299 (require 'ob)
5301 ;;;###autoload
5302 (define-derived-mode org-mode outline-mode "Org"
5303 "Outline-based notes management and organizer, alias
5304 \"Carsten's outline-mode for keeping track of everything.\"
5306 Org-mode develops organizational tasks around a NOTES file which
5307 contains information about projects as plain text. Org-mode is
5308 implemented on top of outline-mode, which is ideal to keep the content
5309 of large files well structured. It supports ToDo items, deadlines and
5310 time stamps, which magically appear in the diary listing of the Emacs
5311 calendar. Tables are easily created with a built-in table editor.
5312 Plain text URL-like links connect to websites, emails (VM), Usenet
5313 messages (Gnus), BBDB entries, and any files related to the project.
5314 For printing and sharing of notes, an Org-mode file (or a part of it)
5315 can be exported as a structured ASCII or HTML file.
5317 The following commands are available:
5319 \\{org-mode-map}"
5321 ;; Get rid of Outline menus, they are not needed
5322 ;; Need to do this here because define-derived-mode sets up
5323 ;; the keymap so late. Still, it is a waste to call this each time
5324 ;; we switch another buffer into org-mode.
5325 (if (featurep 'xemacs)
5326 (when (boundp 'outline-mode-menu-heading)
5327 ;; Assume this is Greg's port, it uses easymenu
5328 (easy-menu-remove outline-mode-menu-heading)
5329 (easy-menu-remove outline-mode-menu-show)
5330 (easy-menu-remove outline-mode-menu-hide))
5331 (define-key org-mode-map [menu-bar headings] 'undefined)
5332 (define-key org-mode-map [menu-bar hide] 'undefined)
5333 (define-key org-mode-map [menu-bar show] 'undefined))
5335 (org-load-modules-maybe)
5336 (easy-menu-add org-org-menu)
5337 (easy-menu-add org-tbl-menu)
5338 (org-install-agenda-files-menu)
5339 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5340 (add-to-invisibility-spec '(org-cwidth))
5341 (add-to-invisibility-spec '(org-hide-block . t))
5342 (when (featurep 'xemacs)
5343 (org-set-local 'line-move-ignore-invisible t))
5344 (org-set-local 'outline-regexp org-outline-regexp)
5345 (org-set-local 'outline-level 'org-outline-level)
5346 (setq bidi-paragraph-direction 'left-to-right)
5347 (when (and org-ellipsis
5348 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5349 (fboundp 'make-glyph-code))
5350 (unless org-display-table
5351 (setq org-display-table (make-display-table)))
5352 (set-display-table-slot
5353 org-display-table 4
5354 (vconcat (mapcar
5355 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5356 org-ellipsis)))
5357 (if (stringp org-ellipsis) org-ellipsis "..."))))
5358 (setq buffer-display-table org-display-table))
5359 (org-set-regexps-and-options-for-tags)
5360 (org-set-regexps-and-options)
5361 (org-set-font-lock-defaults)
5362 (when (and org-tag-faces (not org-tags-special-faces-re))
5363 ;; tag faces set outside customize.... force initialization.
5364 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5365 ;; Calc embedded
5366 (org-set-local 'calc-embedded-open-mode "# ")
5367 ;; Modify a few syntax entries
5368 (modify-syntax-entry ?@ "w")
5369 (modify-syntax-entry ?\" "\"")
5370 (if org-startup-truncated (setq truncate-lines t))
5371 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5372 (org-set-local 'font-lock-unfontify-region-function
5373 'org-unfontify-region)
5374 ;; Activate before-change-function
5375 (org-set-local 'org-table-may-need-update t)
5376 (org-add-hook 'before-change-functions 'org-before-change-function nil
5377 'local)
5378 ;; Check for running clock before killing a buffer
5379 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5380 ;; Initialize macros templates.
5381 (org-macro-initialize-templates)
5382 ;; Initialize radio targets.
5383 (org-update-radio-target-regexp)
5384 ;; Indentation.
5385 (org-set-local 'indent-line-function 'org-indent-line)
5386 (org-set-local 'indent-region-function 'org-indent-region)
5387 ;; Filling and auto-filling.
5388 (org-setup-filling)
5389 ;; Comments.
5390 (org-setup-comments-handling)
5391 ;; Beginning/end of defun
5392 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5393 (org-set-local 'end-of-defun-function 'org-forward-element)
5394 ;; Next error for sparse trees
5395 (org-set-local 'next-error-function 'org-occur-next-match)
5396 ;; Make sure dependence stuff works reliably, even for users who set it
5397 ;; too late :-(
5398 (if org-enforce-todo-dependencies
5399 (add-hook 'org-blocker-hook
5400 'org-block-todo-from-children-or-siblings-or-parent)
5401 (remove-hook 'org-blocker-hook
5402 'org-block-todo-from-children-or-siblings-or-parent))
5403 (if org-enforce-todo-checkbox-dependencies
5404 (add-hook 'org-blocker-hook
5405 'org-block-todo-from-checkboxes)
5406 (remove-hook 'org-blocker-hook
5407 'org-block-todo-from-checkboxes))
5409 ;; Align options lines
5410 (org-set-local
5411 'align-mode-rules-list
5412 '((org-in-buffer-settings
5413 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5414 (modes . '(org-mode)))))
5416 ;; Imenu
5417 (org-set-local 'imenu-create-index-function
5418 'org-imenu-get-tree)
5420 ;; Make isearch reveal context
5421 (if (or (featurep 'xemacs)
5422 (not (boundp 'outline-isearch-open-invisible-function)))
5423 ;; Emacs 21 and XEmacs make use of the hook
5424 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5425 ;; Emacs 22 deals with this through a special variable
5426 (org-set-local 'outline-isearch-open-invisible-function
5427 (lambda (&rest ignore) (org-show-context 'isearch)))
5428 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5430 ;; Setup the pcomplete hooks
5431 (set (make-local-variable 'pcomplete-command-completion-function)
5432 'org-pcomplete-initial)
5433 (set (make-local-variable 'pcomplete-command-name-function)
5434 'org-command-at-point)
5435 (set (make-local-variable 'pcomplete-default-completion-function)
5436 'ignore)
5437 (set (make-local-variable 'pcomplete-parse-arguments-function)
5438 'org-parse-arguments)
5439 (set (make-local-variable 'pcomplete-termination-string) "")
5440 (when (>= emacs-major-version 23)
5441 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5443 ;; If empty file that did not turn on org-mode automatically, make it to.
5444 (if (and org-insert-mode-line-in-empty-file
5445 (org-called-interactively-p 'any)
5446 (= (point-min) (point-max)))
5447 (insert "# -*- mode: org -*-\n\n"))
5448 (unless org-inhibit-startup
5449 (org-unmodified
5450 (and org-startup-with-beamer-mode (org-beamer-mode))
5451 (when org-startup-align-all-tables
5452 (org-table-map-tables 'org-table-align 'quietly))
5453 (when org-startup-with-inline-images
5454 (org-display-inline-images))
5455 (when org-startup-with-latex-preview
5456 (org-preview-latex-fragment))
5457 (unless org-inhibit-startup-visibility-stuff
5458 (org-set-startup-visibility))))
5459 ;; Try to set org-hide correctly
5460 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5462 ;; Update `customize-package-emacs-version-alist'
5463 (add-to-list 'customize-package-emacs-version-alist
5464 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5465 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5466 ("8.0" . "24.4")))
5468 (defvar org-mode-transpose-word-syntax-table
5469 (let ((st (make-syntax-table)))
5470 (mapc (lambda(c) (modify-syntax-entry
5471 (string-to-char (car c)) "w p" st))
5472 org-emphasis-alist)
5473 st))
5475 (when (fboundp 'abbrev-table-put)
5476 (abbrev-table-put org-mode-abbrev-table
5477 :parents (list text-mode-abbrev-table)))
5479 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5481 (defsubst org-fix-ellipsis-at-bol ()
5482 (save-excursion (goto-char (window-start)) (recenter 0)))
5484 (defun org-find-invisible-foreground ()
5485 (let ((candidates (remove
5486 "unspecified-bg"
5487 (nconc
5488 (list (face-background 'default)
5489 (face-background 'org-default))
5490 (mapcar
5491 (lambda (alist)
5492 (when (boundp alist)
5493 (cdr (assoc 'background-color (symbol-value alist)))))
5494 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5495 (list (face-foreground 'org-hide))))))
5496 (car (remove nil candidates))))
5498 (defun org-current-time (&optional rounding-minutes past)
5499 "Current time, possibly rounded to ROUNDING-MINUTES.
5500 When ROUNDING-MINUTES is not an integer, fall back on the car of
5501 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5502 the rounding returns a past time."
5503 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5504 (car org-time-stamp-rounding-minutes)))
5505 (time (decode-time)) res)
5506 (if (< r 1)
5507 (current-time)
5508 (setq res
5509 (apply 'encode-time
5510 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5511 (nthcdr 2 time))))
5512 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5513 (seconds-to-time (- (org-float-time res) (* r 60)))
5514 res))))
5516 (defun org-today ()
5517 "Return today date, considering `org-extend-today-until'."
5518 (time-to-days
5519 (time-subtract (current-time)
5520 (list 0 (* 3600 org-extend-today-until) 0))))
5522 ;;;; Font-Lock stuff, including the activators
5524 (defvar org-mouse-map (make-sparse-keymap))
5525 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5526 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5527 (when org-mouse-1-follows-link
5528 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5529 (when org-tab-follows-link
5530 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5531 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5533 (require 'font-lock)
5535 (defconst org-non-link-chars "]\t\n\r<>")
5536 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5537 "shell" "elisp" "doi" "message"))
5538 (defvar org-link-types-re nil
5539 "Matches a link that has a url-like prefix like \"http:\"")
5540 (defvar org-link-re-with-space nil
5541 "Matches a link with spaces, optional angular brackets around it.")
5542 (defvar org-link-re-with-space2 nil
5543 "Matches a link with spaces, optional angular brackets around it.")
5544 (defvar org-link-re-with-space3 nil
5545 "Matches a link with spaces, only for internal part in bracket links.")
5546 (defvar org-angle-link-re nil
5547 "Matches link with angular brackets, spaces are allowed.")
5548 (defvar org-plain-link-re nil
5549 "Matches plain link, without spaces.")
5550 (defvar org-bracket-link-regexp nil
5551 "Matches a link in double brackets.")
5552 (defvar org-bracket-link-analytic-regexp nil
5553 "Regular expression used to analyze links.
5554 Here is what the match groups contain after a match:
5555 1: http:
5556 2: http
5557 3: path
5558 4: [desc]
5559 5: desc")
5560 (defvar org-bracket-link-analytic-regexp++ nil
5561 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5562 (defvar org-any-link-re nil
5563 "Regular expression matching any link.")
5565 (defconst org-match-sexp-depth 3
5566 "Number of stacked braces for sub/superscript matching.")
5568 (defun org-create-multibrace-regexp (left right n)
5569 "Create a regular expression which will match a balanced sexp.
5570 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5571 as single character strings.
5572 The regexp returned will match the entire expression including the
5573 delimiters. It will also define a single group which contains the
5574 match except for the outermost delimiters. The maximum depth of
5575 stacked delimiters is N. Escaping delimiters is not possible."
5576 (let* ((nothing (concat "[^" left right "]*?"))
5577 (or "\\|")
5578 (re nothing)
5579 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5580 (while (> n 1)
5581 (setq n (1- n)
5582 re (concat re or next)
5583 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5584 (concat left "\\(" re "\\)" right)))
5586 (defvar org-match-substring-regexp
5587 (concat
5588 "\\(\\S-\\)\\([_^]\\)\\("
5589 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5590 "\\|"
5591 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5592 "\\|"
5593 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5594 "The regular expression matching a sub- or superscript.")
5596 (defvar org-match-substring-with-braces-regexp
5597 (concat
5598 "\\(\\S-\\)\\([_^]\\)\\("
5599 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5600 "\\)")
5601 "The regular expression matching a sub- or superscript, forcing braces.")
5603 (defun org-make-link-regexps ()
5604 "Update the link regular expressions.
5605 This should be called after the variable `org-link-types' has changed."
5606 (setq org-link-types-re
5607 (concat
5608 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5609 org-link-re-with-space
5610 (concat
5611 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5612 "\\([^" org-non-link-chars " ]"
5613 "[^" org-non-link-chars "]*"
5614 "[^" org-non-link-chars " ]\\)>?")
5615 org-link-re-with-space2
5616 (concat
5617 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5618 "\\([^" org-non-link-chars " ]"
5619 "[^\t\n\r]*"
5620 "[^" org-non-link-chars " ]\\)>?")
5621 org-link-re-with-space3
5622 (concat
5623 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5624 "\\([^" org-non-link-chars " ]"
5625 "[^\t\n\r]*\\)")
5626 org-angle-link-re
5627 (concat
5628 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5629 "\\([^" org-non-link-chars " ]"
5630 "[^" org-non-link-chars "]*"
5631 "\\)>")
5632 org-plain-link-re
5633 (concat
5634 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5635 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5636 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5637 org-bracket-link-regexp
5638 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5639 org-bracket-link-analytic-regexp
5640 (concat
5641 "\\[\\["
5642 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5643 "\\([^]]+\\)"
5644 "\\]"
5645 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5646 "\\]")
5647 org-bracket-link-analytic-regexp++
5648 (concat
5649 "\\[\\["
5650 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5651 "\\([^]]+\\)"
5652 "\\]"
5653 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5654 "\\]")
5655 org-any-link-re
5656 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5657 org-angle-link-re "\\)\\|\\("
5658 org-plain-link-re "\\)")))
5660 (org-make-link-regexps)
5662 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5663 "Regular expression for fast time stamp matching.")
5664 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5665 "Regular expression for fast time stamp matching.")
5666 (defconst org-ts-regexp0
5667 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5668 "Regular expression matching time strings for analysis.
5669 This one does not require the space after the date, so it can be used
5670 on a string that terminates immediately after the date.")
5671 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5672 "Regular expression matching time strings for analysis.")
5673 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5674 "Regular expression matching time stamps, with groups.")
5675 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5676 "Regular expression matching time stamps (also [..]), with groups.")
5677 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5678 "Regular expression matching a time stamp range.")
5679 (defconst org-tr-regexp-both
5680 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5681 "Regular expression matching a time stamp range.")
5682 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5683 org-ts-regexp "\\)?")
5684 "Regular expression matching a time stamp or time stamp range.")
5685 (defconst org-tsr-regexp-both
5686 (concat org-ts-regexp-both "\\(--?-?"
5687 org-ts-regexp-both "\\)?")
5688 "Regular expression matching a time stamp or time stamp range.
5689 The time stamps may be either active or inactive.")
5691 (defvar org-emph-face nil)
5693 (defun org-do-emphasis-faces (limit)
5694 "Run through the buffer and add overlays to emphasized strings."
5695 (let (rtn a)
5696 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5697 (if (not (= (char-after (match-beginning 3))
5698 (char-after (match-beginning 4))))
5699 (progn
5700 (setq rtn t)
5701 (setq a (assoc (match-string 3) org-emphasis-alist))
5702 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5703 'face
5704 (nth 1 a))
5705 (and (nth 4 a)
5706 (org-remove-flyspell-overlays-in
5707 (match-beginning 0) (match-end 0)))
5708 (add-text-properties (match-beginning 2) (match-end 2)
5709 '(font-lock-multiline t org-emphasis t))
5710 (when org-hide-emphasis-markers
5711 (add-text-properties (match-end 4) (match-beginning 5)
5712 '(invisible org-link))
5713 (add-text-properties (match-beginning 3) (match-end 3)
5714 '(invisible org-link)))))
5715 (backward-char 1))
5716 rtn))
5718 (defun org-emphasize (&optional char)
5719 "Insert or change an emphasis, i.e. a font like bold or italic.
5720 If there is an active region, change that region to a new emphasis.
5721 If there is no region, just insert the marker characters and position
5722 the cursor between them.
5723 CHAR should be the marker character. If it is a space, it means to
5724 remove the emphasis of the selected region.
5725 If CHAR is not given (for example in an interactive call) it will be
5726 prompted for."
5727 (interactive)
5728 (let ((erc org-emphasis-regexp-components)
5729 (prompt "")
5730 (string "") beg end move c s)
5731 (if (org-region-active-p)
5732 (setq beg (region-beginning) end (region-end)
5733 string (buffer-substring beg end))
5734 (setq move t))
5736 (unless char
5737 (message "Emphasis marker or tag: [%s]"
5738 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5739 (setq char (read-char-exclusive)))
5740 (if (equal char ?\ )
5741 (setq s "" move nil)
5742 (unless (assoc (char-to-string char) org-emphasis-alist)
5743 (user-error "No such emphasis marker: \"%c\"" char))
5744 (setq s (char-to-string char)))
5745 (while (and (> (length string) 1)
5746 (equal (substring string 0 1) (substring string -1))
5747 (assoc (substring string 0 1) org-emphasis-alist))
5748 (setq string (substring string 1 -1)))
5749 (setq string (concat s string s))
5750 (if beg (delete-region beg end))
5751 (unless (or (bolp)
5752 (string-match (concat "[" (nth 0 erc) "\n]")
5753 (char-to-string (char-before (point)))))
5754 (insert " "))
5755 (unless (or (eobp)
5756 (string-match (concat "[" (nth 1 erc) "\n]")
5757 (char-to-string (char-after (point)))))
5758 (insert " ") (backward-char 1))
5759 (insert string)
5760 (and move (backward-char 1))))
5762 (defconst org-nonsticky-props
5763 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5765 (defsubst org-rear-nonsticky-at (pos)
5766 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5768 (defun org-activate-plain-links (limit)
5769 "Run through the buffer and add overlays to links."
5770 (let (f hl)
5771 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5772 (not (org-in-src-block-p)))
5773 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5774 (setq f (get-text-property (match-beginning 0) 'face))
5775 (setq hl (org-match-string-no-properties 0))
5776 (if (or (eq f 'org-tag)
5777 (and (listp f) (memq 'org-tag f)))
5779 (add-text-properties (match-beginning 0) (match-end 0)
5780 (list 'mouse-face 'highlight
5781 'face 'org-link
5782 'htmlize-link `(:uri ,hl)
5783 'keymap org-mouse-map))
5784 (org-rear-nonsticky-at (match-end 0)))
5785 t)))
5787 (defun org-activate-code (limit)
5788 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5789 (progn
5790 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5791 (remove-text-properties (match-beginning 0) (match-end 0)
5792 '(display t invisible t intangible t))
5793 t)))
5795 (defcustom org-src-fontify-natively nil
5796 "When non-nil, fontify code in code blocks."
5797 :type 'boolean
5798 :version "24.1"
5799 :group 'org-appearance
5800 :group 'org-babel)
5802 (defcustom org-allow-promoting-top-level-subtree nil
5803 "When non-nil, allow promoting a top level subtree.
5804 The leading star of the top level headline will be replaced
5805 by a #."
5806 :type 'boolean
5807 :version "24.1"
5808 :group 'org-appearance)
5810 (defun org-fontify-meta-lines-and-blocks (limit)
5811 (condition-case nil
5812 (org-fontify-meta-lines-and-blocks-1 limit)
5813 (error (message "org-mode fontification error"))))
5815 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5816 "Fontify #+ lines and blocks."
5817 (let ((case-fold-search t))
5818 (if (re-search-forward
5819 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5820 limit t)
5821 (let ((beg (match-beginning 0))
5822 (block-start (match-end 0))
5823 (block-end nil)
5824 (lang (match-string 7))
5825 (beg1 (line-beginning-position 2))
5826 (dc1 (downcase (match-string 2)))
5827 (dc3 (downcase (match-string 3)))
5828 end end1 quoting block-type ovl)
5829 (cond
5830 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5831 ;; a single line of backend-specific content
5832 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5833 (remove-text-properties (match-beginning 0) (match-end 0)
5834 '(display t invisible t intangible t))
5835 (add-text-properties (match-beginning 1) (match-end 3)
5836 '(font-lock-fontified t face org-meta-line))
5837 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5838 '(font-lock-fontified t face org-block))
5839 ; for backend-specific code
5841 ((and (match-end 4) (equal dc3 "+begin"))
5842 ;; Truly a block
5843 (setq block-type (downcase (match-string 5))
5844 quoting (member block-type org-protecting-blocks))
5845 (when (re-search-forward
5846 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5847 nil t) ;; on purpose, we look further than LIMIT
5848 (setq end (min (point-max) (match-end 0))
5849 end1 (min (point-max) (1- (match-beginning 0))))
5850 (setq block-end (match-beginning 0))
5851 (when quoting
5852 (remove-text-properties beg end
5853 '(display t invisible t intangible t)))
5854 (add-text-properties
5855 beg end
5856 '(font-lock-fontified t font-lock-multiline t))
5857 (add-text-properties beg beg1 '(face org-meta-line))
5858 (add-text-properties end1 (min (point-max) (1+ end))
5859 '(face org-meta-line)) ; for end_src
5860 (cond
5861 ((and lang (not (string= lang "")) org-src-fontify-natively)
5862 (org-src-font-lock-fontify-block lang block-start block-end)
5863 ;; remove old background overlays
5864 (mapc (lambda (ov)
5865 (if (eq (overlay-get ov 'face) 'org-block-background)
5866 (delete-overlay ov)))
5867 (overlays-at (/ (+ beg1 block-end) 2)))
5868 ;; add a background overlay
5869 (setq ovl (make-overlay beg1 block-end))
5870 (overlay-put ovl 'face 'org-block-background)
5871 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5872 (quoting
5873 (add-text-properties beg1 (min (point-max) (1+ end1))
5874 '(face org-block))) ; end of source block
5875 ((not org-fontify-quote-and-verse-blocks))
5876 ((string= block-type "quote")
5877 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5878 ((string= block-type "verse")
5879 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5880 (add-text-properties beg beg1 '(face org-block-begin-line))
5881 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5882 '(face org-block-end-line))
5884 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5885 (add-text-properties
5886 beg (match-end 3)
5887 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5888 '(font-lock-fontified t invisible t)
5889 '(font-lock-fontified t face org-document-info-keyword)))
5890 (add-text-properties
5891 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5892 (if (string-equal dc1 "+title:")
5893 '(font-lock-fontified t face org-document-title)
5894 '(font-lock-fontified t face org-document-info))))
5895 ((or (equal dc1 "+results")
5896 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5897 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5898 "+call:" "+header:" "+headers:" "+name:"))
5899 (and (match-end 4) (equal dc3 "+attr")))
5900 (add-text-properties
5901 beg (match-end 0)
5902 '(font-lock-fontified t face org-meta-line))
5904 ((member dc3 '(" " ""))
5905 (add-text-properties
5906 beg (match-end 0)
5907 '(font-lock-fontified t face font-lock-comment-face)))
5908 ((not (member (char-after beg) '(?\ ?\t)))
5909 ;; just any other in-buffer setting, but not indented
5910 (add-text-properties
5911 beg (match-end 0)
5912 '(font-lock-fontified t face org-meta-line))
5914 (t nil))))))
5916 (defun org-activate-angle-links (limit)
5917 "Run through the buffer and add overlays to links."
5918 (if (and (re-search-forward org-angle-link-re limit t)
5919 (not (org-in-src-block-p)))
5920 (progn
5921 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5922 (add-text-properties (match-beginning 0) (match-end 0)
5923 (list 'mouse-face 'highlight
5924 'keymap org-mouse-map))
5925 (org-rear-nonsticky-at (match-end 0))
5926 t)))
5928 (defun org-activate-footnote-links (limit)
5929 "Run through the buffer and add overlays to footnotes."
5930 (let ((fn (org-footnote-next-reference-or-definition limit)))
5931 (when fn
5932 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5933 (org-remove-flyspell-overlays-in beg end)
5934 (add-text-properties beg end
5935 (list 'mouse-face 'highlight
5936 'keymap org-mouse-map
5937 'help-echo
5938 (if (= (point-at-bol) beg)
5939 "Footnote definition"
5940 "Footnote reference")
5941 'font-lock-fontified t
5942 'font-lock-multiline t
5943 'face 'org-footnote))))))
5945 (defun org-activate-bracket-links (limit)
5946 "Run through the buffer and add overlays to bracketed links."
5947 (if (and (re-search-forward org-bracket-link-regexp limit t)
5948 (not (org-in-src-block-p)))
5949 (let* ((hl (org-match-string-no-properties 1))
5950 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
5951 (ip (org-maybe-intangible
5952 (list 'invisible 'org-link
5953 'keymap org-mouse-map 'mouse-face 'highlight
5954 'font-lock-multiline t 'help-echo help
5955 'htmlize-link `(:uri ,hl))))
5956 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5957 'font-lock-multiline t 'help-echo help
5958 'htmlize-link `(:uri ,hl))))
5959 ;; We need to remove the invisible property here. Table narrowing
5960 ;; may have made some of this invisible.
5961 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5962 (remove-text-properties (match-beginning 0) (match-end 0)
5963 '(invisible nil))
5964 (if (match-end 3)
5965 (progn
5966 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5967 (org-rear-nonsticky-at (match-beginning 3))
5968 (add-text-properties (match-beginning 3) (match-end 3) vp)
5969 (org-rear-nonsticky-at (match-end 3))
5970 (add-text-properties (match-end 3) (match-end 0) ip)
5971 (org-rear-nonsticky-at (match-end 0)))
5972 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5973 (org-rear-nonsticky-at (match-beginning 1))
5974 (add-text-properties (match-beginning 1) (match-end 1) vp)
5975 (org-rear-nonsticky-at (match-end 1))
5976 (add-text-properties (match-end 1) (match-end 0) ip)
5977 (org-rear-nonsticky-at (match-end 0)))
5978 t)))
5980 (defun org-activate-dates (limit)
5981 "Run through the buffer and add overlays to dates."
5982 (if (and (re-search-forward org-tsr-regexp-both limit t)
5983 (not (equal (char-before (match-beginning 0)) 91)))
5984 (progn
5985 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5986 (add-text-properties (match-beginning 0) (match-end 0)
5987 (list 'mouse-face 'highlight
5988 'keymap org-mouse-map))
5989 (org-rear-nonsticky-at (match-end 0))
5990 (when org-display-custom-times
5991 (if (match-end 3)
5992 (org-display-custom-time (match-beginning 3) (match-end 3)))
5993 (org-display-custom-time (match-beginning 1) (match-end 1)))
5994 t)))
5996 (defvar org-target-link-regexp nil
5997 "Regular expression matching radio targets in plain text.")
5998 (make-variable-buffer-local 'org-target-link-regexp)
5999 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
6000 "Regular expression matching a link target.")
6001 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
6002 "Regular expression matching a radio target.")
6003 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
6004 "Regular expression matching any target.")
6006 (defun org-activate-target-links (limit)
6007 "Run through the buffer and add overlays to target matches."
6008 (when org-target-link-regexp
6009 (let ((case-fold-search t))
6010 (if (re-search-forward org-target-link-regexp limit t)
6011 (progn
6012 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6013 (add-text-properties (match-beginning 0) (match-end 0)
6014 (list 'mouse-face 'highlight
6015 'keymap org-mouse-map
6016 'help-echo "Radio target link"
6017 'org-linked-text t))
6018 (org-rear-nonsticky-at (match-end 0))
6019 t)))))
6021 (defun org-update-radio-target-regexp ()
6022 "Find all radio targets in this file and update the regular expression."
6023 (interactive)
6024 (when (memq 'radio org-activate-links)
6025 (setq org-target-link-regexp
6026 (org-make-target-link-regexp (org-all-targets 'radio)))
6027 (org-restart-font-lock)))
6029 (defun org-hide-wide-columns (limit)
6030 (let (s e)
6031 (setq s (text-property-any (point) (or limit (point-max))
6032 'org-cwidth t))
6033 (when s
6034 (setq e (next-single-property-change s 'org-cwidth))
6035 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6036 (goto-char e)
6037 t)))
6039 (defvar org-latex-and-related-regexp nil
6040 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6041 (defvar org-match-substring-regexp)
6042 (defvar org-match-substring-with-braces-regexp)
6044 (defun org-compute-latex-and-related-regexp ()
6045 "Compute regular expression for LaTeX, entities and sub/superscript.
6046 Result depends on variable `org-highlight-latex-and-related'."
6047 (org-set-local
6048 'org-latex-and-related-regexp
6049 (let* ((re-sub
6050 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6051 ((eq org-use-sub-superscripts '{})
6052 (list org-match-substring-with-braces-regexp))
6053 (org-use-sub-superscripts (list org-match-substring-regexp))))
6054 (re-latex
6055 (when (memq 'latex org-highlight-latex-and-related)
6056 (let ((matchers (plist-get org-format-latex-options :matchers)))
6057 (delq nil
6058 (mapcar (lambda (x)
6059 (and (member (car x) matchers) (nth 1 x)))
6060 org-latex-regexps)))))
6061 (re-entities
6062 (when (memq 'entities org-highlight-latex-and-related)
6063 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6064 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6066 (defun org-do-latex-and-related (limit)
6067 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6068 LIMIT bounds the search for syntax to highlight. Stop at first
6069 highlighted object, if any. Return t if some highlighting was
6070 done, nil otherwise."
6071 (when (org-string-nw-p org-latex-and-related-regexp)
6072 (catch 'found
6073 (while (re-search-forward org-latex-and-related-regexp limit t)
6074 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6075 'face))
6076 '(org-code org-verbatim underline))
6077 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6078 '(?_ ?^))
6080 0)))
6081 (font-lock-prepend-text-property
6082 (+ offset (match-beginning 0)) (match-end 0)
6083 'face 'org-latex-and-related)
6084 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6085 '(font-lock-multiline t)))
6086 (throw 'found t)))
6087 nil)))
6089 (defun org-restart-font-lock ()
6090 "Restart `font-lock-mode', to force refontification."
6091 (when (and (boundp 'font-lock-mode) font-lock-mode)
6092 (font-lock-mode -1)
6093 (font-lock-mode 1)))
6095 (defun org-all-targets (&optional radio)
6096 "Return a list of all targets in this file.
6097 When optional argument RADIO is non-nil, only find radio
6098 targets."
6099 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
6100 (save-excursion
6101 (goto-char (point-min))
6102 (while (re-search-forward re nil t)
6103 ;; Make sure point is really within the object.
6104 (backward-char)
6105 (let ((obj (org-element-context)))
6106 (when (memq (org-element-type obj) '(radio-target target))
6107 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
6108 rtn)))
6110 (defun org-make-target-link-regexp (targets)
6111 "Make regular expression matching all strings in TARGETS.
6112 The regular expression finds the targets also if there is a line break
6113 between words."
6114 (and targets
6115 (concat
6116 "\\<\\("
6117 (mapconcat
6118 (lambda (x)
6119 (setq x (regexp-quote x))
6120 (while (string-match " +" x)
6121 (setq x (replace-match "\\s-+" t t x)))
6123 targets
6124 "\\|")
6125 "\\)\\>")))
6127 (defun org-activate-tags (limit)
6128 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6129 (progn
6130 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6131 (add-text-properties (match-beginning 1) (match-end 1)
6132 (list 'mouse-face 'highlight
6133 'keymap org-mouse-map))
6134 (org-rear-nonsticky-at (match-end 1))
6135 t)))
6137 (defun org-outline-level ()
6138 "Compute the outline level of the heading at point.
6139 If this is called at a normal headline, the level is the number of stars.
6140 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6141 (save-excursion
6142 (if (not (condition-case nil
6143 (org-back-to-heading t)
6144 (error nil)))
6146 (looking-at org-outline-regexp)
6147 (1- (- (match-end 0) (match-beginning 0))))))
6149 (defvar org-font-lock-keywords nil)
6151 (defsubst org-re-property (property &optional literal)
6152 "Return a regexp matching a PROPERTY line.
6153 Match group 3 will be set to the value if it exists."
6154 (concat "^\\(?4:[ \t]*\\)\\(?1::\\(?2:"
6155 (if literal property (regexp-quote property))
6156 "\\):\\)[ \t]+\\(?3:[^ \t\r\n].*?\\)\\(?5:[ \t]*\\)$"))
6158 (defconst org-property-re
6159 (org-re-property ".*?" 'literal)
6160 "Regular expression matching a property line.
6161 There are four matching groups:
6162 1: :PROPKEY: including the leading and trailing colon,
6163 2: PROPKEY without the leading and trailing colon,
6164 3: PROPVAL without leading or trailing spaces,
6165 4: the indentation of the current line,
6166 5: trailing whitespace.")
6168 (defvar org-font-lock-hook nil
6169 "Functions to be called for special font lock stuff.")
6171 (defvar org-font-lock-set-keywords-hook nil
6172 "Functions that can manipulate `org-font-lock-extra-keywords'.
6173 This is called after `org-font-lock-extra-keywords' is defined, but before
6174 it is installed to be used by font lock. This can be useful if something
6175 needs to be inserted at a specific position in the font-lock sequence.")
6177 (defun org-font-lock-hook (limit)
6178 "Run `org-font-lock-hook' within LIMIT."
6179 (run-hook-with-args 'org-font-lock-hook limit))
6181 (defun org-set-font-lock-defaults ()
6182 "Set font lock defaults for the current buffer."
6183 (let* ((em org-fontify-emphasized-text)
6184 (lk org-activate-links)
6185 (org-font-lock-extra-keywords
6186 (list
6187 ;; Call the hook
6188 '(org-font-lock-hook)
6189 ;; Headlines
6190 `(,(if org-fontify-whole-heading-line
6191 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6192 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6193 (1 (org-get-level-face 1))
6194 (2 (org-get-level-face 2))
6195 (3 (org-get-level-face 3)))
6196 ;; Table lines
6197 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6198 (1 'org-table t))
6199 ;; Table internals
6200 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6201 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6202 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6203 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6204 ;; Drawers
6205 (list org-drawer-regexp '(0 'org-special-keyword t))
6206 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
6207 ;; Properties
6208 (list org-property-re
6209 '(1 'org-special-keyword t)
6210 '(3 'org-property-value t))
6211 ;; Links
6212 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6213 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6214 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6215 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6216 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6217 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6218 (if (memq 'footnote lk) '(org-activate-footnote-links))
6219 ;; Targets.
6220 (list org-any-target-regexp '(0 'org-target t))
6221 ;; Diary sexps.
6222 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6223 ;; Macro
6224 '("{{{.+}}}" (0 'org-macro t))
6225 '(org-hide-wide-columns (0 nil append))
6226 ;; TODO keyword
6227 (list (format org-heading-keyword-regexp-format
6228 org-todo-regexp)
6229 '(2 (org-get-todo-face 2) t))
6230 ;; DONE
6231 (if org-fontify-done-headline
6232 (list (format org-heading-keyword-regexp-format
6233 (concat
6234 "\\(?:"
6235 (mapconcat 'regexp-quote org-done-keywords "\\|")
6236 "\\)"))
6237 '(2 'org-headline-done t))
6238 nil)
6239 ;; Priorities
6240 '(org-font-lock-add-priority-faces)
6241 ;; Tags
6242 '(org-font-lock-add-tag-faces)
6243 ;; Tags groups
6244 (if (and org-group-tags org-tag-groups-alist)
6245 (list (concat org-outline-regexp-bol ".+\\(:"
6246 (regexp-opt (mapcar 'car org-tag-groups-alist))
6247 ":\\).*$")
6248 '(1 'org-tag-group prepend)))
6249 ;; Special keywords
6250 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6251 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6252 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6253 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6254 ;; Emphasis
6255 (if em
6256 (if (featurep 'xemacs)
6257 '(org-do-emphasis-faces (0 nil append))
6258 '(org-do-emphasis-faces)))
6259 ;; Checkboxes
6260 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6261 1 'org-checkbox prepend)
6262 (if (cdr (assq 'checkbox org-list-automatic-rules))
6263 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6264 (0 (org-get-checkbox-statistics-face) t)))
6265 ;; Description list items
6266 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6267 1 'org-list-dt prepend)
6268 ;; ARCHIVEd headings
6269 (list (concat
6270 org-outline-regexp-bol
6271 "\\(.*:" org-archive-tag ":.*\\)")
6272 '(1 'org-archived prepend))
6273 ;; Specials
6274 '(org-do-latex-and-related)
6275 '(org-fontify-entities)
6276 '(org-raise-scripts)
6277 ;; Code
6278 '(org-activate-code (1 'org-code t))
6279 ;; COMMENT
6280 (list (format org-heading-keyword-regexp-format
6281 (concat "\\("
6282 org-comment-string "\\|" org-quote-string
6283 "\\)"))
6284 '(2 'org-special-keyword t))
6285 ;; Blocks and meta lines
6286 '(org-fontify-meta-lines-and-blocks))))
6287 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6288 (run-hooks 'org-font-lock-set-keywords-hook)
6289 ;; Now set the full font-lock-keywords
6290 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6291 (org-set-local 'font-lock-defaults
6292 '(org-font-lock-keywords t nil nil backward-paragraph))
6293 (kill-local-variable 'font-lock-keywords) nil))
6295 (defun org-toggle-pretty-entities ()
6296 "Toggle the composition display of entities as UTF8 characters."
6297 (interactive)
6298 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6299 (org-restart-font-lock)
6300 (if org-pretty-entities
6301 (message "Entities are now displayed as UTF8 characters")
6302 (save-restriction
6303 (widen)
6304 (org-decompose-region (point-min) (point-max))
6305 (message "Entities are now displayed as plain text"))))
6307 (defvar org-custom-properties-overlays nil
6308 "List of overlays used for custom properties.")
6309 (make-variable-buffer-local 'org-custom-properties-overlays)
6311 (defun org-toggle-custom-properties-visibility ()
6312 "Display or hide properties in `org-custom-properties'."
6313 (interactive)
6314 (if org-custom-properties-overlays
6315 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6316 (setq org-custom-properties-overlays nil))
6317 (unless (not org-custom-properties)
6318 (save-excursion
6319 (save-restriction
6320 (widen)
6321 (goto-char (point-min))
6322 (while (re-search-forward org-property-re nil t)
6323 (mapc (lambda(p)
6324 (when (equal p (substring (match-string 1) 1 -1))
6325 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6326 (overlay-put o 'invisible t)
6327 (overlay-put o 'org-custom-property t)
6328 (push o org-custom-properties-overlays))))
6329 org-custom-properties)))))))
6331 (defun org-fontify-entities (limit)
6332 "Find an entity to fontify."
6333 (let (ee)
6334 (when org-pretty-entities
6335 (catch 'match
6336 (while (re-search-forward
6337 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6338 limit t)
6339 (if (and (not (org-in-indented-comment-line))
6340 (setq ee (org-entity-get (match-string 1)))
6341 (= (length (nth 6 ee)) 1))
6342 (let*
6343 ((end (if (equal (match-string 2) "{}")
6344 (match-end 2)
6345 (match-end 1))))
6346 (add-text-properties
6347 (match-beginning 0) end
6348 (list 'font-lock-fontified t))
6349 (compose-region (match-beginning 0) end
6350 (nth 6 ee) nil)
6351 (backward-char 1)
6352 (throw 'match t))))
6353 nil))))
6355 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6356 "Fontify string S like in Org-mode."
6357 (with-temp-buffer
6358 (insert s)
6359 (let ((org-odd-levels-only odd-levels))
6360 (org-mode)
6361 (font-lock-fontify-buffer)
6362 (buffer-string))))
6364 (defvar org-m nil)
6365 (defvar org-l nil)
6366 (defvar org-f nil)
6367 (defun org-get-level-face (n)
6368 "Get the right face for match N in font-lock matching of headlines."
6369 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6370 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6371 (if org-cycle-level-faces
6372 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6373 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6374 (cond
6375 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6376 ((eq n 2) org-f)
6377 (t (if org-level-color-stars-only nil org-f))))
6380 (defun org-get-todo-face (kwd)
6381 "Get the right face for a TODO keyword KWD.
6382 If KWD is a number, get the corresponding match group."
6383 (if (numberp kwd) (setq kwd (match-string kwd)))
6384 (or (org-face-from-face-or-color
6385 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6386 (and (member kwd org-done-keywords) 'org-done)
6387 'org-todo))
6389 (defun org-face-from-face-or-color (context inherit face-or-color)
6390 "Create a face list that inherits INHERIT, but sets the foreground color.
6391 When FACE-OR-COLOR is not a string, just return it."
6392 (if (stringp face-or-color)
6393 (list :inherit inherit
6394 (cdr (assoc context org-faces-easy-properties))
6395 face-or-color)
6396 face-or-color))
6398 (defun org-font-lock-add-tag-faces (limit)
6399 "Add the special tag faces."
6400 (when (and org-tag-faces org-tags-special-faces-re)
6401 (while (re-search-forward org-tags-special-faces-re limit t)
6402 (add-text-properties (match-beginning 1) (match-end 1)
6403 (list 'face (org-get-tag-face 1)
6404 'font-lock-fontified t))
6405 (backward-char 1))))
6407 (defun org-font-lock-add-priority-faces (limit)
6408 "Add the special priority faces."
6409 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6410 (when (save-match-data (org-at-heading-p))
6411 (add-text-properties
6412 (match-beginning 0) (match-end 0)
6413 (list 'face (or (org-face-from-face-or-color
6414 'priority 'org-priority
6415 (cdr (assoc (char-after (match-beginning 1))
6416 org-priority-faces)))
6417 'org-priority)
6418 'font-lock-fontified t)))))
6420 (defun org-get-tag-face (kwd)
6421 "Get the right face for a TODO keyword KWD.
6422 If KWD is a number, get the corresponding match group."
6423 (if (numberp kwd) (setq kwd (match-string kwd)))
6424 (or (org-face-from-face-or-color
6425 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6426 'org-tag))
6428 (defun org-unfontify-region (beg end &optional maybe_loudly)
6429 "Remove fontification and activation overlays from links."
6430 (font-lock-default-unfontify-region beg end)
6431 (let* ((buffer-undo-list t)
6432 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6433 (inhibit-modification-hooks t)
6434 deactivate-mark buffer-file-name buffer-file-truename)
6435 (org-decompose-region beg end)
6436 (remove-text-properties beg end
6437 '(mouse-face t keymap t org-linked-text t
6438 invisible t intangible t
6439 org-no-flyspell t org-emphasis t))
6440 (org-remove-font-lock-display-properties beg end)))
6442 (defconst org-script-display '(((raise -0.3) (height 0.7))
6443 ((raise 0.3) (height 0.7))
6444 ((raise -0.5))
6445 ((raise 0.5)))
6446 "Display properties for showing superscripts and subscripts.")
6448 (defun org-remove-font-lock-display-properties (beg end)
6449 "Remove specific display properties that have been added by font lock.
6450 The will remove the raise properties that are used to show superscripts
6451 and subscripts."
6452 (let (next prop)
6453 (while (< beg end)
6454 (setq next (next-single-property-change beg 'display nil end)
6455 prop (get-text-property beg 'display))
6456 (if (member prop org-script-display)
6457 (put-text-property beg next 'display nil))
6458 (setq beg next))))
6460 (defun org-raise-scripts (limit)
6461 "Add raise properties to sub/superscripts."
6462 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6463 (if (re-search-forward
6464 (if (eq org-use-sub-superscripts t)
6465 org-match-substring-regexp
6466 org-match-substring-with-braces-regexp)
6467 limit t)
6468 (let* ((pos (point)) table-p comment-p
6469 (mpos (match-beginning 3))
6470 (emph-p (get-text-property mpos 'org-emphasis))
6471 (link-p (get-text-property mpos 'mouse-face))
6472 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6473 (goto-char (point-at-bol))
6474 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6475 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6476 (goto-char pos)
6477 ;; Handle a_b^c
6478 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6479 (if (or comment-p emph-p link-p keyw-p)
6481 (put-text-property (match-beginning 3) (match-end 0)
6482 'display
6483 (if (equal (char-after (match-beginning 2)) ?^)
6484 (nth (if table-p 3 1) org-script-display)
6485 (nth (if table-p 2 0) org-script-display)))
6486 (add-text-properties (match-beginning 2) (match-end 2)
6487 (list 'invisible t
6488 'org-dwidth t 'org-dwidth-n 1))
6489 (if (and (eq (char-after (match-beginning 3)) ?{)
6490 (eq (char-before (match-end 3)) ?}))
6491 (progn
6492 (add-text-properties
6493 (match-beginning 3) (1+ (match-beginning 3))
6494 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6495 (add-text-properties
6496 (1- (match-end 3)) (match-end 3)
6497 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6498 t)))))
6500 ;;;; Visibility cycling, including org-goto and indirect buffer
6502 ;;; Cycling
6504 (defvar org-cycle-global-status nil)
6505 (make-variable-buffer-local 'org-cycle-global-status)
6506 (put 'org-cycle-global-status 'org-state t)
6507 (defvar org-cycle-subtree-status nil)
6508 (make-variable-buffer-local 'org-cycle-subtree-status)
6509 (put 'org-cycle-subtree-status 'org-state t)
6511 (defvar org-inlinetask-min-level)
6513 (defun org-unlogged-message (&rest args)
6514 "Display a message, but avoid logging it in the *Messages* buffer."
6515 (let ((message-log-max nil))
6516 (apply 'message args)))
6518 ;;;###autoload
6519 (defun org-cycle (&optional arg)
6520 "TAB-action and visibility cycling for Org-mode.
6522 This is the command invoked in Org-mode by the TAB key. Its main purpose
6523 is outline visibility cycling, but it also invokes other actions
6524 in special contexts.
6526 - When this function is called with a prefix argument, rotate the entire
6527 buffer through 3 states (global cycling)
6528 1. OVERVIEW: Show only top-level headlines.
6529 2. CONTENTS: Show all headlines of all levels, but no body text.
6530 3. SHOW ALL: Show everything.
6531 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6532 determined by the variable `org-startup-folded', and by any VISIBILITY
6533 properties in the buffer.
6534 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6535 including any drawers.
6537 - When inside a table, re-align the table and move to the next field.
6539 - When point is at the beginning of a headline, rotate the subtree started
6540 by this line through 3 different states (local cycling)
6541 1. FOLDED: Only the main headline is shown.
6542 2. CHILDREN: The main headline and the direct children are shown.
6543 From this state, you can move to one of the children
6544 and zoom in further.
6545 3. SUBTREE: Show the entire subtree, including body text.
6546 If there is no subtree, switch directly from CHILDREN to FOLDED.
6548 - When point is at the beginning of an empty headline and the variable
6549 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6550 of the headline by demoting and promoting it to likely levels. This
6551 speeds up creation document structure by pressing TAB once or several
6552 times right after creating a new headline.
6554 - When there is a numeric prefix, go up to a heading with level ARG, do
6555 a `show-subtree' and return to the previous cursor position. If ARG
6556 is negative, go up that many levels.
6558 - When point is not at the beginning of a headline, execute the global
6559 binding for TAB, which is re-indenting the line. See the option
6560 `org-cycle-emulate-tab' for details.
6562 - Special case: if point is at the beginning of the buffer and there is
6563 no headline in line 1, this function will act as if called with prefix arg
6564 (C-u TAB, same as S-TAB) also when called without prefix arg.
6565 But only if also the variable `org-cycle-global-at-bob' is t."
6566 (interactive "P")
6567 (org-load-modules-maybe)
6568 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6569 (and org-cycle-level-after-item/entry-creation
6570 (or (org-cycle-level)
6571 (org-cycle-item-indentation))))
6572 (let* ((limit-level
6573 (or org-cycle-max-level
6574 (and (boundp 'org-inlinetask-min-level)
6575 org-inlinetask-min-level
6576 (1- org-inlinetask-min-level))))
6577 (nstars (and limit-level
6578 (if org-odd-levels-only
6579 (and limit-level (1- (* limit-level 2)))
6580 limit-level)))
6581 (org-outline-regexp
6582 (if (not (derived-mode-p 'org-mode))
6583 outline-regexp
6584 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6585 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6586 (not (looking-at org-outline-regexp))))
6587 (org-cycle-hook
6588 (if bob-special
6589 (delq 'org-optimize-window-after-visibility-change
6590 (copy-sequence org-cycle-hook))
6591 org-cycle-hook))
6592 (pos (point)))
6594 (if (or bob-special (equal arg '(4)))
6595 ;; special case: use global cycling
6596 (setq arg t))
6598 (cond
6600 ((equal arg '(16))
6601 (setq last-command 'dummy)
6602 (org-set-startup-visibility)
6603 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6605 ((equal arg '(64))
6606 (show-all)
6607 (org-unlogged-message "Entire buffer visible, including drawers"))
6609 ;; Table: enter it or move to the next field.
6610 ((org-at-table-p 'any)
6611 (if (org-at-table.el-p)
6612 (message "Use C-c ' to edit table.el tables")
6613 (if arg (org-table-edit-field t)
6614 (org-table-justify-field-maybe)
6615 (call-interactively 'org-table-next-field))))
6617 ((run-hook-with-args-until-success
6618 'org-tab-after-check-for-table-hook))
6620 ;; Global cycling: delegate to `org-cycle-internal-global'.
6621 ((eq arg t) (org-cycle-internal-global))
6623 ;; Drawers: delegate to `org-flag-drawer'.
6624 ((and org-drawers org-drawer-regexp
6625 (save-excursion
6626 (beginning-of-line 1)
6627 (looking-at org-drawer-regexp)))
6628 (org-flag-drawer ; toggle block visibility
6629 (not (get-char-property (match-end 0) 'invisible))))
6631 ;; Show-subtree, ARG levels up from here.
6632 ((integerp arg)
6633 (save-excursion
6634 (org-back-to-heading)
6635 (outline-up-heading (if (< arg 0) (- arg)
6636 (- (funcall outline-level) arg)))
6637 (org-show-subtree)))
6639 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6640 ((and (featurep 'org-inlinetask)
6641 (org-inlinetask-at-task-p)
6642 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6643 (org-inlinetask-toggle-visibility))
6645 ((org-try-cdlatex-tab))
6647 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6648 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6649 (save-excursion (beginning-of-line 1)
6650 (looking-at org-outline-regexp)))
6651 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6652 (org-cycle-internal-local))
6654 ;; From there: TAB emulation and template completion.
6655 (buffer-read-only (org-back-to-heading))
6657 ((run-hook-with-args-until-success
6658 'org-tab-after-check-for-cycling-hook))
6660 ((org-try-structure-completion))
6662 ((run-hook-with-args-until-success
6663 'org-tab-before-tab-emulation-hook))
6665 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6666 (or (not (bolp))
6667 (not (looking-at org-outline-regexp))))
6668 (call-interactively (global-key-binding "\t")))
6670 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6671 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6672 (or (and (eq org-cycle-emulate-tab 'white)
6673 (= (match-end 0) (point-at-eol)))
6674 (and (eq org-cycle-emulate-tab 'whitestart)
6675 (>= (match-end 0) pos))))
6677 (eq org-cycle-emulate-tab t))
6678 (call-interactively (global-key-binding "\t")))
6680 (t (save-excursion
6681 (org-back-to-heading)
6682 (org-cycle)))))))
6684 (defun org-cycle-internal-global ()
6685 "Do the global cycling action."
6686 ;; Hack to avoid display of messages for .org attachments in Gnus
6687 (let ((ga (string-match "\\*fontification" (buffer-name))))
6688 (cond
6689 ((and (eq last-command this-command)
6690 (eq org-cycle-global-status 'overview))
6691 ;; We just created the overview - now do table of contents
6692 ;; This can be slow in very large buffers, so indicate action
6693 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6694 (unless ga (org-unlogged-message "CONTENTS..."))
6695 (org-content)
6696 (unless ga (org-unlogged-message "CONTENTS...done"))
6697 (setq org-cycle-global-status 'contents)
6698 (run-hook-with-args 'org-cycle-hook 'contents))
6700 ((and (eq last-command this-command)
6701 (eq org-cycle-global-status 'contents))
6702 ;; We just showed the table of contents - now show everything
6703 (run-hook-with-args 'org-pre-cycle-hook 'all)
6704 (show-all)
6705 (unless ga (org-unlogged-message "SHOW ALL"))
6706 (setq org-cycle-global-status 'all)
6707 (run-hook-with-args 'org-cycle-hook 'all))
6710 ;; Default action: go to overview
6711 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6712 (org-overview)
6713 (unless ga (org-unlogged-message "OVERVIEW"))
6714 (setq org-cycle-global-status 'overview)
6715 (run-hook-with-args 'org-cycle-hook 'overview)))))
6717 (defun org-cycle-internal-local ()
6718 "Do the local cycling action."
6719 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6720 ;; First, determine end of headline (EOH), end of subtree or item
6721 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6722 (save-excursion
6723 (if (org-at-item-p)
6724 (progn
6725 (beginning-of-line)
6726 (setq struct (org-list-struct))
6727 (setq eoh (point-at-eol))
6728 (setq eos (org-list-get-item-end-before-blank (point) struct))
6729 (setq has-children (org-list-has-child-p (point) struct)))
6730 (org-back-to-heading)
6731 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6732 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6733 (setq has-children
6734 (or (save-excursion
6735 (let ((level (funcall outline-level)))
6736 (outline-next-heading)
6737 (and (org-at-heading-p t)
6738 (> (funcall outline-level) level))))
6739 (save-excursion
6740 (org-list-search-forward (org-item-beginning-re) eos t)))))
6741 ;; Determine end invisible part of buffer (EOL)
6742 (beginning-of-line 2)
6743 ;; XEmacs doesn't have `next-single-char-property-change'
6744 (if (featurep 'xemacs)
6745 (while (and (not (eobp)) ;; this is like `next-line'
6746 (get-char-property (1- (point)) 'invisible))
6747 (beginning-of-line 2))
6748 (while (and (not (eobp)) ;; this is like `next-line'
6749 (get-char-property (1- (point)) 'invisible))
6750 (goto-char (next-single-char-property-change (point) 'invisible))
6751 (and (eolp) (beginning-of-line 2))))
6752 (setq eol (point)))
6753 ;; Find out what to do next and set `this-command'
6754 (cond
6755 ((= eos eoh)
6756 ;; Nothing is hidden behind this heading
6757 (unless (org-before-first-heading-p)
6758 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6759 (org-unlogged-message "EMPTY ENTRY")
6760 (setq org-cycle-subtree-status nil)
6761 (save-excursion
6762 (goto-char eos)
6763 (outline-next-heading)
6764 (if (outline-invisible-p) (org-flag-heading nil))))
6765 ((and (or (>= eol eos)
6766 (not (string-match "\\S-" (buffer-substring eol eos))))
6767 (or has-children
6768 (not (setq children-skipped
6769 org-cycle-skip-children-state-if-no-children))))
6770 ;; Entire subtree is hidden in one line: children view
6771 (unless (org-before-first-heading-p)
6772 (run-hook-with-args 'org-pre-cycle-hook 'children))
6773 (if (org-at-item-p)
6774 (org-list-set-item-visibility (point-at-bol) struct 'children)
6775 (org-show-entry)
6776 (org-with-limited-levels (show-children))
6777 ;; FIXME: This slows down the func way too much.
6778 ;; How keep drawers hidden in subtree anyway?
6779 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6780 ;; (org-cycle-hide-drawers 'subtree))
6782 ;; Fold every list in subtree to top-level items.
6783 (when (eq org-cycle-include-plain-lists 'integrate)
6784 (save-excursion
6785 (org-back-to-heading)
6786 (while (org-list-search-forward (org-item-beginning-re) eos t)
6787 (beginning-of-line 1)
6788 (let* ((struct (org-list-struct))
6789 (prevs (org-list-prevs-alist struct))
6790 (end (org-list-get-bottom-point struct)))
6791 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6792 (org-list-get-all-items (point) struct prevs))
6793 (goto-char (if (< end eos) end eos)))))))
6794 (org-unlogged-message "CHILDREN")
6795 (save-excursion
6796 (goto-char eos)
6797 (outline-next-heading)
6798 (if (outline-invisible-p) (org-flag-heading nil)))
6799 (setq org-cycle-subtree-status 'children)
6800 (unless (org-before-first-heading-p)
6801 (run-hook-with-args 'org-cycle-hook 'children)))
6802 ((or children-skipped
6803 (and (eq last-command this-command)
6804 (eq org-cycle-subtree-status 'children)))
6805 ;; We just showed the children, or no children are there,
6806 ;; now show everything.
6807 (unless (org-before-first-heading-p)
6808 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6809 (outline-flag-region eoh eos nil)
6810 (org-unlogged-message
6811 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6812 (setq org-cycle-subtree-status 'subtree)
6813 (unless (org-before-first-heading-p)
6814 (run-hook-with-args 'org-cycle-hook 'subtree)))
6816 ;; Default action: hide the subtree.
6817 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6818 (outline-flag-region eoh eos t)
6819 (org-unlogged-message "FOLDED")
6820 (setq org-cycle-subtree-status 'folded)
6821 (unless (org-before-first-heading-p)
6822 (run-hook-with-args 'org-cycle-hook 'folded))))))
6824 ;;;###autoload
6825 (defun org-global-cycle (&optional arg)
6826 "Cycle the global visibility. For details see `org-cycle'.
6827 With \\[universal-argument] prefix arg, switch to startup visibility.
6828 With a numeric prefix, show all headlines up to that level."
6829 (interactive "P")
6830 (let ((org-cycle-include-plain-lists
6831 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6832 (cond
6833 ((integerp arg)
6834 (show-all)
6835 (hide-sublevels arg)
6836 (setq org-cycle-global-status 'contents))
6837 ((equal arg '(4))
6838 (org-set-startup-visibility)
6839 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6841 (org-cycle '(4))))))
6843 (defun org-set-startup-visibility ()
6844 "Set the visibility required by startup options and properties."
6845 (cond
6846 ((eq org-startup-folded t)
6847 (org-cycle '(4)))
6848 ((eq org-startup-folded 'content)
6849 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6850 (org-cycle '(4)) (org-cycle '(4)))))
6851 (unless (eq org-startup-folded 'showeverything)
6852 (if org-hide-block-startup (org-hide-block-all))
6853 (org-set-visibility-according-to-property 'no-cleanup)
6854 (org-cycle-hide-archived-subtrees 'all)
6855 (org-cycle-hide-drawers 'all)
6856 (org-cycle-show-empty-lines t)))
6858 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6859 "Switch subtree visibilities according to :VISIBILITY: property."
6860 (interactive)
6861 (let (org-show-entry-below state)
6862 (save-excursion
6863 (goto-char (point-min))
6864 (while (re-search-forward
6865 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6866 nil t)
6867 (setq state (match-string 1))
6868 (save-excursion
6869 (org-back-to-heading t)
6870 (hide-subtree)
6871 (org-reveal)
6872 (cond
6873 ((equal state '("fold" "folded"))
6874 (hide-subtree))
6875 ((equal state "children")
6876 (org-show-hidden-entry)
6877 (show-children))
6878 ((equal state "content")
6879 (save-excursion
6880 (save-restriction
6881 (org-narrow-to-subtree)
6882 (org-content))))
6883 ((member state '("all" "showall"))
6884 (show-subtree)))))
6885 (unless no-cleanup
6886 (org-cycle-hide-archived-subtrees 'all)
6887 (org-cycle-hide-drawers 'all)
6888 (org-cycle-show-empty-lines 'all)))))
6890 ;; This function uses outline-regexp instead of the more fundamental
6891 ;; org-outline-regexp so that org-cycle-global works outside of Org
6892 ;; buffers, where outline-regexp is needed.
6893 (defun org-overview ()
6894 "Switch to overview mode, showing only top-level headlines.
6895 Really, this shows all headlines with level equal or greater than the level
6896 of the first headline in the buffer. This is important, because if the
6897 first headline is not level one, then (hide-sublevels 1) gives confusing
6898 results."
6899 (interactive)
6900 (let ((l (org-current-line))
6901 (level (save-excursion
6902 (goto-char (point-min))
6903 (if (re-search-forward (concat "^" outline-regexp) nil t)
6904 (progn
6905 (goto-char (match-beginning 0))
6906 (funcall outline-level))))))
6907 (and level (hide-sublevels level))
6908 (recenter '(4))
6909 (org-goto-line l)))
6911 (defun org-content (&optional arg)
6912 "Show all headlines in the buffer, like a table of contents.
6913 With numerical argument N, show content up to level N."
6914 (interactive "P")
6915 (save-excursion
6916 ;; Visit all headings and show their offspring
6917 (and (integerp arg) (org-overview))
6918 (goto-char (point-max))
6919 (catch 'exit
6920 (while (and (progn (condition-case nil
6921 (outline-previous-visible-heading 1)
6922 (error (goto-char (point-min))))
6924 (looking-at org-outline-regexp))
6925 (if (integerp arg)
6926 (show-children (1- arg))
6927 (show-branches))
6928 (if (bobp) (throw 'exit nil))))))
6931 (defun org-optimize-window-after-visibility-change (state)
6932 "Adjust the window after a change in outline visibility.
6933 This function is the default value of the hook `org-cycle-hook'."
6934 (when (get-buffer-window (current-buffer))
6935 (cond
6936 ((eq state 'content) nil)
6937 ((eq state 'all) nil)
6938 ((eq state 'folded) nil)
6939 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6940 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6942 (defun org-remove-empty-overlays-at (pos)
6943 "Remove outline overlays that do not contain non-white stuff."
6944 (mapc
6945 (lambda (o)
6946 (and (eq 'outline (overlay-get o 'invisible))
6947 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6948 (overlay-end o))))
6949 (delete-overlay o)))
6950 (overlays-at pos)))
6952 (defun org-clean-visibility-after-subtree-move ()
6953 "Fix visibility issues after moving a subtree."
6954 ;; First, find a reasonable region to look at:
6955 ;; Start two siblings above, end three below
6956 (let* ((beg (save-excursion
6957 (and (org-get-last-sibling)
6958 (org-get-last-sibling))
6959 (point)))
6960 (end (save-excursion
6961 (and (org-get-next-sibling)
6962 (org-get-next-sibling)
6963 (org-get-next-sibling))
6964 (if (org-at-heading-p)
6965 (point-at-eol)
6966 (point))))
6967 (level (looking-at "\\*+"))
6968 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6969 (save-excursion
6970 (save-restriction
6971 (narrow-to-region beg end)
6972 (when re
6973 ;; Properly fold already folded siblings
6974 (goto-char (point-min))
6975 (while (re-search-forward re nil t)
6976 (if (and (not (outline-invisible-p))
6977 (save-excursion
6978 (goto-char (point-at-eol)) (outline-invisible-p)))
6979 (hide-entry))))
6980 (org-cycle-show-empty-lines 'overview)
6981 (org-cycle-hide-drawers 'overview)))))
6983 (defun org-cycle-show-empty-lines (state)
6984 "Show empty lines above all visible headlines.
6985 The region to be covered depends on STATE when called through
6986 `org-cycle-hook'. Lisp program can use t for STATE to get the
6987 entire buffer covered. Note that an empty line is only shown if there
6988 are at least `org-cycle-separator-lines' empty lines before the headline."
6989 (when (not (= org-cycle-separator-lines 0))
6990 (save-excursion
6991 (let* ((n (abs org-cycle-separator-lines))
6992 (re (cond
6993 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6994 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6995 (t (let ((ns (number-to-string (- n 2))))
6996 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6997 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6998 beg end b e)
6999 (cond
7000 ((memq state '(overview contents t))
7001 (setq beg (point-min) end (point-max)))
7002 ((memq state '(children folded))
7003 (setq beg (point) end (progn (org-end-of-subtree t t)
7004 (beginning-of-line 2)
7005 (point)))))
7006 (when beg
7007 (goto-char beg)
7008 (while (re-search-forward re end t)
7009 (unless (get-char-property (match-end 1) 'invisible)
7010 (setq e (match-end 1))
7011 (if (< org-cycle-separator-lines 0)
7012 (setq b (save-excursion
7013 (goto-char (match-beginning 0))
7014 (org-back-over-empty-lines)
7015 (if (save-excursion
7016 (goto-char (max (point-min) (1- (point))))
7017 (org-at-heading-p))
7018 (1- (point))
7019 (point))))
7020 (setq b (match-beginning 1)))
7021 (outline-flag-region b e nil)))))))
7022 ;; Never hide empty lines at the end of the file.
7023 (save-excursion
7024 (goto-char (point-max))
7025 (outline-previous-heading)
7026 (outline-end-of-heading)
7027 (if (and (looking-at "[ \t\n]+")
7028 (= (match-end 0) (point-max)))
7029 (outline-flag-region (point) (match-end 0) nil))))
7031 (defun org-show-empty-lines-in-parent ()
7032 "Move to the parent and re-show empty lines before visible headlines."
7033 (save-excursion
7034 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7035 (org-cycle-show-empty-lines context))))
7037 (defun org-files-list ()
7038 "Return `org-agenda-files' list, plus all open org-mode files.
7039 This is useful for operations that need to scan all of a user's
7040 open and agenda-wise Org files."
7041 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7042 (dolist (buf (buffer-list))
7043 (with-current-buffer buf
7044 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7045 (let ((file (expand-file-name (buffer-file-name))))
7046 (unless (member file files)
7047 (push file files))))))
7048 files))
7050 (defsubst org-entry-beginning-position ()
7051 "Return the beginning position of the current entry."
7052 (save-excursion (outline-back-to-heading t) (point)))
7054 (defsubst org-entry-end-position ()
7055 "Return the end position of the current entry."
7056 (save-excursion (outline-next-heading) (point)))
7058 (defun org-cycle-hide-drawers (state)
7059 "Re-hide all drawers after a visibility state change."
7060 (when (and (derived-mode-p 'org-mode)
7061 (not (memq state '(overview folded contents))))
7062 (save-excursion
7063 (let* ((globalp (memq state '(contents all)))
7064 (beg (if globalp (point-min) (point)))
7065 (end (if globalp (point-max)
7066 (if (eq state 'children)
7067 (save-excursion (outline-next-heading) (point))
7068 (org-end-of-subtree t)))))
7069 (goto-char beg)
7070 (while (re-search-forward org-drawer-regexp end t)
7071 (org-flag-drawer t))))))
7073 (defun org-cycle-hide-inline-tasks (state)
7074 "Re-hide inline task when switching to 'contents visibility state."
7075 (when (and (eq state 'contents)
7076 (boundp 'org-inlinetask-min-level)
7077 org-inlinetask-min-level)
7078 (hide-sublevels (1- org-inlinetask-min-level))))
7080 (defun org-flag-drawer (flag)
7081 "When FLAG is non-nil, hide the drawer we are within.
7082 Otherwise make it visible."
7083 (save-excursion
7084 (beginning-of-line 1)
7085 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
7086 (let ((b (match-end 0)))
7087 (if (re-search-forward
7088 "^[ \t]*:END:"
7089 (save-excursion (outline-next-heading) (point)) t)
7090 (outline-flag-region b (point-at-eol) flag)
7091 (user-error ":END: line missing at position %s" b))))))
7093 (defun org-subtree-end-visible-p ()
7094 "Is the end of the current subtree visible?"
7095 (pos-visible-in-window-p
7096 (save-excursion (org-end-of-subtree t) (point))))
7098 (defun org-first-headline-recenter (&optional N)
7099 "Move cursor to the first headline and recenter the headline.
7100 Optional argument N means put the headline into the Nth line of the window."
7101 (goto-char (point-min))
7102 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7103 (beginning-of-line)
7104 (recenter (prefix-numeric-value N))))
7106 ;;; Saving and restoring visibility
7108 (defun org-outline-overlay-data (&optional use-markers)
7109 "Return a list of the locations of all outline overlays.
7110 These are overlays with the `invisible' property value `outline'.
7111 The return value is a list of cons cells, with start and stop
7112 positions for each overlay.
7113 If USE-MARKERS is set, return the positions as markers."
7114 (let (beg end)
7115 (save-excursion
7116 (save-restriction
7117 (widen)
7118 (delq nil
7119 (mapcar (lambda (o)
7120 (when (eq (overlay-get o 'invisible) 'outline)
7121 (setq beg (overlay-start o)
7122 end (overlay-end o))
7123 (and beg end (> end beg)
7124 (if use-markers
7125 (cons (move-marker (make-marker) beg)
7126 (move-marker (make-marker) end))
7127 (cons beg end)))))
7128 (overlays-in (point-min) (point-max))))))))
7130 (defun org-set-outline-overlay-data (data)
7131 "Create visibility overlays for all positions in DATA.
7132 DATA should have been made by `org-outline-overlay-data'."
7133 (let (o)
7134 (save-excursion
7135 (save-restriction
7136 (widen)
7137 (show-all)
7138 (mapc (lambda (c)
7139 (outline-flag-region (car c) (cdr c) t))
7140 data)))))
7142 ;;; Folding of blocks
7144 (defvar org-hide-block-overlays nil
7145 "Overlays hiding blocks.")
7146 (make-variable-buffer-local 'org-hide-block-overlays)
7148 (defun org-block-map (function &optional start end)
7149 "Call FUNCTION at the head of all source blocks in the current buffer.
7150 Optional arguments START and END can be used to limit the range."
7151 (let ((start (or start (point-min)))
7152 (end (or end (point-max))))
7153 (save-excursion
7154 (goto-char start)
7155 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7156 (save-excursion
7157 (save-match-data
7158 (goto-char (match-beginning 0))
7159 (funcall function)))))))
7161 (defun org-hide-block-toggle-all ()
7162 "Toggle the visibility of all blocks in the current buffer."
7163 (org-block-map #'org-hide-block-toggle))
7165 (defun org-hide-block-all ()
7166 "Fold all blocks in the current buffer."
7167 (interactive)
7168 (org-show-block-all)
7169 (org-block-map #'org-hide-block-toggle-maybe))
7171 (defun org-show-block-all ()
7172 "Unfold all blocks in the current buffer."
7173 (interactive)
7174 (mapc 'delete-overlay org-hide-block-overlays)
7175 (setq org-hide-block-overlays nil))
7177 (defun org-hide-block-toggle-maybe ()
7178 "Toggle visibility of block at point."
7179 (interactive)
7180 (let ((case-fold-search t))
7181 (if (save-excursion
7182 (beginning-of-line 1)
7183 (looking-at org-block-regexp))
7184 (progn (org-hide-block-toggle)
7185 t) ;; to signal that we took action
7186 nil))) ;; to signal that we did not
7188 (defun org-hide-block-toggle (&optional force)
7189 "Toggle the visibility of the current block."
7190 (interactive)
7191 (save-excursion
7192 (beginning-of-line)
7193 (if (re-search-forward org-block-regexp nil t)
7194 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7195 (end (match-end 0)) ;; end of entire body
7197 (if (memq t (mapcar (lambda (overlay)
7198 (eq (overlay-get overlay 'invisible)
7199 'org-hide-block))
7200 (overlays-at start)))
7201 (if (or (not force) (eq force 'off))
7202 (mapc (lambda (ov)
7203 (when (member ov org-hide-block-overlays)
7204 (setq org-hide-block-overlays
7205 (delq ov org-hide-block-overlays)))
7206 (when (eq (overlay-get ov 'invisible)
7207 'org-hide-block)
7208 (delete-overlay ov)))
7209 (overlays-at start)))
7210 (setq ov (make-overlay start end))
7211 (overlay-put ov 'invisible 'org-hide-block)
7212 ;; make the block accessible to isearch
7213 (overlay-put
7214 ov 'isearch-open-invisible
7215 (lambda (ov)
7216 (when (member ov org-hide-block-overlays)
7217 (setq org-hide-block-overlays
7218 (delq ov org-hide-block-overlays)))
7219 (when (eq (overlay-get ov 'invisible)
7220 'org-hide-block)
7221 (delete-overlay ov))))
7222 (push ov org-hide-block-overlays)))
7223 (user-error "Not looking at a source block"))))
7225 ;; org-tab-after-check-for-cycling-hook
7226 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7227 ;; Remove overlays when changing major mode
7228 (add-hook 'org-mode-hook
7229 (lambda () (org-add-hook 'change-major-mode-hook
7230 'org-show-block-all 'append 'local)))
7232 ;;; Org-goto
7234 (defvar org-goto-window-configuration nil)
7235 (defvar org-goto-marker nil)
7236 (defvar org-goto-map)
7237 (defun org-goto-map ()
7238 "Set the keymap `org-goto'."
7239 (setq org-goto-map
7240 (let ((map (make-sparse-keymap)))
7241 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7242 mouse-drag-region universal-argument org-occur))
7243 cmd)
7244 (while (setq cmd (pop cmds))
7245 (substitute-key-definition cmd cmd map global-map)))
7246 (suppress-keymap map)
7247 (org-defkey map "\C-m" 'org-goto-ret)
7248 (org-defkey map [(return)] 'org-goto-ret)
7249 (org-defkey map [(left)] 'org-goto-left)
7250 (org-defkey map [(right)] 'org-goto-right)
7251 (org-defkey map [(control ?g)] 'org-goto-quit)
7252 (org-defkey map "\C-i" 'org-cycle)
7253 (org-defkey map [(tab)] 'org-cycle)
7254 (org-defkey map [(down)] 'outline-next-visible-heading)
7255 (org-defkey map [(up)] 'outline-previous-visible-heading)
7256 (if org-goto-auto-isearch
7257 (if (fboundp 'define-key-after)
7258 (define-key-after map [t] 'org-goto-local-auto-isearch)
7259 nil)
7260 (org-defkey map "q" 'org-goto-quit)
7261 (org-defkey map "n" 'outline-next-visible-heading)
7262 (org-defkey map "p" 'outline-previous-visible-heading)
7263 (org-defkey map "f" 'outline-forward-same-level)
7264 (org-defkey map "b" 'outline-backward-same-level)
7265 (org-defkey map "u" 'outline-up-heading))
7266 (org-defkey map "/" 'org-occur)
7267 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7268 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7269 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7270 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7271 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7272 map)))
7274 (defconst org-goto-help
7275 "Browse buffer copy, to find location or copy text.%s
7276 RET=jump to location C-g=quit and return to previous location
7277 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7279 (defvar org-goto-start-pos) ; dynamically scoped parameter
7281 (defun org-goto (&optional alternative-interface)
7282 "Look up a different location in the current file, keeping current visibility.
7284 When you want look-up or go to a different location in a
7285 document, the fastest way is often to fold the entire buffer and
7286 then dive into the tree. This method has the disadvantage, that
7287 the previous location will be folded, which may not be what you
7288 want.
7290 This command works around this by showing a copy of the current
7291 buffer in an indirect buffer, in overview mode. You can dive
7292 into the tree in that copy, use org-occur and incremental search
7293 to find a location. When pressing RET or `Q', the command
7294 returns to the original buffer in which the visibility is still
7295 unchanged. After RET it will also jump to the location selected
7296 in the indirect buffer and expose the headline hierarchy above.
7298 With a prefix argument, use the alternative interface: e.g. if
7299 `org-goto-interface' is 'outline use 'outline-path-completion."
7300 (interactive "P")
7301 (org-goto-map)
7302 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7303 (org-refile-use-outline-path t)
7304 (org-refile-target-verify-function nil)
7305 (interface
7306 (if (not alternative-interface)
7307 org-goto-interface
7308 (if (eq org-goto-interface 'outline)
7309 'outline-path-completion
7310 'outline)))
7311 (org-goto-start-pos (point))
7312 (selected-point
7313 (if (eq interface 'outline)
7314 (car (org-get-location (current-buffer) org-goto-help))
7315 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7316 (org-refile-check-position pa)
7317 (nth 3 pa)))))
7318 (if selected-point
7319 (progn
7320 (org-mark-ring-push org-goto-start-pos)
7321 (goto-char selected-point)
7322 (if (or (outline-invisible-p) (org-invisible-p2))
7323 (org-show-context 'org-goto)))
7324 (message "Quit"))))
7326 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7327 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7328 (defvar org-goto-local-auto-isearch-map) ; defined below
7330 (defun org-get-location (buf help)
7331 "Let the user select a location in the Org-mode buffer BUF.
7332 This function uses a recursive edit. It returns the selected position
7333 or nil."
7334 (org-no-popups
7335 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7336 (isearch-hide-immediately nil)
7337 (isearch-search-fun-function
7338 (lambda () 'org-goto-local-search-headings))
7339 (org-goto-selected-point org-goto-exit-command))
7340 (save-excursion
7341 (save-window-excursion
7342 (delete-other-windows)
7343 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7344 (org-pop-to-buffer-same-window
7345 (condition-case nil
7346 (make-indirect-buffer (current-buffer) "*org-goto*")
7347 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7348 (with-output-to-temp-buffer "*Org Help*"
7349 (princ (format help (if org-goto-auto-isearch
7350 " Just type for auto-isearch."
7351 " n/p/f/b/u to navigate, q to quit."))))
7352 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7353 (setq buffer-read-only nil)
7354 (let ((org-startup-truncated t)
7355 (org-startup-folded nil)
7356 (org-startup-align-all-tables nil))
7357 (org-mode)
7358 (org-overview))
7359 (setq buffer-read-only t)
7360 (if (and (boundp 'org-goto-start-pos)
7361 (integer-or-marker-p org-goto-start-pos))
7362 (let ((org-show-hierarchy-above t)
7363 (org-show-siblings t)
7364 (org-show-following-heading t))
7365 (goto-char org-goto-start-pos)
7366 (and (outline-invisible-p) (org-show-context)))
7367 (goto-char (point-min)))
7368 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7369 (message "Select location and press RET")
7370 (use-local-map org-goto-map)
7371 (recursive-edit)))
7372 (kill-buffer "*org-goto*")
7373 (cons org-goto-selected-point org-goto-exit-command))))
7375 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7376 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7377 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7378 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7380 (defun org-goto-local-search-headings (string bound noerror)
7381 "Search and make sure that any matches are in headlines."
7382 (catch 'return
7383 (while (if isearch-forward
7384 (search-forward string bound noerror)
7385 (search-backward string bound noerror))
7386 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7387 (and (member :headline context)
7388 (not (member :tags context))))
7389 (throw 'return (point))))))
7391 (defun org-goto-local-auto-isearch ()
7392 "Start isearch."
7393 (interactive)
7394 (goto-char (point-min))
7395 (let ((keys (this-command-keys)))
7396 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7397 (isearch-mode t)
7398 (isearch-process-search-char (string-to-char keys)))))
7400 (defun org-goto-ret (&optional arg)
7401 "Finish `org-goto' by going to the new location."
7402 (interactive "P")
7403 (setq org-goto-selected-point (point)
7404 org-goto-exit-command 'return)
7405 (throw 'exit nil))
7407 (defun org-goto-left ()
7408 "Finish `org-goto' by going to the new location."
7409 (interactive)
7410 (if (org-at-heading-p)
7411 (progn
7412 (beginning-of-line 1)
7413 (setq org-goto-selected-point (point)
7414 org-goto-exit-command 'left)
7415 (throw 'exit nil))
7416 (user-error "Not on a heading")))
7418 (defun org-goto-right ()
7419 "Finish `org-goto' by going to the new location."
7420 (interactive)
7421 (if (org-at-heading-p)
7422 (progn
7423 (setq org-goto-selected-point (point)
7424 org-goto-exit-command 'right)
7425 (throw 'exit nil))
7426 (user-error "Not on a heading")))
7428 (defun org-goto-quit ()
7429 "Finish `org-goto' without cursor motion."
7430 (interactive)
7431 (setq org-goto-selected-point nil)
7432 (setq org-goto-exit-command 'quit)
7433 (throw 'exit nil))
7435 ;;; Indirect buffer display of subtrees
7437 (defvar org-indirect-dedicated-frame nil
7438 "This is the frame being used for indirect tree display.")
7439 (defvar org-last-indirect-buffer nil)
7441 (defun org-tree-to-indirect-buffer (&optional arg)
7442 "Create indirect buffer and narrow it to current subtree.
7443 With a numerical prefix ARG, go up to this level and then take that tree.
7444 If ARG is negative, go up that many levels.
7446 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7447 indirect buffer previously made with this command, to avoid proliferation of
7448 indirect buffers. However, when you call the command with a \
7449 \\[universal-argument] prefix, or
7450 when `org-indirect-buffer-display' is `new-frame', the last buffer
7451 is kept so that you can work with several indirect buffers at the same time.
7452 If `org-indirect-buffer-display' is `dedicated-frame', the \
7453 \\[universal-argument] prefix also
7454 requests that a new frame be made for the new buffer, so that the dedicated
7455 frame is not changed."
7456 (interactive "P")
7457 (let ((cbuf (current-buffer))
7458 (cwin (selected-window))
7459 (pos (point))
7460 beg end level heading ibuf)
7461 (save-excursion
7462 (org-back-to-heading t)
7463 (when (numberp arg)
7464 (setq level (org-outline-level))
7465 (if (< arg 0) (setq arg (+ level arg)))
7466 (while (> (setq level (org-outline-level)) arg)
7467 (org-up-heading-safe)))
7468 (setq beg (point)
7469 heading (org-get-heading))
7470 (org-end-of-subtree t t)
7471 (if (org-at-heading-p) (backward-char 1))
7472 (setq end (point)))
7473 (if (and (buffer-live-p org-last-indirect-buffer)
7474 (not (eq org-indirect-buffer-display 'new-frame))
7475 (not arg))
7476 (kill-buffer org-last-indirect-buffer))
7477 (setq ibuf (org-get-indirect-buffer cbuf)
7478 org-last-indirect-buffer ibuf)
7479 (cond
7480 ((or (eq org-indirect-buffer-display 'new-frame)
7481 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7482 (select-frame (make-frame))
7483 (delete-other-windows)
7484 (org-pop-to-buffer-same-window ibuf)
7485 (org-set-frame-title heading))
7486 ((eq org-indirect-buffer-display 'dedicated-frame)
7487 (raise-frame
7488 (select-frame (or (and org-indirect-dedicated-frame
7489 (frame-live-p org-indirect-dedicated-frame)
7490 org-indirect-dedicated-frame)
7491 (setq org-indirect-dedicated-frame (make-frame)))))
7492 (delete-other-windows)
7493 (org-pop-to-buffer-same-window ibuf)
7494 (org-set-frame-title (concat "Indirect: " heading)))
7495 ((eq org-indirect-buffer-display 'current-window)
7496 (org-pop-to-buffer-same-window ibuf))
7497 ((eq org-indirect-buffer-display 'other-window)
7498 (pop-to-buffer ibuf))
7499 (t (error "Invalid value")))
7500 (if (featurep 'xemacs)
7501 (save-excursion (org-mode) (turn-on-font-lock)))
7502 (narrow-to-region beg end)
7503 (show-all)
7504 (goto-char pos)
7505 (run-hook-with-args 'org-cycle-hook 'all)
7506 (and (window-live-p cwin) (select-window cwin))))
7508 (defun org-get-indirect-buffer (&optional buffer)
7509 (setq buffer (or buffer (current-buffer)))
7510 (let ((n 1) (base (buffer-name buffer)) bname)
7511 (while (buffer-live-p
7512 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7513 (setq n (1+ n)))
7514 (condition-case nil
7515 (make-indirect-buffer buffer bname 'clone)
7516 (error (make-indirect-buffer buffer bname)))))
7518 (defun org-set-frame-title (title)
7519 "Set the title of the current frame to the string TITLE."
7520 ;; FIXME: how to name a single frame in XEmacs???
7521 (unless (featurep 'xemacs)
7522 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7524 ;;;; Structure editing
7526 ;;; Inserting headlines
7528 (defun org-previous-line-empty-p (&optional next)
7529 "Is the previous line a blank line?
7530 When NEXT is non-nil, check the next line instead."
7531 (save-excursion
7532 (and (not (bobp))
7533 (or (beginning-of-line (if next 2 0)) t)
7534 (save-match-data
7535 (looking-at "[ \t]*$")))))
7537 (defun org-insert-heading (&optional arg invisible-ok)
7538 "Insert a new heading or item with same depth at point.
7539 If point is in a plain list and ARG is nil, create a new list item.
7540 With one universal prefix argument, insert a heading even in lists.
7541 With two universal prefix arguments, insert the heading at the end
7542 of the parent subtree.
7544 If point is at the beginning of a headline, insert a sibling before
7545 the current headline. If point is not at the beginning, split the line
7546 and create a new headline with the text in the current line after point
7547 \(see `org-M-RET-may-split-line' on how to modify this behavior).
7549 If point is at the beginning of a normal line, turn this line into
7550 a heading.
7552 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7553 This is important for non-interactive uses of the command."
7554 (interactive "P")
7555 (if (org-called-interactively-p 'any) (org-reveal))
7556 (let ((itemp (org-in-item-p))
7557 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7558 (respect-content (or org-insert-heading-respect-content
7559 (equal arg '(16))))
7560 (initial-content "")
7561 (adjust-empty-lines t))
7563 (cond
7565 ((or (= (buffer-size) 0)
7566 (and (not (save-excursion
7567 (and (ignore-errors (org-back-to-heading invisible-ok))
7568 (org-at-heading-p))))
7569 (or arg (not itemp))))
7570 ;; At beginning of buffer or so hight up that only a heading makes sense.
7571 (insert
7572 (if (or (bobp) (org-previous-line-empty-p)) "" "\n")
7573 (if (org-in-src-block-p) ",* " "* "))
7574 (run-hooks 'org-insert-heading-hook))
7576 ((and itemp (not (equal arg '(4))))
7577 ;; Insert an item
7578 (org-insert-item))
7581 ;; Insert a heading
7582 (save-restriction
7583 (widen)
7584 (let* ((level nil)
7585 (on-heading (org-at-heading-p))
7586 (empty-line-p (if on-heading
7587 (org-previous-line-empty-p)
7588 ;; We will decide later
7589 nil))
7590 ;; Get a level string to fall back on
7591 (fix-level
7592 (save-excursion
7593 (org-back-to-heading t)
7594 (if (org-previous-line-empty-p) (setq empty-line-p t))
7595 (looking-at org-outline-regexp)
7596 (make-string (1- (length (match-string 0))) ?*)))
7597 (stars
7598 (save-excursion
7599 (condition-case nil
7600 (progn
7601 (org-back-to-heading invisible-ok)
7602 (when (and (not on-heading)
7603 (featurep 'org-inlinetask)
7604 (integerp org-inlinetask-min-level)
7605 (>= (length (match-string 0))
7606 org-inlinetask-min-level))
7607 ;; Find a heading level before the inline task
7608 (while (and (setq level (org-up-heading-safe))
7609 (>= level org-inlinetask-min-level)))
7610 (if (org-at-heading-p)
7611 (org-back-to-heading invisible-ok)
7612 (error "This should not happen")))
7613 (unless (and (save-excursion
7614 (save-match-data
7615 (org-backward-heading-same-level
7616 1 invisible-ok))
7617 (= (point) (match-beginning 0)))
7618 (not (org-previous-line-empty-p t)))
7619 (setq empty-line-p (or empty-line-p
7620 (org-previous-line-empty-p))))
7621 (match-string 0))
7622 (error (or fix-level "* ")))))
7623 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7624 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7625 pos hide-previous previous-pos)
7627 ;; If we insert after content, move there and clean up whitespace
7628 (when respect-content
7629 (org-end-of-subtree nil t)
7630 (when (looking-at "^\\*")
7631 (backward-char 1)
7632 (insert "\n")))
7634 ;; If we are splitting, grab the text that should be moved to the new headline
7635 (when may-split
7636 (if (org-on-heading-p)
7637 ;; This is a heading, we split intelligently (keeping tags)
7638 (let ((pos (point)))
7639 (goto-char (point-at-bol))
7640 (unless (looking-at org-complex-heading-regexp)
7641 (error "This should not happen"))
7642 (when (and (match-beginning 4)
7643 (> pos (match-beginning 4))
7644 (< pos (match-end 4)))
7645 (setq initial-content (buffer-substring pos (match-end 4)))
7646 (goto-char pos)
7647 (delete-region (point) (match-end 4))
7648 (if (looking-at "[ \t]*$")
7649 (replace-match "")
7650 (insert (make-string (length initial-content) ?\ )))
7651 (setq initial-content (org-trim initial-content)))
7652 (goto-char pos))
7653 ;; a normal line
7654 (unless (bolp)
7655 (setq initial-content (buffer-substring (point) (point-at-eol)))
7656 (delete-region (point) (point-at-eol))
7657 (setq initial-content (org-trim initial-content)))))
7659 ;; If we are at the beginning of the line, insert before it. Else after
7660 (cond
7661 ((and (bolp) (looking-at "[ \t]*$")))
7662 ((and (bolp) (not (looking-at "[ \t]*$")))
7663 (open-line 1))
7665 (goto-char (point-at-eol))
7666 (insert "\n")))
7668 ;; Insert the new heading
7669 (insert stars)
7670 (just-one-space)
7671 (insert initial-content)
7672 (when adjust-empty-lines
7673 (if (or (not blank)
7674 (and blank (not (org-previous-line-empty-p))))
7675 (org-N-empty-lines-before-current (if blank 1 0))))
7676 (run-hooks 'org-insert-heading-hook)))))))
7678 (defun org-N-empty-lines-before-current (N)
7679 "Make the number of empty lines before current exactly N.
7680 So this will delete or add empty lines."
7681 (save-excursion
7682 (goto-char (point-at-bol))
7683 (if (looking-back "\\s-+" nil 'greedy)
7684 (replace-match ""))
7685 (or (bobp) (insert "\n"))
7686 (while (> N 0)
7687 (insert "\n")
7688 (setq N (1- N)))))
7690 (defun org-get-heading (&optional no-tags no-todo)
7691 "Return the heading of the current entry, without the stars.
7692 When NO-TAGS is non-nil, don't include tags.
7693 When NO-TODO is non-nil, don't include TODO keywords."
7694 (save-excursion
7695 (org-back-to-heading t)
7696 (cond
7697 ((and no-tags no-todo)
7698 (looking-at org-complex-heading-regexp)
7699 (match-string 4))
7700 (no-tags
7701 (looking-at (concat org-outline-regexp
7702 "\\(.*?\\)"
7703 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7704 (match-string 1))
7705 (no-todo
7706 (looking-at org-todo-line-regexp)
7707 (match-string 3))
7708 (t (looking-at org-heading-regexp)
7709 (match-string 2)))))
7711 (defvar orgstruct-mode) ; defined below
7713 (defun org-heading-components ()
7714 "Return the components of the current heading.
7715 This is a list with the following elements:
7716 - the level as an integer
7717 - the reduced level, different if `org-odd-levels-only' is set.
7718 - the TODO keyword, or nil
7719 - the priority character, like ?A, or nil if no priority is given
7720 - the headline text itself, or the tags string if no headline text
7721 - the tags string, or nil."
7722 (save-excursion
7723 (org-back-to-heading t)
7724 (if (let (case-fold-search)
7725 (looking-at
7726 (if orgstruct-mode
7727 org-heading-regexp
7728 org-complex-heading-regexp)))
7729 (if orgstruct-mode
7730 (list (length (match-string 1))
7731 (org-reduced-level (length (match-string 1)))
7734 (match-string 2)
7735 nil)
7736 (list (length (match-string 1))
7737 (org-reduced-level (length (match-string 1)))
7738 (org-match-string-no-properties 2)
7739 (and (match-end 3) (aref (match-string 3) 2))
7740 (org-match-string-no-properties 4)
7741 (org-match-string-no-properties 5))))))
7743 (defun org-get-entry ()
7744 "Get the entry text, after heading, entire subtree."
7745 (save-excursion
7746 (org-back-to-heading t)
7747 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7749 (defun org-insert-heading-after-current ()
7750 "Insert a new heading with same level as current, after current subtree."
7751 (interactive)
7752 (org-back-to-heading)
7753 (org-insert-heading)
7754 (org-move-subtree-down)
7755 (end-of-line 1))
7757 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7758 "Insert heading with `org-insert-heading-respect-content' set to t."
7759 (interactive "P")
7760 (let ((org-insert-heading-respect-content t))
7761 (org-insert-heading '(4) invisible-ok)))
7763 (defun org-insert-todo-heading-respect-content (&optional force-state)
7764 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7765 (interactive "P")
7766 (let ((org-insert-heading-respect-content t))
7767 (org-insert-todo-heading force-state t)))
7769 (defun org-insert-todo-heading (arg &optional force-heading)
7770 "Insert a new heading with the same level and TODO state as current heading.
7771 If the heading has no TODO state, or if the state is DONE, use the first
7772 state (TODO by default). Also one prefix arg, force first state. With two
7773 prefix args, force inserting at the end of the parent subtree."
7774 (interactive "P")
7775 (when (or force-heading (not (org-insert-item 'checkbox)))
7776 (org-insert-heading (or (and (equal arg '(16)) '(16))
7777 force-heading))
7778 (save-excursion
7779 (org-back-to-heading)
7780 (outline-previous-heading)
7781 (looking-at org-todo-line-regexp))
7782 (let*
7783 ((new-mark-x
7784 (if (or arg
7785 (not (match-beginning 2))
7786 (member (match-string 2) org-done-keywords))
7787 (car org-todo-keywords-1)
7788 (match-string 2)))
7789 (new-mark
7791 (run-hook-with-args-until-success
7792 'org-todo-get-default-hook new-mark-x nil)
7793 new-mark-x)))
7794 (beginning-of-line 1)
7795 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7796 (if org-treat-insert-todo-heading-as-state-change
7797 (org-todo new-mark)
7798 (insert new-mark " "))))
7799 (when org-provide-todo-statistics
7800 (org-update-parent-todo-statistics))))
7802 (defun org-insert-subheading (arg)
7803 "Insert a new subheading and demote it.
7804 Works for outline headings and for plain lists alike."
7805 (interactive "P")
7806 (org-insert-heading arg)
7807 (cond
7808 ((org-at-heading-p) (org-do-demote))
7809 ((org-at-item-p) (org-indent-item))))
7811 (defun org-insert-todo-subheading (arg)
7812 "Insert a new subheading with TODO keyword or checkbox and demote it.
7813 Works for outline headings and for plain lists alike."
7814 (interactive "P")
7815 (org-insert-todo-heading arg)
7816 (cond
7817 ((org-at-heading-p) (org-do-demote))
7818 ((org-at-item-p) (org-indent-item))))
7820 ;;; Promotion and Demotion
7822 (defvar org-after-demote-entry-hook nil
7823 "Hook run after an entry has been demoted.
7824 The cursor will be at the beginning of the entry.
7825 When a subtree is being demoted, the hook will be called for each node.")
7827 (defvar org-after-promote-entry-hook nil
7828 "Hook run after an entry has been promoted.
7829 The cursor will be at the beginning of the entry.
7830 When a subtree is being promoted, the hook will be called for each node.")
7832 (defun org-promote-subtree ()
7833 "Promote the entire subtree.
7834 See also `org-promote'."
7835 (interactive)
7836 (save-excursion
7837 (org-with-limited-levels (org-map-tree 'org-promote)))
7838 (org-fix-position-after-promote))
7840 (defun org-demote-subtree ()
7841 "Demote the entire subtree. See `org-demote'.
7842 See also `org-promote'."
7843 (interactive)
7844 (save-excursion
7845 (org-with-limited-levels (org-map-tree 'org-demote)))
7846 (org-fix-position-after-promote))
7849 (defun org-do-promote ()
7850 "Promote the current heading higher up the tree.
7851 If the region is active in `transient-mark-mode', promote all headings
7852 in the region."
7853 (interactive)
7854 (save-excursion
7855 (if (org-region-active-p)
7856 (org-map-region 'org-promote (region-beginning) (region-end))
7857 (org-promote)))
7858 (org-fix-position-after-promote))
7860 (defun org-do-demote ()
7861 "Demote the current heading lower down the tree.
7862 If the region is active in `transient-mark-mode', demote all headings
7863 in the region."
7864 (interactive)
7865 (save-excursion
7866 (if (org-region-active-p)
7867 (org-map-region 'org-demote (region-beginning) (region-end))
7868 (org-demote)))
7869 (org-fix-position-after-promote))
7871 (defun org-fix-position-after-promote ()
7872 "Make sure that after pro/demotion cursor position is right."
7873 (let ((pos (point)))
7874 (when (save-excursion
7875 (beginning-of-line 1)
7876 (looking-at org-todo-line-regexp)
7877 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7878 (cond ((eobp) (insert " "))
7879 ((eolp) (insert " "))
7880 ((equal (char-after) ?\ ) (forward-char 1))))))
7882 (defun org-current-level ()
7883 "Return the level of the current entry, or nil if before the first headline.
7884 The level is the number of stars at the beginning of the headline."
7885 (save-excursion
7886 (org-with-limited-levels
7887 (if (ignore-errors (org-back-to-heading t))
7888 (funcall outline-level)))))
7890 (defun org-get-previous-line-level ()
7891 "Return the outline depth of the last headline before the current line.
7892 Returns 0 for the first headline in the buffer, and nil if before the
7893 first headline."
7894 (let ((current-level (org-current-level))
7895 (prev-level (when (> (line-number-at-pos) 1)
7896 (save-excursion
7897 (beginning-of-line 0)
7898 (org-current-level)))))
7899 (cond ((null current-level) nil) ; Before first headline
7900 ((null prev-level) 0) ; At first headline
7901 (prev-level))))
7903 (defun org-reduced-level (l)
7904 "Compute the effective level of a heading.
7905 This takes into account the setting of `org-odd-levels-only'."
7906 (cond
7907 ((zerop l) 0)
7908 (org-odd-levels-only (1+ (floor (/ l 2))))
7909 (t l)))
7911 (defun org-level-increment ()
7912 "Return the number of stars that will be added or removed at a
7913 time to headlines when structure editing, based on the value of
7914 `org-odd-levels-only'."
7915 (if org-odd-levels-only 2 1))
7917 (defun org-get-valid-level (level &optional change)
7918 "Rectify a level change under the influence of `org-odd-levels-only'
7919 LEVEL is a current level, CHANGE is by how much the level should be
7920 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7921 even level numbers will become the next higher odd number."
7922 (if org-odd-levels-only
7923 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7924 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7925 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7926 (max 1 (+ level (or change 0)))))
7928 (if (boundp 'define-obsolete-function-alias)
7929 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7930 (define-obsolete-function-alias 'org-get-legal-level
7931 'org-get-valid-level)
7932 (define-obsolete-function-alias 'org-get-legal-level
7933 'org-get-valid-level "23.1")))
7935 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7936 ;; ̀org-with-limited-levels'
7937 (defun org-promote ()
7938 "Promote the current heading higher up the tree.
7939 If the region is active in `transient-mark-mode', promote all headings
7940 in the region."
7941 (org-back-to-heading t)
7942 (let* ((level (save-match-data (funcall outline-level)))
7943 (after-change-functions (remove 'flyspell-after-change-function
7944 after-change-functions))
7945 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7946 (diff (abs (- level (length up-head) -1))))
7947 (cond ((and (= level 1) org-called-with-limited-levels
7948 org-allow-promoting-top-level-subtree)
7949 (replace-match "# " nil t))
7950 ((= level 1)
7951 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
7952 (t (replace-match up-head nil t)))
7953 ;; Fixup tag positioning
7954 (unless (= level 1)
7955 (and org-auto-align-tags (org-set-tags nil t))
7956 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7957 (run-hooks 'org-after-promote-entry-hook)))
7959 (defun org-demote ()
7960 "Demote the current heading lower down the tree.
7961 If the region is active in `transient-mark-mode', demote all headings
7962 in the region."
7963 (org-back-to-heading t)
7964 (let* ((level (save-match-data (funcall outline-level)))
7965 (after-change-functions (remove 'flyspell-after-change-function
7966 after-change-functions))
7967 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7968 (diff (abs (- level (length down-head) -1))))
7969 (replace-match down-head nil t)
7970 ;; Fixup tag positioning
7971 (and org-auto-align-tags (org-set-tags nil t))
7972 (if org-adapt-indentation (org-fixup-indentation diff))
7973 (run-hooks 'org-after-demote-entry-hook)))
7975 (defun org-cycle-level ()
7976 "Cycle the level of an empty headline through possible states.
7977 This goes first to child, then to parent, level, then up the hierarchy.
7978 After top level, it switches back to sibling level."
7979 (interactive)
7980 (let ((org-adapt-indentation nil))
7981 (when (org-point-at-end-of-empty-headline)
7982 (setq this-command 'org-cycle-level) ; Only needed for caching
7983 (let ((cur-level (org-current-level))
7984 (prev-level (org-get-previous-line-level)))
7985 (cond
7986 ;; If first headline in file, promote to top-level.
7987 ((= prev-level 0)
7988 (loop repeat (/ (- cur-level 1) (org-level-increment))
7989 do (org-do-promote)))
7990 ;; If same level as prev, demote one.
7991 ((= prev-level cur-level)
7992 (org-do-demote))
7993 ;; If parent is top-level, promote to top level if not already.
7994 ((= prev-level 1)
7995 (loop repeat (/ (- cur-level 1) (org-level-increment))
7996 do (org-do-promote)))
7997 ;; If top-level, return to prev-level.
7998 ((= cur-level 1)
7999 (loop repeat (/ (- prev-level 1) (org-level-increment))
8000 do (org-do-demote)))
8001 ;; If less than prev-level, promote one.
8002 ((< cur-level prev-level)
8003 (org-do-promote))
8004 ;; If deeper than prev-level, promote until higher than
8005 ;; prev-level.
8006 ((> cur-level prev-level)
8007 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8008 do (org-do-promote))))
8009 t))))
8011 (defun org-map-tree (fun)
8012 "Call FUN for every heading underneath the current one."
8013 (org-back-to-heading)
8014 (let ((level (funcall outline-level)))
8015 (save-excursion
8016 (funcall fun)
8017 (while (and (progn
8018 (outline-next-heading)
8019 (> (funcall outline-level) level))
8020 (not (eobp)))
8021 (funcall fun)))))
8023 (defun org-map-region (fun beg end)
8024 "Call FUN for every heading between BEG and END."
8025 (let ((org-ignore-region t))
8026 (save-excursion
8027 (setq end (copy-marker end))
8028 (goto-char beg)
8029 (if (and (re-search-forward org-outline-regexp-bol nil t)
8030 (< (point) end))
8031 (funcall fun))
8032 (while (and (progn
8033 (outline-next-heading)
8034 (< (point) end))
8035 (not (eobp)))
8036 (funcall fun)))))
8038 (defvar org-property-end-re) ; silence byte-compiler
8039 (defun org-fixup-indentation (diff)
8040 "Change the indentation in the current entry by DIFF.
8041 However, if any line in the current entry has no indentation, or if it
8042 would end up with no indentation after the change, nothing at all is done."
8043 (save-excursion
8044 (let ((end (save-excursion (outline-next-heading)
8045 (point-marker)))
8046 (prohibit (if (> diff 0)
8047 "^\\S-"
8048 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8049 col)
8050 (unless (save-excursion (end-of-line 1)
8051 (re-search-forward prohibit end t))
8052 (while (and (< (point) end)
8053 (re-search-forward "^[ \t]+" end t))
8054 (goto-char (match-end 0))
8055 (setq col (current-column))
8056 (if (< diff 0) (replace-match ""))
8057 (org-indent-to-column (+ diff col))))
8058 (move-marker end nil))))
8060 (defun org-convert-to-odd-levels ()
8061 "Convert an org-mode file with all levels allowed to one with odd levels.
8062 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8063 level 5 etc."
8064 (interactive)
8065 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8066 (let ((outline-level 'org-outline-level)
8067 (org-odd-levels-only nil) n)
8068 (save-excursion
8069 (goto-char (point-min))
8070 (while (re-search-forward "^\\*\\*+ " nil t)
8071 (setq n (- (length (match-string 0)) 2))
8072 (while (>= (setq n (1- n)) 0)
8073 (org-demote))
8074 (end-of-line 1))))))
8076 (defun org-convert-to-oddeven-levels ()
8077 "Convert an org-mode file with only odd levels to one with odd/even levels.
8078 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8079 file contains a section with an even level, conversion would
8080 destroy the structure of the file. An error is signaled in this
8081 case."
8082 (interactive)
8083 (goto-char (point-min))
8084 ;; First check if there are no even levels
8085 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8086 (org-show-context t)
8087 (error "Not all levels are odd in this file. Conversion not possible"))
8088 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8089 (let ((outline-regexp org-outline-regexp)
8090 (outline-level 'org-outline-level)
8091 (org-odd-levels-only nil) n)
8092 (save-excursion
8093 (goto-char (point-min))
8094 (while (re-search-forward "^\\*\\*+ " nil t)
8095 (setq n (/ (1- (length (match-string 0))) 2))
8096 (while (>= (setq n (1- n)) 0)
8097 (org-promote))
8098 (end-of-line 1))))))
8100 (defun org-tr-level (n)
8101 "Make N odd if required."
8102 (if org-odd-levels-only (1+ (/ n 2)) n))
8104 ;;; Vertical tree motion, cutting and pasting of subtrees
8106 (defun org-move-subtree-up (&optional arg)
8107 "Move the current subtree up past ARG headlines of the same level."
8108 (interactive "p")
8109 (org-move-subtree-down (- (prefix-numeric-value arg))))
8111 (defun org-move-subtree-down (&optional arg)
8112 "Move the current subtree down past ARG headlines of the same level."
8113 (interactive "p")
8114 (setq arg (prefix-numeric-value arg))
8115 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8116 'org-get-last-sibling))
8117 (ins-point (make-marker))
8118 (cnt (abs arg))
8119 (col (current-column))
8120 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8121 ;; Select the tree
8122 (org-back-to-heading)
8123 (setq beg0 (point))
8124 (save-excursion
8125 (setq ne-beg (org-back-over-empty-lines))
8126 (setq beg (point)))
8127 (save-match-data
8128 (save-excursion (outline-end-of-heading)
8129 (setq folded (outline-invisible-p)))
8130 (outline-end-of-subtree))
8131 (outline-next-heading)
8132 (setq ne-end (org-back-over-empty-lines))
8133 (setq end (point))
8134 (goto-char beg0)
8135 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8136 ;; include less whitespace
8137 (save-excursion
8138 (goto-char beg)
8139 (forward-line (- ne-beg ne-end))
8140 (setq beg (point))))
8141 ;; Find insertion point, with error handling
8142 (while (> cnt 0)
8143 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8144 (progn (goto-char beg0)
8145 (user-error "Cannot move past superior level or buffer limit")))
8146 (setq cnt (1- cnt)))
8147 (if (> arg 0)
8148 ;; Moving forward - still need to move over subtree
8149 (progn (org-end-of-subtree t t)
8150 (save-excursion
8151 (org-back-over-empty-lines)
8152 (or (bolp) (newline)))))
8153 (setq ne-ins (org-back-over-empty-lines))
8154 (move-marker ins-point (point))
8155 (setq txt (buffer-substring beg end))
8156 (org-save-markers-in-region beg end)
8157 (delete-region beg end)
8158 (org-remove-empty-overlays-at beg)
8159 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8160 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8161 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8162 (let ((bbb (point)))
8163 (insert-before-markers txt)
8164 (org-reinstall-markers-in-region bbb)
8165 (move-marker ins-point bbb))
8166 (or (bolp) (insert "\n"))
8167 (setq ins-end (point))
8168 (goto-char ins-point)
8169 (org-skip-whitespace)
8170 (when (and (< arg 0)
8171 (org-first-sibling-p)
8172 (> ne-ins ne-beg))
8173 ;; Move whitespace back to beginning
8174 (save-excursion
8175 (goto-char ins-end)
8176 (let ((kill-whole-line t))
8177 (kill-line (- ne-ins ne-beg)) (point)))
8178 (insert (make-string (- ne-ins ne-beg) ?\n)))
8179 (move-marker ins-point nil)
8180 (if folded
8181 (hide-subtree)
8182 (org-show-entry)
8183 (show-children)
8184 (org-cycle-hide-drawers 'children))
8185 (org-clean-visibility-after-subtree-move)
8186 ;; move back to the initial column we were at
8187 (move-to-column col)))
8189 (defvar org-subtree-clip ""
8190 "Clipboard for cut and paste of subtrees.
8191 This is actually only a copy of the kill, because we use the normal kill
8192 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8194 (defvar org-subtree-clip-folded nil
8195 "Was the last copied subtree folded?
8196 This is used to fold the tree back after pasting.")
8198 (defun org-cut-subtree (&optional n)
8199 "Cut the current subtree into the clipboard.
8200 With prefix arg N, cut this many sequential subtrees.
8201 This is a short-hand for marking the subtree and then cutting it."
8202 (interactive "p")
8203 (org-copy-subtree n 'cut))
8205 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8206 "Copy the current subtree it in the clipboard.
8207 With prefix arg N, copy this many sequential subtrees.
8208 This is a short-hand for marking the subtree and then copying it.
8209 If CUT is non-nil, actually cut the subtree.
8210 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8211 of some markers in the region, even if CUT is non-nil. This is
8212 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8213 (interactive "p")
8214 (let (beg end folded (beg0 (point)))
8215 (if (org-called-interactively-p 'any)
8216 (org-back-to-heading nil) ; take what looks like a subtree
8217 (org-back-to-heading t)) ; take what is really there
8218 (setq beg (point))
8219 (skip-chars-forward " \t\r\n")
8220 (save-match-data
8221 (if nosubtrees
8222 (outline-next-heading)
8223 (save-excursion (outline-end-of-heading)
8224 (setq folded (outline-invisible-p)))
8225 (condition-case nil
8226 (org-forward-heading-same-level (1- n) t)
8227 (error nil))
8228 (org-end-of-subtree t t)))
8229 (setq end (point))
8230 (goto-char beg0)
8231 (when (> end beg)
8232 (setq org-subtree-clip-folded folded)
8233 (when (or cut force-store-markers)
8234 (org-save-markers-in-region beg end))
8235 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8236 (setq org-subtree-clip (current-kill 0))
8237 (message "%s: Subtree(s) with %d characters"
8238 (if cut "Cut" "Copied")
8239 (length org-subtree-clip)))))
8241 (defun org-paste-subtree (&optional level tree for-yank)
8242 "Paste the clipboard as a subtree, with modification of headline level.
8243 The entire subtree is promoted or demoted in order to match a new headline
8244 level.
8246 If the cursor is at the beginning of a headline, the same level as
8247 that headline is used to paste the tree.
8249 If not, the new level is derived from the *visible* headings
8250 before and after the insertion point, and taken to be the inferior headline
8251 level of the two. So if the previous visible heading is level 3 and the
8252 next is level 4 (or vice versa), level 4 will be used for insertion.
8253 This makes sure that the subtree remains an independent subtree and does
8254 not swallow low level entries.
8256 You can also force a different level, either by using a numeric prefix
8257 argument, or by inserting the heading marker by hand. For example, if the
8258 cursor is after \"*****\", then the tree will be shifted to level 5.
8260 If optional TREE is given, use this text instead of the kill ring.
8262 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8263 move back over whitespace before inserting, and move point to the end of
8264 the inserted text when done."
8265 (interactive "P")
8266 (setq tree (or tree (and kill-ring (current-kill 0))))
8267 (unless (org-kill-is-subtree-p tree)
8268 (user-error "%s"
8269 (substitute-command-keys
8270 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8271 (org-with-limited-levels
8272 (let* ((visp (not (outline-invisible-p)))
8273 (txt tree)
8274 (^re_ "\\(\\*+\\)[ \t]*")
8275 (old-level (if (string-match org-outline-regexp-bol txt)
8276 (- (match-end 0) (match-beginning 0) 1)
8277 -1))
8278 (force-level (cond (level (prefix-numeric-value level))
8279 ((and (looking-at "[ \t]*$")
8280 (string-match
8281 "^\\*+$" (buffer-substring
8282 (point-at-bol) (point))))
8283 (- (match-end 1) (match-beginning 1)))
8284 ((and (bolp)
8285 (looking-at org-outline-regexp))
8286 (- (match-end 0) (point) 1))))
8287 (previous-level (save-excursion
8288 (condition-case nil
8289 (progn
8290 (outline-previous-visible-heading 1)
8291 (if (looking-at ^re_)
8292 (- (match-end 0) (match-beginning 0) 1)
8294 (error 1))))
8295 (next-level (save-excursion
8296 (condition-case nil
8297 (progn
8298 (or (looking-at org-outline-regexp)
8299 (outline-next-visible-heading 1))
8300 (if (looking-at ^re_)
8301 (- (match-end 0) (match-beginning 0) 1)
8303 (error 1))))
8304 (new-level (or force-level (max previous-level next-level)))
8305 (shift (if (or (= old-level -1)
8306 (= new-level -1)
8307 (= old-level new-level))
8309 (- new-level old-level)))
8310 (delta (if (> shift 0) -1 1))
8311 (func (if (> shift 0) 'org-demote 'org-promote))
8312 (org-odd-levels-only nil)
8313 beg end newend)
8314 ;; Remove the forced level indicator
8315 (if force-level
8316 (delete-region (point-at-bol) (point)))
8317 ;; Paste
8318 (beginning-of-line (if (bolp) 1 2))
8319 (setq beg (point))
8320 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8321 (insert-before-markers txt)
8322 (unless (string-match "\n\\'" txt) (insert "\n"))
8323 (setq newend (point))
8324 (org-reinstall-markers-in-region beg)
8325 (setq end (point))
8326 (goto-char beg)
8327 (skip-chars-forward " \t\n\r")
8328 (setq beg (point))
8329 (if (and (outline-invisible-p) visp)
8330 (save-excursion (outline-show-heading)))
8331 ;; Shift if necessary
8332 (unless (= shift 0)
8333 (save-restriction
8334 (narrow-to-region beg end)
8335 (while (not (= shift 0))
8336 (org-map-region func (point-min) (point-max))
8337 (setq shift (+ delta shift)))
8338 (goto-char (point-min))
8339 (setq newend (point-max))))
8340 (when (or (org-called-interactively-p 'interactive) for-yank)
8341 (message "Clipboard pasted as level %d subtree" new-level))
8342 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8343 kill-ring
8344 (eq org-subtree-clip (current-kill 0))
8345 org-subtree-clip-folded)
8346 ;; The tree was folded before it was killed/copied
8347 (hide-subtree))
8348 (and for-yank (goto-char newend)))))
8350 (defun org-kill-is-subtree-p (&optional txt)
8351 "Check if the current kill is an outline subtree, or a set of trees.
8352 Returns nil if kill does not start with a headline, or if the first
8353 headline level is not the largest headline level in the tree.
8354 So this will actually accept several entries of equal levels as well,
8355 which is OK for `org-paste-subtree'.
8356 If optional TXT is given, check this string instead of the current kill."
8357 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8358 (re (org-get-limited-outline-regexp))
8359 (^re (concat "^" re))
8360 (start-level (and kill
8361 (string-match
8362 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8363 kill)
8364 (- (match-end 2) (match-beginning 2) 1)))
8365 (start (1+ (or (match-beginning 2) -1))))
8366 (if (not start-level)
8367 (progn
8368 nil) ;; does not even start with a heading
8369 (catch 'exit
8370 (while (setq start (string-match ^re kill (1+ start)))
8371 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8372 (throw 'exit nil)))
8373 t))))
8375 (defvar org-markers-to-move nil
8376 "Markers that should be moved with a cut-and-paste operation.
8377 Those markers are stored together with their positions relative to
8378 the start of the region.")
8380 (defun org-save-markers-in-region (beg end)
8381 "Check markers in region.
8382 If these markers are between BEG and END, record their position relative
8383 to BEG, so that after moving the block of text, we can put the markers back
8384 into place.
8385 This function gets called just before an entry or tree gets cut from the
8386 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8387 called immediately, to move the markers with the entries."
8388 (setq org-markers-to-move nil)
8389 (when (featurep 'org-clock)
8390 (org-clock-save-markers-for-cut-and-paste beg end))
8391 (when (featurep 'org-agenda)
8392 (org-agenda-save-markers-for-cut-and-paste beg end)))
8394 (defun org-check-and-save-marker (marker beg end)
8395 "Check if MARKER is between BEG and END.
8396 If yes, remember the marker and the distance to BEG."
8397 (when (and (marker-buffer marker)
8398 (equal (marker-buffer marker) (current-buffer)))
8399 (if (and (>= marker beg) (< marker end))
8400 (push (cons marker (- marker beg)) org-markers-to-move))))
8402 (defun org-reinstall-markers-in-region (beg)
8403 "Move all remembered markers to their position relative to BEG."
8404 (mapc (lambda (x)
8405 (move-marker (car x) (+ beg (cdr x))))
8406 org-markers-to-move)
8407 (setq org-markers-to-move nil))
8409 (defun org-narrow-to-subtree ()
8410 "Narrow buffer to the current subtree."
8411 (interactive)
8412 (save-excursion
8413 (save-match-data
8414 (org-with-limited-levels
8415 (narrow-to-region
8416 (progn (org-back-to-heading t) (point))
8417 (progn (org-end-of-subtree t t)
8418 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8419 (point)))))))
8421 (defun org-narrow-to-block ()
8422 "Narrow buffer to the current block."
8423 (interactive)
8424 (let* ((case-fold-search t)
8425 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8426 "^[ \t]*#\\+end_.*")))
8427 (if blockp
8428 (narrow-to-region (car blockp) (cdr blockp))
8429 (user-error "Not in a block"))))
8431 (eval-when-compile
8432 (defvar org-property-drawer-re))
8434 (defvar org-property-start-re) ;; defined below
8435 (defun org-clone-subtree-with-time-shift (n &optional shift)
8436 "Clone the task (subtree) at point N times.
8437 The clones will be inserted as siblings.
8439 In interactive use, the user will be prompted for the number of
8440 clones to be produced. If the entry has a timestamp, the user
8441 will also be prompted for a time shift, which may be a repeater
8442 as used in time stamps, for example `+3d'. To disable this,
8443 you can call the function with a universal prefix argument.
8445 When a valid repeater is given and the entry contains any time
8446 stamps, the clones will become a sequence in time, with time
8447 stamps in the subtree shifted for each clone produced. If SHIFT
8448 is nil or the empty string, time stamps will be left alone. The
8449 ID property of the original subtree is removed.
8451 If the original subtree did contain time stamps with a repeater,
8452 the following will happen:
8453 - the repeater will be removed in each clone
8454 - an additional clone will be produced, with the current, unshifted
8455 date(s) in the entry.
8456 - the original entry will be placed *after* all the clones, with
8457 repeater intact.
8458 - the start days in the repeater in the original entry will be shifted
8459 to past the last clone.
8460 In this way you can spell out a number of instances of a repeating task,
8461 and still retain the repeater to cover future instances of the task."
8462 (interactive "nNumber of clones to produce: ")
8463 (let ((shift
8464 (or shift
8465 (if (and (not (equal current-prefix-arg '(4)))
8466 (save-excursion
8467 (re-search-forward org-ts-regexp-both
8468 (save-excursion
8469 (org-end-of-subtree t)
8470 (point)) t)))
8471 (read-from-minibuffer
8472 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8473 ""))) ;; No time shift
8474 (n-no-remove -1)
8475 (drawer-re org-drawer-regexp)
8476 beg end template task idprop
8477 shift-n shift-what doshift nmin nmax)
8478 (if (not (and (integerp n) (> n 0)))
8479 (error "Invalid number of replications %s" n))
8480 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8481 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8482 shift)))
8483 (error "Invalid shift specification %s" shift))
8484 (when doshift
8485 (setq shift-n (string-to-number (match-string 1 shift))
8486 shift-what (cdr (assoc (match-string 2 shift)
8487 '(("d" . day) ("w" . week)
8488 ("m" . month) ("y" . year))))))
8489 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8490 (setq nmin 1 nmax n)
8491 (org-back-to-heading t)
8492 (setq beg (point))
8493 (setq idprop (org-entry-get nil "ID"))
8494 (org-end-of-subtree t t)
8495 (or (bolp) (insert "\n"))
8496 (setq end (point))
8497 (setq template (buffer-substring beg end))
8498 (when (and doshift
8499 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8500 (delete-region beg end)
8501 (setq end beg)
8502 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8503 (goto-char end)
8504 (loop for n from nmin to nmax do
8505 ;; prepare clone
8506 (with-temp-buffer
8507 (insert template)
8508 (org-mode)
8509 (goto-char (point-min))
8510 (org-show-subtree)
8511 (and idprop (if org-clone-delete-id
8512 (org-entry-delete nil "ID")
8513 (org-id-get-create t)))
8514 (unless (= n 0)
8515 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8516 (kill-whole-line))
8517 (goto-char (point-min))
8518 (while (re-search-forward drawer-re nil t)
8519 (mapc (lambda (d)
8520 (org-remove-empty-drawer-at d (point))) org-drawers)))
8521 (goto-char (point-min))
8522 (when doshift
8523 (while (re-search-forward org-ts-regexp-both nil t)
8524 (org-timestamp-change (* n shift-n) shift-what))
8525 (unless (= n n-no-remove)
8526 (goto-char (point-min))
8527 (while (re-search-forward org-ts-regexp nil t)
8528 (save-excursion
8529 (goto-char (match-beginning 0))
8530 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8531 (delete-region (match-beginning 1) (match-end 1)))))))
8532 (setq task (buffer-string)))
8533 (insert task))
8534 (goto-char beg)))
8536 ;;; Outline Sorting
8538 (defun org-sort (with-case)
8539 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8540 Optional argument WITH-CASE means sort case-sensitively."
8541 (interactive "P")
8542 (cond
8543 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8544 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8546 (org-call-with-arg 'org-sort-entries with-case))))
8548 (defun org-sort-remove-invisible (s)
8549 "Remove invisible links from string S."
8550 (remove-text-properties 0 (length s) org-rm-props s)
8551 (while (string-match org-bracket-link-regexp s)
8552 (setq s (replace-match (if (match-end 2)
8553 (match-string 3 s)
8554 (match-string 1 s)) t t s)))
8555 (let ((st (format " %s " s)))
8556 (while (string-match org-emph-re st)
8557 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8558 (setq s (substring st 1 -1)))
8561 (defvar org-priority-regexp) ; defined later in the file
8563 (defvar org-after-sorting-entries-or-items-hook nil
8564 "Hook that is run after a bunch of entries or items have been sorted.
8565 When children are sorted, the cursor is in the parent line when this
8566 hook gets called. When a region or a plain list is sorted, the cursor
8567 will be in the first entry of the sorted region/list.")
8569 (defun org-sort-entries
8570 (&optional with-case sorting-type getkey-func compare-func property)
8571 "Sort entries on a certain level of an outline tree.
8572 If there is an active region, the entries in the region are sorted.
8573 Else, if the cursor is before the first entry, sort the top-level items.
8574 Else, the children of the entry at point are sorted.
8576 Sorting can be alphabetically, numerically, by date/time as given by
8577 a time stamp, by a property, by priority order, or by a custom function.
8579 The command prompts for the sorting type unless it has been given to the
8580 function through the SORTING-TYPE argument, which needs to be a character,
8581 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8582 precise meaning of each character:
8584 n Numerically, by converting the beginning of the entry/item to a number.
8585 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8586 o By order of TODO keywords.
8587 t By date/time, either the first active time stamp in the entry, or, if
8588 none exist, by the first inactive one.
8589 s By the scheduled date/time.
8590 d By deadline date/time.
8591 c By creation time, which is assumed to be the first inactive time stamp
8592 at the beginning of a line.
8593 p By priority according to the cookie.
8594 r By the value of a property.
8596 Capital letters will reverse the sort order.
8598 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8599 called with point at the beginning of the record. It must return either
8600 a string or a number that should serve as the sorting key for that record.
8602 Comparing entries ignores case by default. However, with an optional argument
8603 WITH-CASE, the sorting considers case as well.
8605 Sorting is done against the visible part of the headlines, it ignores hidden
8606 links."
8607 (interactive "P")
8608 (let ((case-func (if with-case 'identity 'downcase))
8609 (cmstr
8610 ;; The clock marker is lost when using `sort-subr', let's
8611 ;; store the clocking string.
8612 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8613 (save-excursion
8614 (goto-char org-clock-marker)
8615 (looking-back "^.*") (match-string-no-properties 0))))
8616 start beg end stars re re2
8617 txt what tmp)
8618 ;; Find beginning and end of region to sort
8619 (cond
8620 ((org-region-active-p)
8621 ;; we will sort the region
8622 (setq end (region-end)
8623 what "region")
8624 (goto-char (region-beginning))
8625 (if (not (org-at-heading-p)) (outline-next-heading))
8626 (setq start (point)))
8627 ((or (org-at-heading-p)
8628 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8629 ;; we will sort the children of the current headline
8630 (org-back-to-heading)
8631 (setq start (point)
8632 end (progn (org-end-of-subtree t t)
8633 (or (bolp) (insert "\n"))
8634 (org-back-over-empty-lines)
8635 (point))
8636 what "children")
8637 (goto-char start)
8638 (show-subtree)
8639 (outline-next-heading))
8641 ;; we will sort the top-level entries in this file
8642 (goto-char (point-min))
8643 (or (org-at-heading-p) (outline-next-heading))
8644 (setq start (point))
8645 (goto-char (point-max))
8646 (beginning-of-line 1)
8647 (when (looking-at ".*?\\S-")
8648 ;; File ends in a non-white line
8649 (end-of-line 1)
8650 (insert "\n"))
8651 (setq end (point-max))
8652 (setq what "top-level")
8653 (goto-char start)
8654 (show-all)))
8656 (setq beg (point))
8657 (if (>= beg end) (user-error "Nothing to sort"))
8659 (looking-at "\\(\\*+\\)")
8660 (setq stars (match-string 1)
8661 re (concat "^" (regexp-quote stars) " +")
8662 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8663 txt (buffer-substring beg end))
8664 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8665 (if (and (not (equal stars "*")) (string-match re2 txt))
8666 (user-error "Region to sort contains a level above the first entry"))
8668 (unless sorting-type
8669 (message
8670 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8671 [t]ime [s]cheduled [d]eadline [c]reated
8672 A/N/P/R/O/F/T/S/D/C means reversed:"
8673 what)
8674 (setq sorting-type (read-char-exclusive))
8676 (unless getkey-func
8677 (and (= (downcase sorting-type) ?f)
8678 (setq getkey-func
8679 (org-icompleting-read "Sort using function: "
8680 obarray 'fboundp t nil nil))
8681 (setq getkey-func (intern getkey-func))))
8683 (and (= (downcase sorting-type) ?r)
8684 (not property)
8685 (setq property
8686 (org-icompleting-read "Property: "
8687 (mapcar 'list (org-buffer-property-keys t))
8688 nil t))))
8690 (message "Sorting entries...")
8692 (save-restriction
8693 (narrow-to-region start end)
8694 (let ((dcst (downcase sorting-type))
8695 (case-fold-search nil)
8696 (now (current-time)))
8697 (sort-subr
8698 (/= dcst sorting-type)
8699 ;; This function moves to the beginning character of the "record" to
8700 ;; be sorted.
8701 (lambda nil
8702 (if (re-search-forward re nil t)
8703 (goto-char (match-beginning 0))
8704 (goto-char (point-max))))
8705 ;; This function moves to the last character of the "record" being
8706 ;; sorted.
8707 (lambda nil
8708 (save-match-data
8709 (condition-case nil
8710 (outline-forward-same-level 1)
8711 (error
8712 (goto-char (point-max))))))
8713 ;; This function returns the value that gets sorted against.
8714 (lambda nil
8715 (cond
8716 ((= dcst ?n)
8717 (if (looking-at org-complex-heading-regexp)
8718 (string-to-number (org-sort-remove-invisible (match-string 4)))
8719 nil))
8720 ((= dcst ?a)
8721 (if (looking-at org-complex-heading-regexp)
8722 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8723 nil))
8724 ((= dcst ?t)
8725 (let ((end (save-excursion (outline-next-heading) (point))))
8726 (if (or (re-search-forward org-ts-regexp end t)
8727 (re-search-forward org-ts-regexp-both end t))
8728 (org-time-string-to-seconds (match-string 0))
8729 (org-float-time now))))
8730 ((= dcst ?c)
8731 (let ((end (save-excursion (outline-next-heading) (point))))
8732 (if (re-search-forward
8733 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8734 end t)
8735 (org-time-string-to-seconds (match-string 0))
8736 (org-float-time now))))
8737 ((= dcst ?s)
8738 (let ((end (save-excursion (outline-next-heading) (point))))
8739 (if (re-search-forward org-scheduled-time-regexp end t)
8740 (org-time-string-to-seconds (match-string 1))
8741 (org-float-time now))))
8742 ((= dcst ?d)
8743 (let ((end (save-excursion (outline-next-heading) (point))))
8744 (if (re-search-forward org-deadline-time-regexp end t)
8745 (org-time-string-to-seconds (match-string 1))
8746 (org-float-time now))))
8747 ((= dcst ?p)
8748 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8749 (string-to-char (match-string 2))
8750 org-default-priority))
8751 ((= dcst ?r)
8752 (or (org-entry-get nil property) ""))
8753 ((= dcst ?o)
8754 (if (looking-at org-complex-heading-regexp)
8755 (- 9999 (length (member (match-string 2)
8756 org-todo-keywords-1)))))
8757 ((= dcst ?f)
8758 (if getkey-func
8759 (progn
8760 (setq tmp (funcall getkey-func))
8761 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8762 tmp)
8763 (error "Invalid key function `%s'" getkey-func)))
8764 (t (error "Invalid sorting type `%c'" sorting-type))))
8766 (cond
8767 ((= dcst ?a) 'string<)
8768 ((= dcst ?f) compare-func)
8769 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8770 (run-hooks 'org-after-sorting-entries-or-items-hook)
8771 ;; Reset the clock marker if needed
8772 (when cmstr
8773 (save-excursion
8774 (goto-char start)
8775 (search-forward cmstr nil t)
8776 (move-marker org-clock-marker (point))))
8777 (message "Sorting entries...done")))
8779 (defun org-do-sort (table what &optional with-case sorting-type)
8780 "Sort TABLE of WHAT according to SORTING-TYPE.
8781 The user will be prompted for the SORTING-TYPE if the call to this
8782 function does not specify it. WHAT is only for the prompt, to indicate
8783 what is being sorted. The sorting key will be extracted from
8784 the car of the elements of the table.
8785 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8786 (unless sorting-type
8787 (message
8788 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8789 what)
8790 (setq sorting-type (read-char-exclusive)))
8791 (let ((dcst (downcase sorting-type))
8792 extractfun comparefun)
8793 ;; Define the appropriate functions
8794 (cond
8795 ((= dcst ?n)
8796 (setq extractfun 'string-to-number
8797 comparefun (if (= dcst sorting-type) '< '>)))
8798 ((= dcst ?a)
8799 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8800 (lambda(x) (downcase (org-sort-remove-invisible x))))
8801 comparefun (if (= dcst sorting-type)
8802 'string<
8803 (lambda (a b) (and (not (string< a b))
8804 (not (string= a b)))))))
8805 ((= dcst ?t)
8806 (setq extractfun
8807 (lambda (x)
8808 (if (or (string-match org-ts-regexp x)
8809 (string-match org-ts-regexp-both x))
8810 (org-float-time
8811 (org-time-string-to-time (match-string 0 x)))
8813 comparefun (if (= dcst sorting-type) '< '>)))
8814 (t (error "Invalid sorting type `%c'" sorting-type)))
8816 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8817 table)
8818 (lambda (a b) (funcall comparefun (car a) (car b))))))
8821 ;;; The orgstruct minor mode
8823 ;; Define a minor mode which can be used in other modes in order to
8824 ;; integrate the org-mode structure editing commands.
8826 ;; This is really a hack, because the org-mode structure commands use
8827 ;; keys which normally belong to the major mode. Here is how it
8828 ;; works: The minor mode defines all the keys necessary to operate the
8829 ;; structure commands, but wraps the commands into a function which
8830 ;; tests if the cursor is currently at a headline or a plain list
8831 ;; item. If that is the case, the structure command is used,
8832 ;; temporarily setting many Org-mode variables like regular
8833 ;; expressions for filling etc. However, when any of those keys is
8834 ;; used at a different location, function uses `key-binding' to look
8835 ;; up if the key has an associated command in another currently active
8836 ;; keymap (minor modes, major mode, global), and executes that
8837 ;; command. There might be problems if any of the keys is otherwise
8838 ;; used as a prefix key.
8840 (defcustom orgstruct-heading-prefix-regexp nil
8841 "Regexp that matches the custom prefix of Org headlines in
8842 orgstruct(++)-mode."
8843 :group 'org
8844 :version "24.4"
8845 :package-version '(Org . "8.0")
8846 :type 'string)
8847 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8849 (defcustom orgstruct-setup-hook nil
8850 "Hook run after orgstruct-mode-map is filled."
8851 :group 'org
8852 :version "24.4"
8853 :package-version '(Org . "8.0")
8854 :type 'hook)
8856 (defvar orgstruct-initialized nil)
8858 (defvar org-local-vars nil
8859 "List of local variables, for use by `orgstruct-mode'.")
8861 ;;;###autoload
8862 (define-minor-mode orgstruct-mode
8863 "Toggle the minor mode `orgstruct-mode'.
8864 This mode is for using Org-mode structure commands in other
8865 modes. The following keys behave as if Org-mode were active, if
8866 the cursor is on a headline, or on a plain list item (both as
8867 defined by Org-mode)."
8868 nil " OrgStruct" (make-sparse-keymap)
8869 (funcall (if orgstruct-mode
8870 'add-to-invisibility-spec
8871 'remove-from-invisibility-spec)
8872 '(outline . t))
8873 (when orgstruct-mode
8874 (org-load-modules-maybe)
8875 (unless orgstruct-initialized
8876 (orgstruct-setup)
8877 (setq orgstruct-initialized t))))
8879 ;;;###autoload
8880 (defun turn-on-orgstruct ()
8881 "Unconditionally turn on `orgstruct-mode'."
8882 (orgstruct-mode 1))
8884 (defvar org-fb-vars nil)
8885 (make-variable-buffer-local 'org-fb-vars)
8886 (defun orgstruct++-mode (&optional arg)
8887 "Toggle `orgstruct-mode', the enhanced version of it.
8888 In addition to setting orgstruct-mode, this also exports all
8889 indentation and autofilling variables from org-mode into the
8890 buffer. It will also recognize item context in multiline items."
8891 (interactive "P")
8892 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8893 (if (< arg 1)
8894 (progn (orgstruct-mode -1)
8895 (mapc (lambda(v)
8896 (org-set-local (car v)
8897 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8898 org-fb-vars))
8899 (orgstruct-mode 1)
8900 (setq org-fb-vars nil)
8901 (unless org-local-vars
8902 (setq org-local-vars (org-get-local-variables)))
8903 (let (var val)
8904 (mapc
8905 (lambda (x)
8906 (when (string-match
8907 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8908 (symbol-name (car x)))
8909 (setq var (car x) val (nth 1 x))
8910 (push (list var `(quote ,(eval var))) org-fb-vars)
8911 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8912 org-local-vars)
8913 (org-set-local 'orgstruct-is-++ t))))
8915 (defvar orgstruct-is-++ nil
8916 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8917 (make-variable-buffer-local 'orgstruct-is-++)
8919 ;;;###autoload
8920 (defun turn-on-orgstruct++ ()
8921 "Unconditionally turn on `orgstruct++-mode'."
8922 (orgstruct++-mode 1))
8924 (defun orgstruct-error ()
8925 "Error when there is no default binding for a structure key."
8926 (interactive)
8927 (funcall (if (fboundp 'user-error)
8928 'user-error
8929 'error)
8930 "This key has no function outside structure elements"))
8932 (defun orgstruct-setup ()
8933 "Setup orgstruct keymap."
8934 (dolist (cell '((org-demote . t)
8935 (org-metaleft . t)
8936 (org-metaright . t)
8937 (org-promote . t)
8938 (org-shiftmetaleft . t)
8939 (org-shiftmetaright . t)
8940 org-backward-element
8941 org-backward-heading-same-level
8942 org-ctrl-c-ret
8943 org-ctrl-c-minus
8944 org-ctrl-c-star
8945 org-cycle
8946 org-forward-heading-same-level
8947 org-insert-heading
8948 org-insert-heading-respect-content
8949 org-kill-note-or-show-branches
8950 org-mark-subtree
8951 org-meta-return
8952 org-metadown
8953 org-metaup
8954 org-narrow-to-subtree
8955 org-promote-subtree
8956 org-reveal
8957 org-shiftdown
8958 org-shiftleft
8959 org-shiftmetadown
8960 org-shiftmetaup
8961 org-shiftright
8962 org-shifttab
8963 org-shifttab
8964 org-shiftup
8965 org-show-subtree
8966 org-sort
8967 org-up-element
8968 outline-demote
8969 outline-next-visible-heading
8970 outline-previous-visible-heading
8971 outline-promote
8972 outline-up-heading
8973 show-children))
8974 (let ((f (or (car-safe cell) cell))
8975 (disable-when-heading-prefix (cdr-safe cell)))
8976 (when (fboundp f)
8977 (let ((new-bindings))
8978 (dolist (binding (nconc (where-is-internal f org-mode-map)
8979 (where-is-internal f outline-mode-map)))
8980 (push binding new-bindings)
8981 ;; TODO use local-function-key-map
8982 (dolist (rep '(("<tab>" . "TAB")
8983 ("<return>" . "RET")
8984 ("<escape>" . "ESC")
8985 ("<delete>" . "DEL")))
8986 (setq binding (read-kbd-macro
8987 (let ((case-fold-search))
8988 (replace-regexp-in-string
8989 (regexp-quote (cdr rep))
8990 (car rep)
8991 (key-description binding)))))
8992 (pushnew binding new-bindings :test 'equal)))
8993 (dolist (binding new-bindings)
8994 (let ((key (lookup-key orgstruct-mode-map binding)))
8995 (when (or (not key) (numberp key))
8996 (condition-case nil
8997 (org-defkey orgstruct-mode-map
8998 binding
8999 (orgstruct-make-binding f binding disable-when-heading-prefix))
9000 (error nil)))))))))
9001 (run-hooks 'orgstruct-setup-hook))
9003 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9004 "Create a function for binding in the structure minor mode.
9005 FUN is the command to call inside a table. KEY is the key that
9006 should be checked in for a command to execute outside of tables.
9007 Non-nil DISABLE-WHEN-HEADING-PREFIX means to disable the command
9008 if `orgstruct-heading-prefix-regexp' is non-nil."
9009 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9010 (let ((nname name)
9011 (i 0))
9012 (while (fboundp (intern nname))
9013 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9014 (setq name (intern nname)))
9015 (eval
9016 (let ((bindings '((org-heading-regexp
9017 (concat "^"
9018 orgstruct-heading-prefix-regexp
9019 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9020 (org-outline-regexp
9021 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9022 (org-outline-regexp-bol
9023 (concat "^" org-outline-regexp))
9024 (outline-regexp org-outline-regexp)
9025 (outline-heading-end-regexp "\n")
9026 (outline-level 'org-outline-level)
9027 (outline-heading-alist))))
9028 `(defun ,name (arg)
9029 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9030 "Outside of structure, run the binding of `"
9031 (key-description key) "'."
9032 (when disable-when-heading-prefix
9033 (concat
9034 "\nIf `orgstruct-heading-prefix-regexp' is non-nil, this command will always fall\n"
9035 "back to the default binding due to limitations of Org's implementation of\n"
9036 "`" (symbol-name fun) "'.")))
9037 (interactive "p")
9038 (let* ((disable
9039 ,(when disable-when-heading-prefix
9040 '(and orgstruct-heading-prefix-regexp
9041 (not (string= orgstruct-heading-prefix-regexp "")))))
9042 (fallback
9043 (or disable
9044 (not
9045 (let* ,bindings
9046 (org-context-p 'headline 'item
9047 ,(when (memq fun
9048 '(org-insert-heading
9049 org-insert-heading-respect-content
9050 org-meta-return))
9051 '(when orgstruct-is-++
9052 'item-body))))))))
9053 (if fallback
9054 (let* ((orgstruct-mode)
9055 (binding
9056 (loop with key = ,key
9057 for rep in
9058 '(nil
9059 ("<\\([^>]*\\)tab>" . "\\1TAB")
9060 ("<\\([^>]*\\)return>" . "\\1RET")
9061 ("<\\([^>]*\\)escape>" . "\\1ESC")
9062 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9064 (when rep
9065 (setq key (read-kbd-macro
9066 (let ((case-fold-search))
9067 (replace-regexp-in-string
9068 (car rep)
9069 (cdr rep)
9070 (key-description key))))))
9071 thereis (key-binding key))))
9072 (if (keymapp binding)
9073 (set-temporary-overlay-map binding)
9074 (let ((func (or binding
9075 (unless disable
9076 'orgstruct-error))))
9077 (when func
9078 (call-interactively func)))))
9079 (org-run-like-in-org-mode
9080 (lambda ()
9081 (interactive)
9082 (let* ,bindings
9083 (call-interactively ',fun)))))))))
9084 name))
9086 (defun org-contextualize-keys (alist contexts)
9087 "Return valid elements in ALIST depending on CONTEXTS.
9089 `org-agenda-custom-commands' or `org-capture-templates' are the
9090 values used for ALIST, and `org-agenda-custom-commands-contexts'
9091 or `org-capture-templates-contexts' are the associated contexts
9092 definitions."
9093 (let ((contexts
9094 ;; normalize contexts
9095 (mapcar
9096 (lambda(c) (cond ((listp (cadr c))
9097 (list (car c) (car c) (cadr c)))
9098 ((string= "" (cadr c))
9099 (list (car c) (car c) (caddr c)))
9100 (t c))) contexts))
9101 (a alist) c r s)
9102 ;; loop over all commands or templates
9103 (while (setq c (pop a))
9104 (let (vrules repl)
9105 (cond
9106 ((not (assoc (car c) contexts))
9107 (push c r))
9108 ((and (assoc (car c) contexts)
9109 (setq vrules (org-contextualize-validate-key
9110 (car c) contexts)))
9111 (mapc (lambda (vr)
9112 (when (not (equal (car vr) (cadr vr)))
9113 (setq repl vr))) vrules)
9114 (if (not repl) (push c r)
9115 (push (cadr repl) s)
9116 (push
9117 (cons (car c)
9118 (cdr (or (assoc (cadr repl) alist)
9119 (error "Undefined key `%s' as contextual replacement for `%s'"
9120 (cadr repl) (car c)))))
9121 r))))))
9122 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9123 (delq
9125 (delete-dups
9126 (mapcar (lambda (x)
9127 (let ((tpl (car x)))
9128 (when (not (delq
9130 (mapcar (lambda(y)
9131 (equal y tpl)) s))) x)))
9132 (reverse r))))))
9134 (defun org-contextualize-validate-key (key contexts)
9135 "Check CONTEXTS for agenda or capture KEY."
9136 (let (r rr res)
9137 (while (setq r (pop contexts))
9138 (mapc
9139 (lambda (rr)
9140 (when
9141 (and (equal key (car r))
9142 (if (functionp rr) (funcall rr)
9143 (or (and (eq (car rr) 'in-file)
9144 (buffer-file-name)
9145 (string-match (cdr rr) (buffer-file-name)))
9146 (and (eq (car rr) 'in-mode)
9147 (string-match (cdr rr) (symbol-name major-mode)))
9148 (and (eq (car rr) 'in-buffer)
9149 (string-match (cdr rr) (buffer-name)))
9150 (when (and (eq (car rr) 'not-in-file)
9151 (buffer-file-name))
9152 (not (string-match (cdr rr) (buffer-file-name))))
9153 (when (eq (car rr) 'not-in-mode)
9154 (not (string-match (cdr rr) (symbol-name major-mode))))
9155 (when (eq (car rr) 'not-in-buffer)
9156 (not (string-match (cdr rr) (buffer-name)))))))
9157 (push r res)))
9158 (car (last r))))
9159 (delete-dups (delq nil res))))
9161 (defun org-context-p (&rest contexts)
9162 "Check if local context is any of CONTEXTS.
9163 Possible values in the list of contexts are `table', `headline', and `item'."
9164 (let ((pos (point)))
9165 (goto-char (point-at-bol))
9166 (prog1 (or (and (memq 'table contexts)
9167 (looking-at "[ \t]*|"))
9168 (and (memq 'headline contexts)
9169 (looking-at org-outline-regexp))
9170 (and (memq 'item contexts)
9171 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9172 (and (memq 'item-body contexts)
9173 (org-in-item-p)))
9174 (goto-char pos))))
9176 (defun org-get-local-variables ()
9177 "Return a list of all local variables in an Org mode buffer."
9178 (let (varlist)
9179 (with-current-buffer (get-buffer-create "*Org tmp*")
9180 (erase-buffer)
9181 (org-mode)
9182 (setq varlist (buffer-local-variables)))
9183 (kill-buffer "*Org tmp*")
9184 (delq nil
9185 (mapcar
9186 (lambda (x)
9187 (setq x
9188 (if (symbolp x)
9189 (list x)
9190 (list (car x) (cdr x))))
9191 (if (and (not (get (car x) 'org-state))
9192 (string-match
9193 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9194 (symbol-name (car x))))
9195 x nil))
9196 varlist))))
9198 (defun org-clone-local-variables (from-buffer &optional regexp)
9199 "Clone local variables from FROM-BUFFER.
9200 Optional argument REGEXP selects variables to clone."
9201 (mapc
9202 (lambda (pair)
9203 (and (symbolp (car pair))
9204 (or (null regexp)
9205 (string-match regexp (symbol-name (car pair))))
9206 (set (make-local-variable (car pair))
9207 (cdr pair))))
9208 (buffer-local-variables from-buffer)))
9210 ;;;###autoload
9211 (defun org-run-like-in-org-mode (cmd)
9212 "Run a command, pretending that the current buffer is in Org-mode.
9213 This will temporarily bind local variables that are typically bound in
9214 Org-mode to the values they have in Org-mode, and then interactively
9215 call CMD."
9216 (org-load-modules-maybe)
9217 (unless org-local-vars
9218 (setq org-local-vars (org-get-local-variables)))
9219 (let (binds)
9220 (dolist (var org-local-vars)
9221 (when (or (not (boundp (car var)))
9222 (eq (symbol-value (car var))
9223 (default-value (car var))))
9224 (push (list (car var) `(quote ,(cadr var))) binds)))
9225 (eval `(let ,binds
9226 (call-interactively (quote ,cmd))))))
9228 ;;;; Archiving
9230 (defun org-get-category (&optional pos force-refresh)
9231 "Get the category applying to position POS."
9232 (save-match-data
9233 (if force-refresh (org-refresh-category-properties))
9234 (let ((pos (or pos (point))))
9235 (or (get-text-property pos 'org-category)
9236 (progn (org-refresh-category-properties)
9237 (get-text-property pos 'org-category))))))
9239 (defun org-refresh-category-properties ()
9240 "Refresh category text properties in the buffer."
9241 (let ((case-fold-search t)
9242 (inhibit-read-only t)
9243 (def-cat (cond
9244 ((null org-category)
9245 (if buffer-file-name
9246 (file-name-sans-extension
9247 (file-name-nondirectory buffer-file-name))
9248 "???"))
9249 ((symbolp org-category) (symbol-name org-category))
9250 (t org-category)))
9251 beg end cat pos optionp)
9252 (org-with-silent-modifications
9253 (save-excursion
9254 (save-restriction
9255 (widen)
9256 (goto-char (point-min))
9257 (put-text-property (point) (point-max) 'org-category def-cat)
9258 (while (re-search-forward
9259 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9260 (setq pos (match-end 0)
9261 optionp (equal (char-after (match-beginning 0)) ?#)
9262 cat (org-trim (match-string 2)))
9263 (if optionp
9264 (setq beg (point-at-bol) end (point-max))
9265 (org-back-to-heading t)
9266 (setq beg (point) end (org-end-of-subtree t t)))
9267 (put-text-property beg end 'org-category cat)
9268 (put-text-property beg end 'org-category-position beg)
9269 (goto-char pos)))))))
9271 (defun org-refresh-properties (dprop tprop)
9272 "Refresh buffer text properties.
9273 DPROP is the drawer property and TPROP is the corresponding text
9274 property to set."
9275 (let ((case-fold-search t)
9276 (inhibit-read-only t) p)
9277 (org-with-silent-modifications
9278 (save-excursion
9279 (save-restriction
9280 (widen)
9281 (goto-char (point-min))
9282 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9283 (setq p (org-match-string-no-properties 1))
9284 (save-excursion
9285 (org-back-to-heading t)
9286 (put-text-property
9287 (point-at-bol) (org-end-of-subtree t t) tprop p))))))))
9290 ;;;; Link Stuff
9292 ;;; Link abbreviations
9294 (defun org-link-expand-abbrev (link)
9295 "Apply replacements as defined in `org-link-abbrev-alist'."
9296 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9297 (let* ((key (match-string 1 link))
9298 (as (or (assoc key org-link-abbrev-alist-local)
9299 (assoc key org-link-abbrev-alist)))
9300 (tag (and (match-end 2) (match-string 3 link)))
9301 rpl)
9302 (if (not as)
9303 link
9304 (setq rpl (cdr as))
9305 (cond
9306 ((symbolp rpl) (funcall rpl tag))
9307 ((string-match "%(\\([^)]+\\))" rpl)
9308 (replace-match
9309 (save-match-data
9310 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9311 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9312 ((string-match "%h" rpl)
9313 (replace-match (url-hexify-string (or tag "")) t t rpl))
9314 (t (concat rpl tag)))))
9315 link))
9317 ;;; Storing and inserting links
9319 (defvar org-insert-link-history nil
9320 "Minibuffer history for links inserted with `org-insert-link'.")
9322 (defvar org-stored-links nil
9323 "Contains the links stored with `org-store-link'.")
9325 (defvar org-store-link-plist nil
9326 "Plist with info about the most recently link created with `org-store-link'.")
9328 (defvar org-link-protocols nil
9329 "Link protocols added to Org-mode using `org-add-link-type'.")
9331 (defvar org-store-link-functions nil
9332 "List of functions that are called to create and store a link.
9333 Each function will be called in turn until one returns a non-nil
9334 value. Each function should check if it is responsible for creating
9335 this link (for example by looking at the major mode).
9336 If not, it must exit and return nil.
9337 If yes, it should return a non-nil value after a calling
9338 `org-store-link-props' with a list of properties and values.
9339 Special properties are:
9341 :type The link prefix, like \"http\". This must be given.
9342 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9343 This is obligatory as well.
9344 :description Optional default description for the second pair
9345 of brackets in an Org-mode link. The user can still change
9346 this when inserting this link into an Org-mode buffer.
9348 In addition to these, any additional properties can be specified
9349 and then used in capture templates.")
9351 (defun org-add-link-type (type &optional follow export)
9352 "Add TYPE to the list of `org-link-types'.
9353 Re-compute all regular expressions depending on `org-link-types'
9355 FOLLOW and EXPORT are two functions.
9357 FOLLOW should take the link path as the single argument and do whatever
9358 is necessary to follow the link, for example find a file or display
9359 a mail message.
9361 EXPORT should format the link path for export to one of the export formats.
9362 It should be a function accepting three arguments:
9364 path the path of the link, the text after the prefix (like \"http:\")
9365 desc the description of the link, if any, or a description added by
9366 org-export-normalize-links if there is none
9367 format the export format, a symbol like `html' or `latex' or `ascii'..
9369 The function may use the FORMAT information to return different values
9370 depending on the format. The return value will be put literally into
9371 the exported file. If the return value is nil, this means Org should
9372 do what it normally does with links which do not have EXPORT defined.
9374 Org-mode has a built-in default for exporting links. If you are happy with
9375 this default, there is no need to define an export function for the link
9376 type. For a simple example of an export function, see `org-bbdb.el'."
9377 (add-to-list 'org-link-types type t)
9378 (org-make-link-regexps)
9379 (if (assoc type org-link-protocols)
9380 (setcdr (assoc type org-link-protocols) (list follow export))
9381 (push (list type follow export) org-link-protocols)))
9383 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9384 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9386 ;;;###autoload
9387 (defun org-store-link (arg)
9388 "\\<org-mode-map>Store an org-link to the current location.
9389 This link is added to `org-stored-links' and can later be inserted
9390 into an org-buffer with \\[org-insert-link].
9392 For some link types, a prefix arg is interpreted.
9393 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9394 For file links, arg negates `org-context-in-file-links'.
9396 A double prefix arg force skipping storing functions that are not
9397 part of Org's core.
9399 A triple prefix arg force storing a link for each line in the
9400 active region."
9401 (interactive "P")
9402 (org-load-modules-maybe)
9403 (if (and (equal arg '(64)) (org-region-active-p))
9404 (save-excursion
9405 (let ((end (region-end)))
9406 (goto-char (region-beginning))
9407 (set-mark (point))
9408 (while (< (point-at-eol) end)
9409 (move-end-of-line 1) (activate-mark)
9410 (let (current-prefix-arg)
9411 (call-interactively 'org-store-link))
9412 (move-beginning-of-line 2)
9413 (set-mark (point)))))
9414 (org-with-limited-levels
9415 (setq org-store-link-plist nil)
9416 (let (link cpltxt desc description search
9417 txt custom-id agenda-link sfuns sfunsn)
9418 (cond
9420 ;; Store a link using an external link type
9421 ((and (not (equal arg '(16)))
9422 (setq sfuns
9423 (delq
9424 nil (mapcar (lambda (f)
9425 (let (fs) (if (funcall f) (push f fs))))
9426 org-store-link-functions))
9427 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9428 (or (and (cdr sfuns)
9429 (funcall (intern
9430 (completing-read
9431 "Which function for creating the link? "
9432 sfunsn t (car sfunsn)))))
9433 (funcall (caar sfuns)))
9434 (setq link (plist-get org-store-link-plist :link)
9435 desc (or (plist-get org-store-link-plist
9436 :description) link))))
9438 ;; Store a link from a source code buffer
9439 ((org-src-edit-buffer-p)
9440 (let (label gc)
9441 (while (or (not label)
9442 (save-excursion
9443 (save-restriction
9444 (widen)
9445 (goto-char (point-min))
9446 (re-search-forward
9447 (regexp-quote (format org-coderef-label-format label))
9448 nil t))))
9449 (when label (message "Label exists already") (sit-for 2))
9450 (setq label (read-string "Code line label: " label)))
9451 (end-of-line 1)
9452 (setq link (format org-coderef-label-format label))
9453 (setq gc (- 79 (length link)))
9454 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9455 (insert link)
9456 (setq link (concat "(" label ")") desc nil)))
9458 ;; We are in the agenda, link to referenced location
9459 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9460 (let ((m (or (get-text-property (point) 'org-hd-marker)
9461 (get-text-property (point) 'org-marker))))
9462 (when m
9463 (org-with-point-at m
9464 (setq agenda-link
9465 (if (org-called-interactively-p 'any)
9466 (call-interactively 'org-store-link)
9467 (org-store-link nil)))))))
9469 ((eq major-mode 'calendar-mode)
9470 (let ((cd (calendar-cursor-to-date)))
9471 (setq link
9472 (format-time-string
9473 (car org-time-stamp-formats)
9474 (apply 'encode-time
9475 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9476 nil nil nil))))
9477 (org-store-link-props :type "calendar" :date cd)))
9479 ((eq major-mode 'help-mode)
9480 (setq link (concat "help:" (save-excursion
9481 (goto-char (point-min))
9482 (looking-at "^[^ ]+")
9483 (match-string 0))))
9484 (org-store-link-props :type "help"))
9486 ((eq major-mode 'w3-mode)
9487 (setq cpltxt (if (and (buffer-name)
9488 (not (string-match "Untitled" (buffer-name))))
9489 (buffer-name)
9490 (url-view-url t))
9491 link (url-view-url t))
9492 (org-store-link-props :type "w3" :url (url-view-url t)))
9494 ((eq major-mode 'image-mode)
9495 (setq cpltxt (concat "file:"
9496 (abbreviate-file-name buffer-file-name))
9497 link cpltxt)
9498 (org-store-link-props :type "image" :file buffer-file-name))
9500 ;; In dired, store a link to the file of the current line
9501 ((eq major-mode 'dired-mode)
9502 (let ((file (dired-get-filename nil t)))
9503 (setq file (if file
9504 (abbreviate-file-name
9505 (expand-file-name (dired-get-filename nil t)))
9506 ;; otherwise, no file so use current directory.
9507 default-directory))
9508 (setq cpltxt (concat "file:" file)
9509 link cpltxt)))
9511 ((setq search (run-hook-with-args-until-success
9512 'org-create-file-search-functions))
9513 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9514 "::" search))
9515 (setq cpltxt (or description link)))
9517 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9518 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9519 (cond
9520 ;; Store a link using the target at point
9521 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9522 (setq cpltxt
9523 (concat "file:"
9524 (abbreviate-file-name
9525 (buffer-file-name (buffer-base-buffer)))
9526 "::" (match-string 1))
9527 link cpltxt))
9528 ((and (featurep 'org-id)
9529 (or (eq org-id-link-to-org-use-id t)
9530 (and (org-called-interactively-p 'any)
9531 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9532 (and (eq org-id-link-to-org-use-id
9533 'create-if-interactive-and-no-custom-id)
9534 (not custom-id))))
9535 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9536 ;; Store a link using the ID at point
9537 (setq link (condition-case nil
9538 (prog1 (org-id-store-link)
9539 (setq desc (plist-get org-store-link-plist
9540 :description)))
9541 (error
9542 ;; Probably before first headline, link only to file
9543 (concat "file:"
9544 (abbreviate-file-name
9545 (buffer-file-name (buffer-base-buffer))))))))
9547 ;; Just link to current headline
9548 (setq cpltxt (concat "file:"
9549 (abbreviate-file-name
9550 (buffer-file-name (buffer-base-buffer)))))
9551 ;; Add a context search string
9552 (when (org-xor org-context-in-file-links arg)
9553 (let* ((ee (org-element-at-point))
9554 (et (org-element-type ee))
9555 (ev (plist-get (cadr ee) :value))
9556 (ek (plist-get (cadr ee) :key))
9557 (eok (and (stringp ek) (string-match "name" ek))))
9558 (setq txt (cond
9559 ((org-at-heading-p) nil)
9560 ((and (eq et 'keyword) eok) ev)
9561 ((org-region-active-p)
9562 (buffer-substring (region-beginning) (region-end)))))
9563 (when (or (null txt) (string-match "\\S-" txt))
9564 (setq cpltxt
9565 (concat cpltxt "::"
9566 (condition-case nil
9567 (org-make-org-heading-search-string txt)
9568 (error "")))
9569 desc (or (and (eq et 'keyword) eok ev)
9570 (nth 4 (ignore-errors (org-heading-components)))
9571 "NONE")))))
9572 (if (string-match "::\\'" cpltxt)
9573 (setq cpltxt (substring cpltxt 0 -2)))
9574 (setq link cpltxt))))
9576 ((buffer-file-name (buffer-base-buffer))
9577 ;; Just link to this file here.
9578 (setq cpltxt (concat "file:"
9579 (abbreviate-file-name
9580 (buffer-file-name (buffer-base-buffer)))))
9581 ;; Add a context string.
9582 (when (org-xor org-context-in-file-links arg)
9583 (setq txt (if (org-region-active-p)
9584 (buffer-substring (region-beginning) (region-end))
9585 (buffer-substring (point-at-bol) (point-at-eol))))
9586 ;; Only use search option if there is some text.
9587 (when (string-match "\\S-" txt)
9588 (setq cpltxt
9589 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9590 desc "NONE")))
9591 (setq link cpltxt))
9593 ((org-called-interactively-p 'interactive)
9594 (user-error "No method for storing a link from this buffer"))
9596 (t (setq link nil)))
9598 ;; We're done setting link and desc, clean up
9599 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9600 (setq link (or link cpltxt)
9601 desc (or desc cpltxt))
9602 (cond ((equal desc "NONE") (setq desc nil))
9603 ((string-match org-bracket-link-analytic-regexp desc)
9604 (let ((d0 (match-string 3 desc))
9605 (p0 (match-string 5 desc)))
9606 (setq desc
9607 (replace-regexp-in-string
9608 org-bracket-link-regexp
9609 (concat (or p0 d0)
9610 (if (equal (length (match-string 0 desc))
9611 (length desc)) "*" "")) desc)))))
9613 ;; Return the link
9614 (if (not (and (or (org-called-interactively-p 'any)
9615 executing-kbd-macro) link))
9616 (or agenda-link (and link (org-make-link-string link desc)))
9617 (push (list link desc) org-stored-links)
9618 (message "Stored: %s" (or desc link))
9619 (when custom-id
9620 (setq link (concat "file:" (abbreviate-file-name
9621 (buffer-file-name)) "::#" custom-id))
9622 (push (list link desc) org-stored-links)))))))
9624 (defun org-store-link-props (&rest plist)
9625 "Store link properties, extract names and addresses."
9626 (let (x adr)
9627 (when (setq x (plist-get plist :from))
9628 (setq adr (mail-extract-address-components x))
9629 (setq plist (plist-put plist :fromname (car adr)))
9630 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9631 (when (setq x (plist-get plist :to))
9632 (setq adr (mail-extract-address-components x))
9633 (setq plist (plist-put plist :toname (car adr)))
9634 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9635 (let ((from (plist-get plist :from))
9636 (to (plist-get plist :to)))
9637 (when (and from to org-from-is-user-regexp)
9638 (setq plist
9639 (plist-put plist :fromto
9640 (if (string-match org-from-is-user-regexp from)
9641 (concat "to %t")
9642 (concat "from %f"))))))
9643 (setq org-store-link-plist plist))
9645 (defun org-add-link-props (&rest plist)
9646 "Add these properties to the link property list."
9647 (let (key value)
9648 (while plist
9649 (setq key (pop plist) value (pop plist))
9650 (setq org-store-link-plist
9651 (plist-put org-store-link-plist key value)))))
9653 (defun org-email-link-description (&optional fmt)
9654 "Return the description part of an email link.
9655 This takes information from `org-store-link-plist' and formats it
9656 according to FMT (default from `org-email-link-description-format')."
9657 (setq fmt (or fmt org-email-link-description-format))
9658 (let* ((p org-store-link-plist)
9659 (to (plist-get p :toaddress))
9660 (from (plist-get p :fromaddress))
9661 (table
9662 (list
9663 (cons "%c" (plist-get p :fromto))
9664 (cons "%F" (plist-get p :from))
9665 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9666 (cons "%T" (plist-get p :to))
9667 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9668 (cons "%s" (plist-get p :subject))
9669 (cons "%d" (plist-get p :date))
9670 (cons "%m" (plist-get p :message-id)))))
9671 (when (string-match "%c" fmt)
9672 ;; Check if the user wrote this message
9673 (if (and org-from-is-user-regexp from to
9674 (save-match-data (string-match org-from-is-user-regexp from)))
9675 (setq fmt (replace-match "to %t" t t fmt))
9676 (setq fmt (replace-match "from %f" t t fmt))))
9677 (org-replace-escapes fmt table)))
9679 (defun org-make-org-heading-search-string (&optional string)
9680 "Make search string for the current headline or STRING."
9681 (let ((s (or string
9682 (and (derived-mode-p 'org-mode)
9683 (save-excursion
9684 (org-back-to-heading t)
9685 (org-element-property :raw-value (org-element-at-point))))))
9686 (lines org-context-in-file-links))
9687 (or string (setq s (concat "*" s))) ; Add * for headlines
9688 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9689 (when (and string (integerp lines) (> lines 0))
9690 (let ((slines (org-split-string s "\n")))
9691 (when (< lines (length slines))
9692 (setq s (mapconcat
9693 'identity
9694 (reverse (nthcdr (- (length slines) lines)
9695 (reverse slines))) "\n")))))
9696 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9698 (defun org-make-link-string (link &optional description)
9699 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9700 (unless (string-match "\\S-" link)
9701 (error "Empty link"))
9702 (when (and description
9703 (stringp description)
9704 (not (string-match "\\S-" description)))
9705 (setq description nil))
9706 (when (stringp description)
9707 ;; Remove brackets from the description, they are fatal.
9708 (while (string-match "\\[" description)
9709 (setq description (replace-match "{" t t description)))
9710 (while (string-match "\\]" description)
9711 (setq description (replace-match "}" t t description))))
9712 (when (equal link description)
9713 ;; No description needed, it is identical
9714 (setq description nil))
9715 (when (and (not description)
9716 (not (string-match (org-image-file-name-regexp) link))
9717 (not (equal link (org-link-escape link))))
9718 (setq description (org-extract-attributes link)))
9719 (setq link
9720 (cond ((string-match (org-image-file-name-regexp) link) link)
9721 ((string-match org-link-types-re link)
9722 (concat (match-string 1 link)
9723 (org-link-escape (substring link (match-end 1)))))
9724 (t (org-link-escape link))))
9725 (concat "[[" link "]"
9726 (if description (concat "[" description "]") "")
9727 "]"))
9729 (defconst org-link-escape-chars
9730 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9731 "List of characters that should be escaped in link.
9732 This is the list that is used for internal purposes.")
9734 (defconst org-link-escape-chars-browser
9735 '(?\ ?\")
9736 "List of escapes for characters that are problematic in links.
9737 This is the list that is used before handing over to the browser.")
9739 (defun org-link-escape (text &optional table merge)
9740 "Return percent escaped representation of TEXT.
9741 TEXT is a string with the text to escape.
9742 Optional argument TABLE is a list with characters that should be
9743 escaped. When nil, `org-link-escape-chars' is used.
9744 If optional argument MERGE is set, merge TABLE into
9745 `org-link-escape-chars'."
9746 (cond
9747 ((and table merge)
9748 (mapc (lambda (defchr)
9749 (unless (member defchr table)
9750 (setq table (cons defchr table)))) org-link-escape-chars))
9751 ((null table)
9752 (setq table org-link-escape-chars)))
9753 (mapconcat
9754 (lambda (char)
9755 (if (or (member char table)
9756 (and (or (< char 32) (= char 37) (> char 126))
9757 org-url-hexify-p))
9758 (mapconcat (lambda (sequence-element)
9759 (format "%%%.2X" sequence-element))
9760 (or (encode-coding-char char 'utf-8)
9761 (error "Unable to percent escape character: %s"
9762 (char-to-string char))) "")
9763 (char-to-string char))) text ""))
9765 (defun org-link-unescape (str)
9766 "Unhex hexified Unicode strings as returned from the JavaScript function
9767 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9768 (unless (and (null str) (string= "" str))
9769 (let ((pos 0) (case-fold-search t) unhexed)
9770 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9771 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9772 (setq str (replace-match unhexed t t str))
9773 (setq pos (+ pos (length unhexed))))))
9774 str)
9776 (defun org-link-unescape-compound (hex)
9777 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9778 Note: this function also decodes single byte encodings like
9779 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9780 (save-match-data
9781 (let* ((bytes (cdr (split-string hex "%")))
9782 (ret "")
9783 (eat 0)
9784 (sum 0))
9785 (while bytes
9786 (let* ((val (string-to-number (pop bytes) 16))
9787 (shift-xor
9788 (if (= 0 eat)
9789 (cond
9790 ((>= val 252) (cons 6 252))
9791 ((>= val 248) (cons 5 248))
9792 ((>= val 240) (cons 4 240))
9793 ((>= val 224) (cons 3 224))
9794 ((>= val 192) (cons 2 192))
9795 (t (cons 0 0)))
9796 (cons 6 128))))
9797 (if (>= val 192) (setq eat (car shift-xor)))
9798 (setq val (logxor val (cdr shift-xor)))
9799 (setq sum (+ (lsh sum (car shift-xor)) val))
9800 (if (> eat 0) (setq eat (- eat 1)))
9801 (cond
9802 ((= 0 eat) ;multi byte
9803 (setq ret (concat ret (org-char-to-string sum)))
9804 (setq sum 0))
9805 ((not bytes) ; single byte(s)
9806 (setq ret (org-link-unescape-single-byte-sequence hex))))
9807 )) ;; end (while bytes
9808 ret )))
9810 (defun org-link-unescape-single-byte-sequence (hex)
9811 "Unhexify hex-encoded single byte character sequences."
9812 (mapconcat (lambda (byte)
9813 (char-to-string (string-to-number byte 16)))
9814 (cdr (split-string hex "%")) ""))
9816 (defun org-xor (a b)
9817 "Exclusive or."
9818 (if a (not b) b))
9820 (defun org-fixup-message-id-for-http (s)
9821 "Replace special characters in a message id, so it can be used in an http query."
9822 (when (string-match "%" s)
9823 (setq s (mapconcat (lambda (c)
9824 (if (eq c ?%)
9825 "%25"
9826 (char-to-string c)))
9827 s "")))
9828 (while (string-match "<" s)
9829 (setq s (replace-match "%3C" t t s)))
9830 (while (string-match ">" s)
9831 (setq s (replace-match "%3E" t t s)))
9832 (while (string-match "@" s)
9833 (setq s (replace-match "%40" t t s)))
9836 (defun org-link-prettify (link)
9837 "Return a human-readable representation of LINK.
9838 The car of LINK must be a raw link the cdr of LINK must be either
9839 a link description or nil."
9840 (let ((desc (or (cadr link) "<no description>")))
9841 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9842 "<" (car link) ">")))
9844 ;;;###autoload
9845 (defun org-insert-link-global ()
9846 "Insert a link like Org-mode does.
9847 This command can be called in any mode to insert a link in Org-mode syntax."
9848 (interactive)
9849 (org-load-modules-maybe)
9850 (org-run-like-in-org-mode 'org-insert-link))
9852 (defun org-insert-all-links (&optional keep)
9853 "Insert all links in `org-stored-links'."
9854 (interactive "P")
9855 (let ((links (copy-sequence org-stored-links)) l)
9856 (while (setq l (if keep (pop links) (pop org-stored-links)))
9857 (insert "- ")
9858 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9859 (insert "\n"))))
9861 (defun org-link-fontify-links-to-this-file ()
9862 "Fontify links to the current file in `org-stored-links'."
9863 (let ((f (buffer-file-name)) a b)
9864 (setq a (mapcar (lambda(l)
9865 (let ((ll (car l)))
9866 (when (and (string-match "^file:\\(.+\\)::" ll)
9867 (equal f (expand-file-name (match-string 1 ll))))
9868 ll)))
9869 org-stored-links))
9870 (when (featurep 'org-id)
9871 (setq b (mapcar (lambda(l)
9872 (let ((ll (car l)))
9873 (when (and (string-match "^id:\\(.+\\)$" ll)
9874 (equal f (expand-file-name
9875 (or (org-id-find-id-file
9876 (match-string 1 ll)) ""))))
9877 ll)))
9878 org-stored-links)))
9879 (mapcar (lambda(l)
9880 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9881 (delq nil (append a b)))))
9883 (defvar org-link-links-in-this-file nil)
9884 (defun org-insert-link (&optional complete-file link-location default-description)
9885 "Insert a link. At the prompt, enter the link.
9887 Completion can be used to insert any of the link protocol prefixes like
9888 http or ftp in use.
9890 The history can be used to select a link previously stored with
9891 `org-store-link'. When the empty string is entered (i.e. if you just
9892 press RET at the prompt), the link defaults to the most recently
9893 stored link. As SPC triggers completion in the minibuffer, you need to
9894 use M-SPC or C-q SPC to force the insertion of a space character.
9896 You will also be prompted for a description, and if one is given, it will
9897 be displayed in the buffer instead of the link.
9899 If there is already a link at point, this command will allow you to edit link
9900 and description parts.
9902 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9903 be selected using completion. The path to the file will be relative to the
9904 current directory if the file is in the current directory or a subdirectory.
9905 Otherwise, the link will be the absolute path as completed in the minibuffer
9906 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9907 option `org-link-file-path-type'.
9909 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9910 the current directory or below.
9912 With three \\[universal-argument] prefixes, negate the meaning of
9913 `org-keep-stored-link-after-insertion'.
9915 If `org-make-link-description-function' is non-nil, this function will be
9916 called with the link target, and the result will be the default
9917 link description.
9919 If the LINK-LOCATION parameter is non-nil, this value will be
9920 used as the link location instead of reading one interactively.
9922 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9923 be used as the default description."
9924 (interactive "P")
9925 (let* ((wcf (current-window-configuration))
9926 (origbuf (current-buffer))
9927 (region (if (org-region-active-p)
9928 (buffer-substring (region-beginning) (region-end))))
9929 (remove (and region (list (region-beginning) (region-end))))
9930 (desc region)
9931 tmphist ; byte-compile incorrectly complains about this
9932 (link link-location)
9933 (abbrevs org-link-abbrev-alist-local)
9934 entry file all-prefixes auto-desc)
9935 (cond
9936 (link-location) ; specified by arg, just use it.
9937 ((org-in-regexp org-bracket-link-regexp 1)
9938 ;; We do have a link at point, and we are going to edit it.
9939 (setq remove (list (match-beginning 0) (match-end 0)))
9940 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9941 (setq link (read-string "Link: "
9942 (org-link-unescape
9943 (org-match-string-no-properties 1)))))
9944 ((or (org-in-regexp org-angle-link-re)
9945 (org-in-regexp org-plain-link-re))
9946 ;; Convert to bracket link
9947 (setq remove (list (match-beginning 0) (match-end 0))
9948 link (read-string "Link: "
9949 (org-remove-angle-brackets (match-string 0)))))
9950 ((member complete-file '((4) (16)))
9951 ;; Completing read for file names.
9952 (setq link (org-file-complete-link complete-file)))
9954 ;; Read link, with completion for stored links.
9955 (org-link-fontify-links-to-this-file)
9956 (org-switch-to-buffer-other-window "*Org Links*")
9957 (with-current-buffer "*Org Links*"
9958 (erase-buffer)
9959 (insert "Insert a link.
9960 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9961 (when org-stored-links
9962 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9963 (insert (mapconcat 'org-link-prettify
9964 (reverse org-stored-links) "\n")))
9965 (goto-char (point-min)))
9966 (let ((cw (selected-window)))
9967 (select-window (get-buffer-window "*Org Links*" 'visible))
9968 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9969 (unless (pos-visible-in-window-p (point-max))
9970 (org-fit-window-to-buffer))
9971 (and (window-live-p cw) (select-window cw)))
9972 ;; Fake a link history, containing the stored links.
9973 (setq tmphist (append (mapcar 'car org-stored-links)
9974 org-insert-link-history))
9975 (setq all-prefixes (append (mapcar 'car abbrevs)
9976 (mapcar 'car org-link-abbrev-alist)
9977 org-link-types))
9978 (unwind-protect
9979 (progn
9980 (setq link
9981 (org-completing-read
9982 "Link: "
9983 (append
9984 (mapcar (lambda (x) (concat x ":"))
9985 all-prefixes)
9986 (mapcar 'car org-stored-links))
9987 nil nil nil
9988 'tmphist
9989 (caar org-stored-links)))
9990 (if (not (string-match "\\S-" link))
9991 (user-error "No link selected"))
9992 (mapc (lambda(l)
9993 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9994 org-stored-links)
9995 (if (or (member link all-prefixes)
9996 (and (equal ":" (substring link -1))
9997 (member (substring link 0 -1) all-prefixes)
9998 (setq link (substring link 0 -1))))
9999 (setq link (with-current-buffer origbuf
10000 (org-link-try-special-completion link)))))
10001 (set-window-configuration wcf)
10002 (kill-buffer "*Org Links*"))
10003 (setq entry (assoc link org-stored-links))
10004 (or entry (push link org-insert-link-history))
10005 (setq desc (or desc (nth 1 entry)))))
10007 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10008 (not org-keep-stored-link-after-insertion))
10009 (setq org-stored-links (delq (assoc link org-stored-links)
10010 org-stored-links)))
10012 (if (string-match org-plain-link-re 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 clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10312 (defun org-open-at-point (&optional arg reference-buffer)
10313 "Open link at or after point.
10314 If there is no link at point, this function will search forward up to
10315 the end of the current line.
10316 Normally, files will be opened by an appropriate application. If the
10317 optional prefix argument ARG is non-nil, Emacs will visit the file.
10318 With a double prefix argument, try to open outside of Emacs, in the
10319 application the system uses for this file type."
10320 (interactive "P")
10321 ;; if in a code block, then open the block's results
10322 (unless (call-interactively #'org-babel-open-src-block-result)
10323 (org-load-modules-maybe)
10324 (move-marker org-open-link-marker (point))
10325 (setq org-window-config-before-follow-link (current-window-configuration))
10326 (org-remove-occur-highlights nil nil t)
10327 (cond
10328 ((and (org-at-heading-p)
10329 (not (org-at-timestamp-p t))
10330 (not (org-in-regexp
10331 (concat org-plain-link-re "\\|"
10332 org-bracket-link-regexp "\\|"
10333 org-angle-link-re "\\|"
10334 "[ \t]:[^ \t\n]+:[ \t]*$")))
10335 (not (get-text-property (point) 'org-linked-text)))
10336 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10337 (lk0 (car lkall))
10338 (lk (if (stringp lk0) (list lk0) lk0))
10339 (lkend (cdr lkall)))
10340 (mapcar (lambda(l)
10341 (search-forward l nil lkend)
10342 (goto-char (match-beginning 0))
10343 (org-open-at-point))
10344 lk))
10345 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10346 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10347 ((and (org-at-timestamp-p t)
10348 (not (org-in-regexp org-bracket-link-regexp)))
10349 (org-follow-timestamp-link))
10350 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10351 (not (org-in-regexp org-any-link-re)))
10352 (org-footnote-action))
10354 (let (type path link line search (pos (point)))
10355 (catch 'match
10356 (save-excursion
10357 (skip-chars-forward "^]\n\r")
10358 (when (org-in-regexp org-bracket-link-regexp 1)
10359 (setq link (org-extract-attributes
10360 (org-link-unescape (org-match-string-no-properties 1))))
10361 (while (string-match " *\n *" link)
10362 (setq link (replace-match " " t t link)))
10363 (setq link (org-link-expand-abbrev link))
10364 (cond
10365 ((or (file-name-absolute-p link)
10366 (string-match "^\\.\\.?/" link))
10367 (setq type "file" path link))
10368 ((string-match org-link-re-with-space3 link)
10369 (setq type (match-string 1 link) path (match-string 2 link)))
10370 ((string-match "^help:+\\(.+\\)" link)
10371 (setq type "help" path (match-string 1 link)))
10372 (t (setq type "thisfile" path link)))
10373 (throw 'match t)))
10375 (when (get-text-property (point) 'org-linked-text)
10376 (setq type "thisfile"
10377 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10378 (1+ (point)) (point))
10379 path (buffer-substring
10380 (or (previous-single-property-change pos 'org-linked-text)
10381 (point-min))
10382 (or (next-single-property-change pos 'org-linked-text)
10383 (point-max)))
10384 ;; Ensure we will search for a <<<radio>>> link, not
10385 ;; a simple reference like <<ref>>
10386 path (concat "<" path))
10387 (throw 'match t))
10389 (save-excursion
10390 (when (or (org-in-regexp org-angle-link-re)
10391 (let ((match (org-in-regexp org-plain-link-re)))
10392 ;; Check a plain link is not within a bracket link
10393 (and match
10394 (save-excursion
10395 (progn
10396 (goto-char (car match))
10397 (not (org-in-regexp org-bracket-link-regexp))))))
10398 (let ((line_ending (save-excursion (end-of-line) (point))))
10399 ;; We are in a line before a plain or bracket link
10400 (or (re-search-forward org-plain-link-re line_ending t)
10401 (re-search-forward org-bracket-link-regexp line_ending t))))
10402 (setq type (match-string 1)
10403 path (org-link-unescape (match-string 2)))
10404 (throw 'match t)))
10405 (save-excursion
10406 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10407 (setq type "tags"
10408 path (match-string 1))
10409 (while (string-match ":" path)
10410 (setq path (replace-match "+" t t path)))
10411 (throw 'match t)))
10412 (when (org-in-regexp "<\\([^><\n]+\\)>")
10413 (setq type "tree-match"
10414 path (match-string 1))
10415 (throw 'match t)))
10416 (unless path
10417 (user-error "No link found"))
10419 ;; switch back to reference buffer
10420 ;; needed when if called in a temporary buffer through
10421 ;; org-open-link-from-string
10422 (with-current-buffer (or reference-buffer (current-buffer))
10424 ;; Remove any trailing spaces in path
10425 (if (string-match " +\\'" path)
10426 (setq path (replace-match "" t t path)))
10427 (if (and org-link-translation-function
10428 (fboundp org-link-translation-function))
10429 ;; Check if we need to translate the link
10430 (let ((tmp (funcall org-link-translation-function type path)))
10431 (setq type (car tmp) path (cdr tmp))))
10433 (cond
10435 ((assoc type org-link-protocols)
10436 (funcall (nth 1 (assoc type org-link-protocols)) path))
10438 ((equal type "help")
10439 (let ((f-or-v (intern path)))
10440 (cond ((fboundp f-or-v)
10441 (describe-function f-or-v))
10442 ((boundp f-or-v)
10443 (describe-variable f-or-v))
10444 (t (error "Not a known function or variable")))))
10446 ((equal type "mailto")
10447 (let ((cmd (car org-link-mailto-program))
10448 (args (cdr org-link-mailto-program)) args1
10449 (address path) (subject "") a)
10450 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10451 (setq address (match-string 1 path)
10452 subject (org-link-escape (match-string 2 path))))
10453 (while args
10454 (cond
10455 ((not (stringp (car args))) (push (pop args) args1))
10456 (t (setq a (pop args))
10457 (if (string-match "%a" a)
10458 (setq a (replace-match address t t a)))
10459 (if (string-match "%s" a)
10460 (setq a (replace-match subject t t a)))
10461 (push a args1))))
10462 (apply cmd (nreverse args1))))
10464 ((member type '("http" "https" "ftp" "news"))
10465 (browse-url
10466 (concat type ":"
10467 (if (org-string-match-p
10468 (concat "[[:nonascii:]"
10469 org-link-escape-chars-browser "]")
10470 path)
10471 (org-link-escape path org-link-escape-chars-browser)
10472 path))))
10474 ((string= type "doi")
10475 (browse-url
10476 (concat org-doi-server-url
10477 (if (org-string-match-p
10478 (concat "[[:nonascii:]"
10479 org-link-escape-chars-browser "]")
10480 path)
10481 (org-link-escape path org-link-escape-chars-browser)
10482 path))))
10484 ((member type '("message"))
10485 (browse-url (concat type ":" path)))
10487 ((string= type "tags")
10488 (org-tags-view arg path))
10490 ((string= type "tree-match")
10491 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10493 ((string= type "file")
10494 (if (string-match "::\\([0-9]+\\)\\'" path)
10495 (setq line (string-to-number (match-string 1 path))
10496 path (substring path 0 (match-beginning 0)))
10497 (if (string-match "::\\(.+\\)\\'" path)
10498 (setq search (match-string 1 path)
10499 path (substring path 0 (match-beginning 0)))))
10500 (if (string-match "[*?{]" (file-name-nondirectory path))
10501 (dired path)
10502 (org-open-file path arg line search)))
10504 ((string= type "shell")
10505 (let ((buf (generate-new-buffer "*Org Shell Output"))
10506 (cmd path))
10507 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10508 (string-match org-confirm-shell-link-not-regexp cmd))
10509 (not org-confirm-shell-link-function)
10510 (funcall org-confirm-shell-link-function
10511 (format "Execute \"%s\" in shell? "
10512 (org-add-props cmd nil
10513 'face 'org-warning))))
10514 (progn
10515 (message "Executing %s" cmd)
10516 (shell-command cmd buf)
10517 (if (featurep 'midnight)
10518 (setq clean-buffer-list-kill-buffer-names
10519 (cons buf clean-buffer-list-kill-buffer-names))))
10520 (error "Abort"))))
10522 ((string= type "elisp")
10523 (let ((cmd path))
10524 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10525 (string-match org-confirm-elisp-link-not-regexp cmd))
10526 (not org-confirm-elisp-link-function)
10527 (funcall org-confirm-elisp-link-function
10528 (format "Execute \"%s\" as elisp? "
10529 (org-add-props cmd nil
10530 'face 'org-warning))))
10531 (message "%s => %s" cmd
10532 (if (equal (string-to-char cmd) ?\()
10533 (eval (read cmd))
10534 (call-interactively (read cmd))))
10535 (error "Abort"))))
10537 ((and (string= type "thisfile")
10538 (or (run-hook-with-args-until-success
10539 'org-open-link-functions path)
10540 (and (string-match "^id:" link)
10541 (or (featurep 'org-id) (require 'org-id))
10542 (progn
10543 (funcall (nth 1 (assoc "id" org-link-protocols))
10544 (substring path 3))
10545 t)))))
10547 ((string= type "thisfile")
10548 (if arg
10549 (switch-to-buffer-other-window
10550 (org-get-buffer-for-internal-link (current-buffer)))
10551 (org-mark-ring-push))
10552 (let ((cmd `(org-link-search
10553 ,path
10554 ,(cond ((equal arg '(4)) ''occur)
10555 ((equal arg '(16)) ''org-occur))
10556 ,pos)))
10557 (condition-case nil (let ((org-link-search-inhibit-query t))
10558 (eval cmd))
10559 (error (progn (widen) (eval cmd))))))
10561 (t (browse-url-at-point)))))))
10562 (move-marker org-open-link-marker nil)
10563 (run-hook-with-args 'org-follow-link-hook)))
10565 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10566 "Offer links in the current entry and return the selected link.
10567 If there is only one link, return it.
10568 If NTH is an integer, return the NTH link found.
10569 If ZERO is a string, check also this string for a link, and if
10570 there is one, return it."
10571 (with-current-buffer buffer
10572 (save-excursion
10573 (save-restriction
10574 (widen)
10575 (goto-char marker)
10576 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10577 "\\(" org-angle-link-re "\\)\\|"
10578 "\\(" org-plain-link-re "\\)"))
10579 (cnt ?0)
10580 (in-emacs (if (integerp nth) nil nth))
10581 have-zero end links link c)
10582 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10583 (push (match-string 0 zero) links)
10584 (setq cnt (1- cnt) have-zero t))
10585 (save-excursion
10586 (org-back-to-heading t)
10587 (setq end (save-excursion (outline-next-heading) (point)))
10588 (while (re-search-forward re end t)
10589 (push (match-string 0) links))
10590 (setq links (org-uniquify (reverse links))))
10591 (cond
10592 ((null links)
10593 (message "No links"))
10594 ((equal (length links) 1)
10595 (setq link (car links)))
10596 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10597 (setq link (nth (if have-zero nth (1- nth)) links)))
10598 (t ; we have to select a link
10599 (save-excursion
10600 (save-window-excursion
10601 (delete-other-windows)
10602 (with-output-to-temp-buffer "*Select Link*"
10603 (mapc (lambda (l)
10604 (if (not (string-match org-bracket-link-regexp l))
10605 (princ (format "[%c] %s\n" (incf cnt)
10606 (org-remove-angle-brackets l)))
10607 (if (match-end 3)
10608 (princ (format "[%c] %s (%s)\n" (incf cnt)
10609 (match-string 3 l) (match-string 1 l)))
10610 (princ (format "[%c] %s\n" (incf cnt)
10611 (match-string 1 l))))))
10612 links))
10613 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10614 (message "Select link to open, RET to open all:")
10615 (setq c (read-char-exclusive))
10616 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10617 (when (equal c ?q) (error "Abort"))
10618 (if (equal c ?\C-m)
10619 (setq link links)
10620 (setq nth (- c ?0))
10621 (if have-zero (setq nth (1+ nth)))
10622 (unless (and (integerp nth) (>= (length links) nth))
10623 (user-error "Invalid link selection"))
10624 (setq link (nth (1- nth) links)))))
10625 (cons link end))))))
10627 ;; Add special file links that specify the way of opening
10629 (org-add-link-type "file+sys" 'org-open-file-with-system)
10630 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10631 (defun org-open-file-with-system (path)
10632 "Open file at PATH using the system way of opening it."
10633 (org-open-file path 'system))
10634 (defun org-open-file-with-emacs (path)
10635 "Open file at PATH in Emacs."
10636 (org-open-file path 'emacs))
10639 ;;; File search
10641 (defvar org-create-file-search-functions nil
10642 "List of functions to construct the right search string for a file link.
10643 These functions are called in turn with point at the location to
10644 which the link should point.
10646 A function in the hook should first test if it would like to
10647 handle this file type, for example by checking the `major-mode'
10648 or the file extension. If it decides not to handle this file, it
10649 should just return nil to give other functions a chance. If it
10650 does handle the file, it must return the search string to be used
10651 when following the link. The search string will be part of the
10652 file link, given after a double colon, and `org-open-at-point'
10653 will automatically search for it. If special measures must be
10654 taken to make the search successful, another function should be
10655 added to the companion hook `org-execute-file-search-functions',
10656 which see.
10658 A function in this hook may also use `setq' to set the variable
10659 `description' to provide a suggestion for the descriptive text to
10660 be used for this link when it gets inserted into an Org-mode
10661 buffer with \\[org-insert-link].")
10663 (defvar org-execute-file-search-functions nil
10664 "List of functions to execute a file search triggered by a link.
10666 Functions added to this hook must accept a single argument, the
10667 search string that was part of the file link, the part after the
10668 double colon. The function must first check if it would like to
10669 handle this search, for example by checking the `major-mode' or
10670 the file extension. If it decides not to handle this search, it
10671 should just return nil to give other functions a chance. If it
10672 does handle the search, it must return a non-nil value to keep
10673 other functions from trying.
10675 Each function can access the current prefix argument through the
10676 variable `current-prefix-arg'. Note that a single prefix is used
10677 to force opening a link in Emacs, so it may be good to only use a
10678 numeric or double prefix to guide the search function.
10680 In case this is needed, a function in this hook can also restore
10681 the window configuration before `org-open-at-point' was called using:
10683 (set-window-configuration org-window-config-before-follow-link)")
10685 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10686 (defun org-link-search (s &optional type avoid-pos stealth)
10687 "Search for a link search option.
10688 If S is surrounded by forward slashes, it is interpreted as a
10689 regular expression. In org-mode files, this will create an `org-occur'
10690 sparse tree. In ordinary files, `occur' will be used to list matches.
10691 If the current buffer is in `dired-mode', grep will be used to search
10692 in all files. If AVOID-POS is given, ignore matches near that position.
10694 When optional argument STEALTH is non-nil, do not modify
10695 visibility around point, thus ignoring
10696 `org-show-hierarchy-above', `org-show-following-heading' and
10697 `org-show-siblings' variables."
10698 (let ((case-fold-search t)
10699 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10700 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10701 (append '(("") (" ") ("\t") ("\n"))
10702 org-emphasis-alist)
10703 "\\|") "\\)"))
10704 (pos (point))
10705 (pre nil) (post nil)
10706 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10707 (cond
10708 ;; First check if there are any special search functions
10709 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10710 ;; Now try the builtin stuff
10711 ((and (equal (string-to-char s0) ?#)
10712 (> (length s0) 1)
10713 (save-excursion
10714 (goto-char (point-min))
10715 (and
10716 (re-search-forward
10717 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10718 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10719 (setq type 'dedicated
10720 pos (match-beginning 0))))
10721 ;; There is an exact target for this
10722 (goto-char pos)
10723 (org-back-to-heading t)))
10724 ((save-excursion
10725 (goto-char (point-min))
10726 (and
10727 (re-search-forward
10728 (concat "<<" (regexp-quote s0) ">>") nil t)
10729 (setq type 'dedicated
10730 pos (match-beginning 0))))
10731 ;; There is an exact target for this
10732 (goto-char pos))
10733 ((save-excursion
10734 (goto-char (point-min))
10735 (and
10736 (re-search-forward
10737 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10738 (setq type 'dedicated pos (match-beginning 0))))
10739 ;; Found an element with a matching #+name affiliated keyword.
10740 (goto-char pos))
10741 ((and (string-match "^(\\(.*\\))$" s0)
10742 (save-excursion
10743 (goto-char (point-min))
10744 (and
10745 (re-search-forward
10746 (concat "[^[]" (regexp-quote
10747 (format org-coderef-label-format
10748 (match-string 1 s0))))
10749 nil t)
10750 (setq type 'dedicated
10751 pos (1+ (match-beginning 0))))))
10752 ;; There is a coderef target for this
10753 (goto-char pos))
10754 ((string-match "^/\\(.*\\)/$" s)
10755 ;; A regular expression
10756 (cond
10757 ((derived-mode-p 'org-mode)
10758 (org-occur (match-string 1 s)))
10759 (t (org-do-occur (match-string 1 s)))))
10760 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10761 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10762 (goto-char (point-min))
10763 (cond
10764 ((let (case-fold-search)
10765 (re-search-forward (format org-complex-heading-regexp-format
10766 (regexp-quote s))
10767 nil t))
10768 ;; OK, found a match
10769 (setq type 'dedicated)
10770 (goto-char (match-beginning 0)))
10771 ((and (not org-link-search-inhibit-query)
10772 (eq org-link-search-must-match-exact-headline 'query-to-create)
10773 (y-or-n-p "No match - create this as a new heading? "))
10774 (goto-char (point-max))
10775 (or (bolp) (newline))
10776 (insert "* " s "\n")
10777 (beginning-of-line 0))
10779 (goto-char pos)
10780 (error "No match"))))
10782 ;; A normal search string
10783 (when (equal (string-to-char s) ?*)
10784 ;; Anchor on headlines, post may include tags.
10785 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10786 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10787 s (substring s 1)))
10788 (remove-text-properties
10789 0 (length s)
10790 '(face nil mouse-face nil keymap nil fontified nil) s)
10791 ;; Make a series of regular expressions to find a match
10792 (setq words (org-split-string s "[ \n\r\t]+")
10794 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10795 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10796 "\\)" markers)
10797 re2a_ (concat "\\(" (mapconcat 'downcase words
10798 "[ \t\r\n]+") "\\)[ \t\r\n]")
10799 re2a (concat "[ \t\r\n]" re2a_)
10800 re4_ (concat "\\(" (mapconcat 'downcase words
10801 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10802 re4 (concat "[^a-zA-Z_]" re4_)
10804 re1 (concat pre re2 post)
10805 re3 (concat pre (if pre re4_ re4) post)
10806 re5 (concat pre ".*" re4)
10807 re2 (concat pre re2)
10808 re2a (concat pre (if pre re2a_ re2a))
10809 re4 (concat pre (if pre re4_ re4))
10810 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10811 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10812 re5 "\\)"))
10813 (cond
10814 ((eq type 'org-occur) (org-occur reall))
10815 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10816 (t (goto-char (point-min))
10817 (setq type 'fuzzy)
10818 (if (or (and (org-search-not-self 1 re0 nil t)
10819 (setq type 'dedicated))
10820 (org-search-not-self 1 re1 nil t)
10821 (org-search-not-self 1 re2 nil t)
10822 (org-search-not-self 1 re2a nil t)
10823 (org-search-not-self 1 re3 nil t)
10824 (org-search-not-self 1 re4 nil t)
10825 (org-search-not-self 1 re5 nil t))
10826 (goto-char (match-beginning 1))
10827 (goto-char pos)
10828 (error "No match"))))))
10829 (and (derived-mode-p 'org-mode)
10830 (not stealth)
10831 (org-show-context 'link-search))
10832 type))
10834 (defun org-search-not-self (group &rest args)
10835 "Execute `re-search-forward', but only accept matches that do not
10836 enclose the position of `org-open-link-marker'."
10837 (let ((m org-open-link-marker))
10838 (catch 'exit
10839 (while (apply 're-search-forward args)
10840 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10841 (goto-char (match-end group))
10842 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10843 (> (match-beginning 0) (marker-position m))
10844 (< (match-end 0) (marker-position m)))
10845 (save-match-data
10846 (or (not (org-in-regexp
10847 org-bracket-link-analytic-regexp 1))
10848 (not (match-end 4)) ; no description
10849 (and (<= (match-beginning 4) (point))
10850 (>= (match-end 4) (point))))))
10851 (throw 'exit (point))))))))
10853 (defun org-get-buffer-for-internal-link (buffer)
10854 "Return a buffer to be used for displaying the link target of internal links."
10855 (cond
10856 ((not org-display-internal-link-with-indirect-buffer)
10857 buffer)
10858 ((string-match "(Clone)$" (buffer-name buffer))
10859 (message "Buffer is already a clone, not making another one")
10860 ;; we also do not modify visibility in this case
10861 buffer)
10862 (t ; make a new indirect buffer for displaying the link
10863 (let* ((bn (buffer-name buffer))
10864 (ibn (concat bn "(Clone)"))
10865 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10866 (with-current-buffer ib (org-overview))
10867 ib))))
10869 (defun org-do-occur (regexp &optional cleanup)
10870 "Call the Emacs command `occur'.
10871 If CLEANUP is non-nil, remove the printout of the regular expression
10872 in the *Occur* buffer. This is useful if the regex is long and not useful
10873 to read."
10874 (occur regexp)
10875 (when cleanup
10876 (let ((cwin (selected-window)) win beg end)
10877 (when (setq win (get-buffer-window "*Occur*"))
10878 (select-window win))
10879 (goto-char (point-min))
10880 (when (re-search-forward "match[a-z]+" nil t)
10881 (setq beg (match-end 0))
10882 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10883 (setq end (1- (match-beginning 0)))))
10884 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10885 (goto-char (point-min))
10886 (select-window cwin))))
10888 ;;; The mark ring for links jumps
10890 (defvar org-mark-ring nil
10891 "Mark ring for positions before jumps in Org-mode.")
10892 (defvar org-mark-ring-last-goto nil
10893 "Last position in the mark ring used to go back.")
10894 ;; Fill and close the ring
10895 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10896 (loop for i from 1 to org-mark-ring-length do
10897 (push (make-marker) org-mark-ring))
10898 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10899 org-mark-ring)
10901 (defun org-mark-ring-push (&optional pos buffer)
10902 "Put the current position or POS into the mark ring and rotate it."
10903 (interactive)
10904 (setq pos (or pos (point)))
10905 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10906 (move-marker (car org-mark-ring)
10907 (or pos (point))
10908 (or buffer (current-buffer)))
10909 (message "%s"
10910 (substitute-command-keys
10911 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10913 (defun org-mark-ring-goto (&optional n)
10914 "Jump to the previous position in the mark ring.
10915 With prefix arg N, jump back that many stored positions. When
10916 called several times in succession, walk through the entire ring.
10917 Org-mode commands jumping to a different position in the current file,
10918 or to another Org-mode file, automatically push the old position
10919 onto the ring."
10920 (interactive "p")
10921 (let (p m)
10922 (if (eq last-command this-command)
10923 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10924 (setq p org-mark-ring))
10925 (setq org-mark-ring-last-goto p)
10926 (setq m (car p))
10927 (org-pop-to-buffer-same-window (marker-buffer m))
10928 (goto-char m)
10929 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10931 (defun org-remove-angle-brackets (s)
10932 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10933 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10935 (defun org-add-angle-brackets (s)
10936 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10937 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10939 (defun org-remove-double-quotes (s)
10940 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10941 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10944 ;;; Following specific links
10946 (defun org-follow-timestamp-link ()
10947 "Open an agenda view for the time-stamp date/range at point."
10948 (cond
10949 ((org-at-date-range-p t)
10950 (let ((org-agenda-start-on-weekday)
10951 (t1 (match-string 1))
10952 (t2 (match-string 2)) tt1 tt2)
10953 (setq tt1 (time-to-days (org-time-string-to-time t1))
10954 tt2 (time-to-days (org-time-string-to-time t2)))
10955 (let ((org-agenda-buffer-tmp-name
10956 (format "*Org Agenda(a:%s)"
10957 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10958 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10959 ((org-at-timestamp-p t)
10960 (let ((org-agenda-buffer-tmp-name
10961 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10962 (org-agenda-list nil (time-to-days (org-time-string-to-time
10963 (substring (match-string 1) 0 10)))
10964 1)))
10965 (t (error "This should not happen"))))
10968 ;;; Following file links
10969 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10970 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10971 (declare-function mailcap-mime-info
10972 "mailcap" (string &optional request no-decode))
10973 (defvar org-wait nil)
10974 (defun org-open-file (path &optional in-emacs line search)
10975 "Open the file at PATH.
10976 First, this expands any special file name abbreviations. Then the
10977 configuration variable `org-file-apps' is checked if it contains an
10978 entry for this file type, and if yes, the corresponding command is launched.
10980 If no application is found, Emacs simply visits the file.
10982 With optional prefix argument IN-EMACS, Emacs will visit the file.
10983 With a double \\[universal-argument] \\[universal-argument] \
10984 prefix arg, Org tries to avoid opening in Emacs
10985 and to use an external application to visit the file.
10987 Optional LINE specifies a line to go to, optional SEARCH a string
10988 to search for. If LINE or SEARCH is given, the file will be
10989 opened in Emacs, unless an entry from org-file-apps that makes
10990 use of groups in a regexp matches.
10992 If you want to change the way frames are used when following a
10993 link, please customize `org-link-frame-setup'.
10995 If the file does not exist, an error is thrown."
10996 (let* ((file (if (equal path "")
10997 buffer-file-name
10998 (substitute-in-file-name (expand-file-name path))))
10999 (file-apps (append org-file-apps (org-default-apps)))
11000 (apps (org-remove-if
11001 'org-file-apps-entry-match-against-dlink-p file-apps))
11002 (apps-dlink (org-remove-if-not
11003 'org-file-apps-entry-match-against-dlink-p file-apps))
11004 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11005 (dirp (if remp nil (file-directory-p file)))
11006 (file (if (and dirp org-open-directory-means-index-dot-org)
11007 (concat (file-name-as-directory file) "index.org")
11008 file))
11009 (a-m-a-p (assq 'auto-mode apps))
11010 (dfile (downcase file))
11011 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
11012 (link (cond ((and (eq line nil)
11013 (eq search nil))
11014 file)
11015 (line
11016 (concat file "::" (number-to-string line)))
11017 (search
11018 (concat file "::" search))))
11019 (dlink (downcase link))
11020 (old-buffer (current-buffer))
11021 (old-pos (point))
11022 (old-mode major-mode)
11023 ext cmd link-match-data)
11024 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11025 (setq ext (match-string 1 dfile))
11026 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11027 (setq ext (match-string 1 dfile))))
11028 (cond
11029 ((member in-emacs '((16) system))
11030 (setq cmd (cdr (assoc 'system apps))))
11031 (in-emacs (setq cmd 'emacs))
11033 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11034 (and dirp (cdr (assoc 'directory apps)))
11035 ; first, try matching against apps-dlink
11036 ; if we get a match here, store the match data for later
11037 (let ((match (assoc-default dlink apps-dlink
11038 'string-match)))
11039 (if match
11040 (progn (setq link-match-data (match-data))
11041 match)
11042 (progn (setq in-emacs (or in-emacs line search))
11043 nil))) ; if we have no match in apps-dlink,
11044 ; always open the file in emacs if line or search
11045 ; is given (for backwards compatibility)
11046 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11047 'string-match)
11048 (cdr (assoc ext apps))
11049 (cdr (assoc t apps))))))
11050 (when (eq cmd 'system)
11051 (setq cmd (cdr (assoc 'system apps))))
11052 (when (eq cmd 'default)
11053 (setq cmd (cdr (assoc t apps))))
11054 (when (eq cmd 'mailcap)
11055 (require 'mailcap)
11056 (mailcap-parse-mailcaps)
11057 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11058 (command (mailcap-mime-info mime-type)))
11059 (if (stringp command)
11060 (setq cmd command)
11061 (setq cmd 'emacs))))
11062 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11063 (not (file-exists-p file))
11064 (not org-open-non-existing-files))
11065 (user-error "No such file: %s" file))
11066 (cond
11067 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11068 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11069 (while (string-match "['\"]%s['\"]" cmd)
11070 (setq cmd (replace-match "%s" t t cmd)))
11071 (while (string-match "%s" cmd)
11072 (setq cmd (replace-match
11073 (save-match-data
11074 (shell-quote-argument
11075 (convert-standard-filename file)))
11076 t t cmd)))
11078 ;; Replace "%1", "%2" etc. in command with group matches from regex
11079 (save-match-data
11080 (let ((match-index 1)
11081 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11082 (set-match-data link-match-data)
11083 (while (<= match-index number-of-groups)
11084 (let ((regex (concat "%" (number-to-string match-index)))
11085 (replace-with (match-string match-index dlink)))
11086 (while (string-match regex cmd)
11087 (setq cmd (replace-match replace-with t t cmd))))
11088 (setq match-index (+ match-index 1)))))
11090 (save-window-excursion
11091 (message "Running %s...done" cmd)
11092 (start-process-shell-command cmd nil cmd)
11093 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11094 ((or (stringp cmd)
11095 (eq cmd 'emacs))
11096 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11097 (widen)
11098 (if line (org-goto-line line)
11099 (if search (org-link-search search))))
11100 ((consp cmd)
11101 (let ((file (convert-standard-filename file)))
11102 (save-match-data
11103 (set-match-data link-match-data)
11104 (eval cmd))))
11105 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11106 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11107 (or (not (equal old-buffer (current-buffer)))
11108 (not (equal old-pos (point))))
11109 (org-mark-ring-push old-pos old-buffer))))
11111 (defun org-file-apps-entry-match-against-dlink-p (entry)
11112 "This function returns non-nil if `entry' uses a regular
11113 expression which should be matched against the whole link by
11114 org-open-file.
11116 It assumes that is the case when the entry uses a regular
11117 expression which has at least one grouping construct and the
11118 action is either a lisp form or a command string containing
11119 '%1', i.e. using at least one subexpression match as a
11120 parameter."
11121 (let ((selector (car entry))
11122 (action (cdr entry)))
11123 (if (stringp selector)
11124 (and (> (regexp-opt-depth selector) 0)
11125 (or (and (stringp action)
11126 (string-match "%[0-9]" action))
11127 (consp action)))
11128 nil)))
11130 (defun org-default-apps ()
11131 "Return the default applications for this operating system."
11132 (cond
11133 ((eq system-type 'darwin)
11134 org-file-apps-defaults-macosx)
11135 ((eq system-type 'windows-nt)
11136 org-file-apps-defaults-windowsnt)
11137 (t org-file-apps-defaults-gnu)))
11139 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11140 "Convert extensions to regular expressions in the cars of LIST.
11141 Also, weed out any non-string entries, because the return value is used
11142 only for regexp matching.
11143 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11144 point to the symbol `emacs', indicating that the file should
11145 be opened in Emacs."
11146 (append
11147 (delq nil
11148 (mapcar (lambda (x)
11149 (if (not (stringp (car x)))
11151 (if (string-match "\\W" (car x))
11153 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11154 list))
11155 (if add-auto-mode
11156 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11158 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11159 (defun org-file-remote-p (file)
11160 "Test whether FILE specifies a location on a remote system.
11161 Return non-nil if the location is indeed remote.
11163 For example, the filename \"/user@host:/foo\" specifies a location
11164 on the system \"/user@host:\"."
11165 (cond ((fboundp 'file-remote-p)
11166 (file-remote-p file))
11167 ((fboundp 'tramp-handle-file-remote-p)
11168 (tramp-handle-file-remote-p file))
11169 ((and (boundp 'ange-ftp-name-format)
11170 (string-match (car ange-ftp-name-format) file))
11171 t)))
11174 ;;;; Refiling
11176 (defun org-get-org-file ()
11177 "Read a filename, with default directory `org-directory'."
11178 (let ((default (or org-default-notes-file remember-data-file)))
11179 (read-file-name (format "File name [%s]: " default)
11180 (file-name-as-directory org-directory)
11181 default)))
11183 (defun org-notes-order-reversed-p ()
11184 "Check if the current file should receive notes in reversed order."
11185 (cond
11186 ((not org-reverse-note-order) nil)
11187 ((eq t org-reverse-note-order) t)
11188 ((not (listp org-reverse-note-order)) nil)
11189 (t (catch 'exit
11190 (let ((all org-reverse-note-order)
11191 entry)
11192 (while (setq entry (pop all))
11193 (if (string-match (car entry) buffer-file-name)
11194 (throw 'exit (cdr entry))))
11195 nil)))))
11197 (defvar org-refile-target-table nil
11198 "The list of refile targets, created by `org-refile'.")
11200 (defvar org-agenda-new-buffers nil
11201 "Buffers created to visit agenda files.")
11203 (defvar org-refile-cache nil
11204 "Cache for refile targets.")
11206 (defvar org-refile-markers nil
11207 "All the markers used for caching refile locations.")
11209 (defun org-refile-marker (pos)
11210 "Get a new refile marker, but only if caching is in use."
11211 (if (not org-refile-use-cache)
11213 (let ((m (make-marker)))
11214 (move-marker m pos)
11215 (push m org-refile-markers)
11216 m)))
11218 (defun org-refile-cache-clear ()
11219 "Clear the refile cache and disable all the markers."
11220 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11221 (setq org-refile-markers nil)
11222 (setq org-refile-cache nil)
11223 (message "Refile cache has been cleared"))
11225 (defun org-refile-cache-check-set (set)
11226 "Check if all the markers in the cache still have live buffers."
11227 (let (marker)
11228 (catch 'exit
11229 (while (and set (setq marker (nth 3 (pop set))))
11230 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11231 (when (and marker (null (marker-buffer marker)))
11232 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11233 (sit-for 3)
11234 (throw 'exit nil)))
11235 t)))
11237 (defun org-refile-cache-put (set &rest identifiers)
11238 "Push the refile targets SET into the cache, under IDENTIFIERS."
11239 (let* ((key (sha1 (prin1-to-string identifiers)))
11240 (entry (assoc key org-refile-cache)))
11241 (if entry
11242 (setcdr entry set)
11243 (push (cons key set) org-refile-cache))))
11245 (defun org-refile-cache-get (&rest identifiers)
11246 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11247 (cond
11248 ((not org-refile-cache) nil)
11249 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11251 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11252 org-refile-cache))))
11253 (and set (org-refile-cache-check-set set) set)))))
11255 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11256 "Produce a table with refile targets."
11257 (let ((case-fold-search nil)
11258 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11259 (entries (or org-refile-targets '((nil . (:level . 1)))))
11260 targets tgs txt re files f desc descre fast-path-p level pos0)
11261 (message "Getting targets...")
11262 (with-current-buffer (or default-buffer (current-buffer))
11263 (while (setq entry (pop entries))
11264 (setq files (car entry) desc (cdr entry))
11265 (setq fast-path-p nil)
11266 (cond
11267 ((null files) (setq files (list (current-buffer))))
11268 ((eq files 'org-agenda-files)
11269 (setq files (org-agenda-files 'unrestricted)))
11270 ((and (symbolp files) (fboundp files))
11271 (setq files (funcall files)))
11272 ((and (symbolp files) (boundp files))
11273 (setq files (symbol-value files))))
11274 (if (stringp files) (setq files (list files)))
11275 (cond
11276 ((eq (car desc) :tag)
11277 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11278 ((eq (car desc) :todo)
11279 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11280 ((eq (car desc) :regexp)
11281 (setq descre (cdr desc)))
11282 ((eq (car desc) :level)
11283 (setq descre (concat "^\\*\\{" (number-to-string
11284 (if org-odd-levels-only
11285 (1- (* 2 (cdr desc)))
11286 (cdr desc)))
11287 "\\}[ \t]")))
11288 ((eq (car desc) :maxlevel)
11289 (setq fast-path-p t)
11290 (setq descre (concat "^\\*\\{1," (number-to-string
11291 (if org-odd-levels-only
11292 (1- (* 2 (cdr desc)))
11293 (cdr desc)))
11294 "\\}[ \t]")))
11295 (t (error "Bad refiling target description %s" desc)))
11296 (while (setq f (pop files))
11297 (with-current-buffer
11298 (if (bufferp f) f (org-get-agenda-file-buffer f))
11300 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11301 (progn
11302 (if (bufferp f) (setq f (buffer-file-name
11303 (buffer-base-buffer f))))
11304 (setq f (and f (expand-file-name f)))
11305 (if (eq org-refile-use-outline-path 'file)
11306 (push (list (file-name-nondirectory f) f nil nil) tgs))
11307 (save-excursion
11308 (save-restriction
11309 (widen)
11310 (goto-char (point-min))
11311 (while (re-search-forward descre nil t)
11312 (goto-char (setq pos0 (point-at-bol)))
11313 (catch 'next
11314 (when org-refile-target-verify-function
11315 (save-match-data
11316 (or (funcall org-refile-target-verify-function)
11317 (throw 'next t))))
11318 (when (and (looking-at org-complex-heading-regexp)
11319 (not (member (match-string 4) excluded-entries))
11320 (match-string 4))
11321 (setq level (org-reduced-level
11322 (- (match-end 1) (match-beginning 1)))
11323 txt (org-link-display-format (match-string 4))
11324 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11325 re (format org-complex-heading-regexp-format
11326 (regexp-quote (match-string 4))))
11327 (when org-refile-use-outline-path
11328 (setq txt (mapconcat
11329 'org-protect-slash
11330 (append
11331 (if (eq org-refile-use-outline-path
11332 'file)
11333 (list (file-name-nondirectory
11334 (buffer-file-name
11335 (buffer-base-buffer))))
11336 (if (eq org-refile-use-outline-path
11337 'full-file-path)
11338 (list (buffer-file-name
11339 (buffer-base-buffer)))))
11340 (org-get-outline-path fast-path-p
11341 level txt)
11342 (list txt))
11343 "/")))
11344 (push (list txt f re (org-refile-marker (point)))
11345 tgs)))
11346 (when (= (point) pos0)
11347 ;; verification function has not moved point
11348 (goto-char (point-at-eol))))))))
11349 (when org-refile-use-cache
11350 (org-refile-cache-put tgs (buffer-file-name) descre))
11351 (setq targets (append tgs targets))))))
11352 (message "Getting targets...done")
11353 (nreverse targets)))
11355 (defun org-protect-slash (s)
11356 (while (string-match "/" s)
11357 (setq s (replace-match "\\" t t s)))
11360 (defvar org-olpa (make-vector 20 nil))
11362 (defun org-get-outline-path (&optional fastp level heading)
11363 "Return the outline path to the current entry, as a list.
11365 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11366 routine which makes outline path derivations for an entire file,
11367 avoiding backtracing. Refile target collection makes use of that."
11368 (if fastp
11369 (progn
11370 (if (> level 19)
11371 (error "Outline path failure, more than 19 levels"))
11372 (loop for i from level upto 19 do
11373 (aset org-olpa i nil))
11374 (prog1
11375 (delq nil (append org-olpa nil))
11376 (aset org-olpa level heading)))
11377 (let (rtn case-fold-search)
11378 (save-excursion
11379 (save-restriction
11380 (widen)
11381 (while (org-up-heading-safe)
11382 (when (looking-at org-complex-heading-regexp)
11383 (push (org-trim
11384 (replace-regexp-in-string
11385 ;; Remove statistical/checkboxes cookies
11386 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11387 (org-match-string-no-properties 4)))
11388 rtn)))
11389 rtn)))))
11391 (defun org-format-outline-path (path &optional width prefix separator)
11392 "Format the outline path PATH for display.
11393 WIDTH is the maximum number of characters that is available.
11394 PREFIX is a prefix to be included in the returned string,
11395 such as the file name.
11396 SEPARATOR is inserted between the different parts of the path,
11397 the default is \"/\"."
11398 (setq width (or width 79))
11399 (if prefix (setq width (- width (length prefix))))
11400 (if (not path)
11401 (or prefix "")
11402 (let* ((nsteps (length path))
11403 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11404 (maxwidth (if (<= total-width width)
11405 10000 ;; everything fits
11406 ;; we need to shorten the level headings
11407 (/ (- width nsteps) nsteps)))
11408 (org-odd-levels-only nil)
11409 (n 0)
11410 (total (1+ (length prefix))))
11411 (setq maxwidth (max maxwidth 10))
11412 (concat prefix
11413 (if prefix (or separator "/"))
11414 (mapconcat
11415 (lambda (h)
11416 (setq n (1+ n))
11417 (if (and (= n nsteps) (< maxwidth 10000))
11418 (setq maxwidth (- total-width total)))
11419 (if (< (length h) maxwidth)
11420 (progn (setq total (+ total (length h) 1)) h)
11421 (setq h (substring h 0 (- maxwidth 2))
11422 total (+ total maxwidth 1))
11423 (if (string-match "[ \t]+\\'" h)
11424 (setq h (substring h 0 (match-beginning 0))))
11425 (setq h (concat h "..")))
11426 (org-add-props h nil 'face
11427 (nth (% (1- n) org-n-level-faces)
11428 org-level-faces))
11430 path (or separator "/"))))))
11432 (defun org-display-outline-path (&optional file current separator just-return-string)
11433 "Display the current outline path in the echo area.
11435 If FILE is non-nil, prepend the output with the file name.
11436 If CURRENT is non-nil, append the current heading to the output.
11437 SEPARATOR is passed through to `org-format-outline-path'. It separates
11438 the different parts of the path and defaults to \"/\".
11439 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11440 (interactive "P")
11441 (let* (case-fold-search
11442 (bfn (buffer-file-name (buffer-base-buffer)))
11443 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11444 res)
11445 (if current (setq path (append path
11446 (save-excursion
11447 (org-back-to-heading t)
11448 (if (looking-at org-complex-heading-regexp)
11449 (list (match-string 4)))))))
11450 (setq res
11451 (org-format-outline-path
11452 path
11453 (1- (frame-width))
11454 (and file bfn (concat (file-name-nondirectory bfn) separator))
11455 separator))
11456 (if just-return-string
11457 (org-no-properties res)
11458 (org-unlogged-message "%s" res))))
11460 (defvar org-refile-history nil
11461 "History for refiling operations.")
11463 (defvar org-after-refile-insert-hook nil
11464 "Hook run after `org-refile' has inserted its stuff at the new location.
11465 Note that this is still *before* the stuff will be removed from
11466 the *old* location.")
11468 (defvar org-capture-last-stored-marker)
11469 (defvar org-refile-keep nil
11470 "Non-nil means `org-refile' will copy instead of refile.")
11472 (defun org-copy ()
11473 "Like `org-refile', but copy."
11474 (interactive)
11475 (let ((org-refile-keep t))
11476 (funcall 'org-refile nil nil nil "Copy")))
11478 (defun org-refile (&optional goto default-buffer rfloc msg)
11479 "Move the entry or entries at point to another heading.
11480 The list of target headings is compiled using the information in
11481 `org-refile-targets', which see.
11483 At the target location, the entry is filed as a subitem of the target
11484 heading. Depending on `org-reverse-note-order', the new subitem will
11485 either be the first or the last subitem.
11487 If there is an active region, all entries in that region will be moved.
11488 However, the region must fulfill the requirement that the first heading
11489 is the first one sets the top-level of the moved text - at most siblings
11490 below it are allowed.
11492 With prefix arg GOTO, the command will only visit the target location
11493 and not actually move anything.
11495 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11496 go to the location where the last refiling operation has put the subtree.
11498 With a numeric prefix argument of `2', refile to the running clock.
11500 With a numeric prefix argument of `3', emulate `org-refile-keep'
11501 being set to `t' and copy to the target location, don't move it.
11502 Beware that keeping refiled entries may result in duplicated ID
11503 properties.
11505 RFLOC can be a refile location obtained in a different way.
11507 MSG is a string to replace \"Refile\" in the default prompt with
11508 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11510 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11512 If you are using target caching (see `org-refile-use-cache'),
11513 you have to clear the target cache in order to find new targets.
11514 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11515 prefix argument (`C-u C-u C-u C-c C-w')."
11517 (interactive "P")
11518 (if (member goto '(0 (64)))
11519 (org-refile-cache-clear)
11520 (let* ((actionmsg (or msg "Refile"))
11521 (cbuf (current-buffer))
11522 (regionp (org-region-active-p))
11523 (region-start (and regionp (region-beginning)))
11524 (region-end (and regionp (region-end)))
11525 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11526 (org-refile-keep (if (equal goto 3) t org-refile-keep))
11527 pos it nbuf file re level reversed)
11528 (setq last-command nil)
11529 (when regionp
11530 (goto-char region-start)
11531 (or (bolp) (goto-char (point-at-bol)))
11532 (setq region-start (point))
11533 (unless (or (org-kill-is-subtree-p
11534 (buffer-substring region-start region-end))
11535 (prog1 org-refile-active-region-within-subtree
11536 (let ((s (point-at-eol)))
11537 (org-toggle-heading)
11538 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11539 (user-error "The region is not a (sequence of) subtree(s)")))
11540 (if (equal goto '(16))
11541 (org-refile-goto-last-stored)
11542 (when (or
11543 (and (equal goto 2)
11544 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11545 (prog1
11546 (setq it (list (or org-clock-heading "running clock")
11547 (buffer-file-name
11548 (marker-buffer org-clock-hd-marker))
11550 (marker-position org-clock-hd-marker)))
11551 (setq goto nil)))
11552 (setq it (or rfloc
11553 (let (heading-text)
11554 (save-excursion
11555 (unless goto
11556 (org-back-to-heading t)
11557 (setq heading-text
11558 (nth 4 (org-heading-components))))
11560 (org-refile-get-location
11561 (cond (goto "Goto")
11562 (regionp (concat actionmsg " region to"))
11563 (t (concat actionmsg " subtree \""
11564 heading-text "\" to")))
11565 default-buffer
11566 (and (not (equal '(4) goto))
11567 org-refile-allow-creating-parent-nodes)
11568 goto))))))
11569 (setq file (nth 1 it)
11570 re (nth 2 it)
11571 pos (nth 3 it))
11572 (if (and (not goto)
11574 (equal (buffer-file-name) file)
11575 (if regionp
11576 (and (>= pos region-start)
11577 (<= pos region-end))
11578 (and (>= pos (point))
11579 (< pos (save-excursion
11580 (org-end-of-subtree t t))))))
11581 (error "Cannot refile to position inside the tree or region"))
11583 (setq nbuf (or (find-buffer-visiting file)
11584 (find-file-noselect file)))
11585 (if (and goto (not (equal goto 3)))
11586 (progn
11587 (org-pop-to-buffer-same-window nbuf)
11588 (goto-char pos)
11589 (org-show-context 'org-goto))
11590 (if regionp
11591 (progn
11592 (org-kill-new (buffer-substring region-start region-end))
11593 (org-save-markers-in-region region-start region-end))
11594 (org-copy-subtree 1 nil t))
11595 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11596 (find-file-noselect file)))
11597 (setq reversed (org-notes-order-reversed-p))
11598 (save-excursion
11599 (save-restriction
11600 (widen)
11601 (if pos
11602 (progn
11603 (goto-char pos)
11604 (looking-at org-outline-regexp)
11605 (setq level (org-get-valid-level (funcall outline-level) 1))
11606 (goto-char
11607 (if reversed
11608 (or (outline-next-heading) (point-max))
11609 (or (save-excursion (org-get-next-sibling))
11610 (org-end-of-subtree t t)
11611 (point-max)))))
11612 (setq level 1)
11613 (if (not reversed)
11614 (goto-char (point-max))
11615 (goto-char (point-min))
11616 (or (outline-next-heading) (goto-char (point-max)))))
11617 (if (not (bolp)) (newline))
11618 (org-paste-subtree level)
11619 (when org-log-refile
11620 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11621 (unless (eq org-log-refile 'note)
11622 (save-excursion (org-add-log-note))))
11623 (and org-auto-align-tags
11624 (let ((org-loop-over-headlines-in-active-region nil))
11625 (org-set-tags nil t)))
11626 (let ((bookmark-name (plist-get org-bookmark-names-plist
11627 :last-refile)))
11628 (when bookmark-name
11629 (with-demoted-errors
11630 (bookmark-set bookmark-name))))
11631 ;; If we are refiling for capture, make sure that the
11632 ;; last-capture pointers point here
11633 (when (org-bound-and-true-p org-refile-for-capture)
11634 (let ((bookmark-name (plist-get org-bookmark-names-plist
11635 :last-capture-marker)))
11636 (when bookmark-name
11637 (with-demoted-errors
11638 (bookmark-set bookmark-name))))
11639 (move-marker org-capture-last-stored-marker (point)))
11640 (if (fboundp 'deactivate-mark) (deactivate-mark))
11641 (run-hooks 'org-after-refile-insert-hook))))
11642 (unless org-refile-keep
11643 (if regionp
11644 (delete-region (point) (+ (point) (- region-end region-start)))
11645 (delete-region
11646 (and (org-back-to-heading t) (point))
11647 (min (buffer-size) (org-end-of-subtree t t) (point)))))
11648 (when (featurep 'org-inlinetask)
11649 (org-inlinetask-remove-END-maybe))
11650 (setq org-markers-to-move nil)
11651 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11653 (defun org-refile-goto-last-stored ()
11654 "Go to the location where the last refile was stored."
11655 (interactive)
11656 (bookmark-jump "org-refile-last-stored")
11657 (message "This is the location of the last refile"))
11659 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11660 no-exclude)
11661 "Prompt the user for a refile location, using PROMPT.
11662 PROMPT should not be suffixed with a colon and a space, because
11663 this function appends the default value from
11664 `org-refile-history' automatically, if that is not empty.
11665 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11666 this is used for the GOTO interface."
11667 (let ((org-refile-targets org-refile-targets)
11668 (org-refile-use-outline-path org-refile-use-outline-path)
11669 excluded-entries)
11670 (when (and (derived-mode-p 'org-mode)
11671 (not org-refile-use-cache)
11672 (not no-exclude))
11673 (org-map-tree
11674 (lambda()
11675 (setq excluded-entries
11676 (append excluded-entries (list (org-get-heading t t)))))))
11677 (setq org-refile-target-table
11678 (org-refile-get-targets default-buffer excluded-entries)))
11679 (unless org-refile-target-table
11680 (user-error "No refile targets"))
11681 (let* ((cbuf (current-buffer))
11682 (partial-completion-mode nil)
11683 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11684 (cfunc (if (and org-refile-use-outline-path
11685 org-outline-path-complete-in-steps)
11686 'org-olpath-completing-read
11687 'org-icompleting-read))
11688 (extra (if org-refile-use-outline-path "/" ""))
11689 (cbnex (concat (buffer-name) extra))
11690 (filename (and cfn (expand-file-name cfn)))
11691 (tbl (mapcar
11692 (lambda (x)
11693 (if (and (not (member org-refile-use-outline-path
11694 '(file full-file-path)))
11695 (not (equal filename (nth 1 x))))
11696 (cons (concat (car x) extra " ("
11697 (file-name-nondirectory (nth 1 x)) ")")
11698 (cdr x))
11699 (cons (concat (car x) extra) (cdr x))))
11700 org-refile-target-table))
11701 (completion-ignore-case t)
11702 cdef
11703 (prompt (concat prompt
11704 (or (and (car org-refile-history)
11705 (concat " (default " (car org-refile-history) ")"))
11706 (and (assoc cbnex tbl) (setq cdef cbnex)
11707 (concat " (default " cbnex ")"))) ": "))
11708 pa answ parent-target child parent old-hist)
11709 (setq old-hist org-refile-history)
11710 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11711 nil 'org-refile-history (or cdef (car org-refile-history))))
11712 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11713 (org-refile-check-position pa)
11714 (if pa
11715 (progn
11716 (when (or (not org-refile-history)
11717 (not (eq old-hist org-refile-history))
11718 (not (equal (car pa) (car org-refile-history))))
11719 (setq org-refile-history
11720 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11721 org-refile-history
11722 (cdr org-refile-history))))
11723 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11724 (pop org-refile-history)))
11726 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11727 (progn
11728 (setq parent (match-string 1 answ)
11729 child (match-string 2 answ))
11730 (setq parent-target (or (assoc parent tbl)
11731 (assoc (concat parent "/") tbl)))
11732 (when (and parent-target
11733 (or (eq new-nodes t)
11734 (and (eq new-nodes 'confirm)
11735 (y-or-n-p (format "Create new node \"%s\"? "
11736 child)))))
11737 (org-refile-new-child parent-target child)))
11738 (user-error "Invalid target location")))))
11740 (declare-function org-string-nw-p "org-macs" (s))
11741 (defun org-refile-check-position (refile-pointer)
11742 "Check if the refile pointer matches the headline to which it points."
11743 (let* ((file (nth 1 refile-pointer))
11744 (re (nth 2 refile-pointer))
11745 (pos (nth 3 refile-pointer))
11746 buffer)
11747 (if (and (not (markerp pos)) (not file))
11748 (user-error "Please save the buffer to a file before refiling")
11749 (when (org-string-nw-p re)
11750 (setq buffer (if (markerp pos)
11751 (marker-buffer pos)
11752 (or (find-buffer-visiting file)
11753 (find-file-noselect file))))
11754 (with-current-buffer buffer
11755 (save-excursion
11756 (save-restriction
11757 (widen)
11758 (goto-char pos)
11759 (beginning-of-line 1)
11760 (unless (org-looking-at-p re)
11761 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11763 (defun org-refile-new-child (parent-target child)
11764 "Use refile target PARENT-TARGET to add new CHILD below it."
11765 (unless parent-target
11766 (error "Cannot find parent for new node"))
11767 (let ((file (nth 1 parent-target))
11768 (pos (nth 3 parent-target))
11769 level)
11770 (with-current-buffer (or (find-buffer-visiting file)
11771 (find-file-noselect file))
11772 (save-excursion
11773 (save-restriction
11774 (widen)
11775 (if pos
11776 (goto-char pos)
11777 (goto-char (point-max))
11778 (if (not (bolp)) (newline)))
11779 (when (looking-at org-outline-regexp)
11780 (setq level (funcall outline-level))
11781 (org-end-of-subtree t t))
11782 (org-back-over-empty-lines)
11783 (insert "\n" (make-string
11784 (if pos (org-get-valid-level level 1) 1) ?*)
11785 " " child "\n")
11786 (beginning-of-line 0)
11787 (list (concat (car parent-target) "/" child) file "" (point)))))))
11789 (defun org-olpath-completing-read (prompt collection &rest args)
11790 "Read an outline path like a file name."
11791 (let ((thetable collection)
11792 (org-completion-use-ido nil) ; does not work with ido.
11793 (org-completion-use-iswitchb nil)) ; or iswitchb
11794 (apply
11795 'org-icompleting-read prompt
11796 (lambda (string predicate &optional flag)
11797 (let (rtn r f (l (length string)))
11798 (cond
11799 ((eq flag nil)
11800 ;; try completion
11801 (try-completion string thetable))
11802 ((eq flag t)
11803 ;; all-completions
11804 (setq rtn (all-completions string thetable predicate))
11805 (mapcar
11806 (lambda (x)
11807 (setq r (substring x l))
11808 (if (string-match " ([^)]*)$" x)
11809 (setq f (match-string 0 x))
11810 (setq f ""))
11811 (if (string-match "/" r)
11812 (concat string (substring r 0 (match-end 0)) f)
11814 rtn))
11815 ((eq flag 'lambda)
11816 ;; exact match?
11817 (assoc string thetable)))))
11818 args)))
11820 ;;;; Dynamic blocks
11822 (defun org-find-dblock (name)
11823 "Find the first dynamic block with name NAME in the buffer.
11824 If not found, stay at current position and return nil."
11825 (let ((case-fold-search t) pos)
11826 (save-excursion
11827 (goto-char (point-min))
11828 (setq pos (and (re-search-forward
11829 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11830 (match-beginning 0))))
11831 (if pos (goto-char pos))
11832 pos))
11834 (defconst org-dblock-start-re
11835 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11836 "Matches the start line of a dynamic block, with parameters.")
11838 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11839 "Matches the end of a dynamic block.")
11841 (defun org-create-dblock (plist)
11842 "Create a dynamic block section, with parameters taken from PLIST.
11843 PLIST must contain a :name entry which is used as name of the block."
11844 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11845 (end-of-line 1)
11846 (newline))
11847 (let ((col (current-column))
11848 (name (plist-get plist :name)))
11849 (insert "#+BEGIN: " name)
11850 (while plist
11851 (if (eq (car plist) :name)
11852 (setq plist (cddr plist))
11853 (insert " " (prin1-to-string (pop plist)))))
11854 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11855 (beginning-of-line -2)))
11857 (defun org-prepare-dblock ()
11858 "Prepare dynamic block for refresh.
11859 This empties the block, puts the cursor at the insert position and returns
11860 the property list including an extra property :name with the block name."
11861 (unless (looking-at org-dblock-start-re)
11862 (user-error "Not at a dynamic block"))
11863 (let* ((begdel (1+ (match-end 0)))
11864 (name (org-no-properties (match-string 1)))
11865 (params (append (list :name name)
11866 (read (concat "(" (match-string 3) ")")))))
11867 (save-excursion
11868 (beginning-of-line 1)
11869 (skip-chars-forward " \t")
11870 (setq params (plist-put params :indentation-column (current-column))))
11871 (unless (re-search-forward org-dblock-end-re nil t)
11872 (error "Dynamic block not terminated"))
11873 (setq params
11874 (append params
11875 (list :content (buffer-substring
11876 begdel (match-beginning 0)))))
11877 (delete-region begdel (match-beginning 0))
11878 (goto-char begdel)
11879 (open-line 1)
11880 params))
11882 (defun org-map-dblocks (&optional command)
11883 "Apply COMMAND to all dynamic blocks in the current buffer.
11884 If COMMAND is not given, use `org-update-dblock'."
11885 (let ((cmd (or command 'org-update-dblock)))
11886 (save-excursion
11887 (goto-char (point-min))
11888 (while (re-search-forward org-dblock-start-re nil t)
11889 (goto-char (match-beginning 0))
11890 (save-excursion
11891 (condition-case nil
11892 (funcall cmd)
11893 (error (message "Error during update of dynamic block"))))
11894 (unless (re-search-forward org-dblock-end-re nil t)
11895 (error "Dynamic block not terminated"))))))
11897 (defun org-dblock-update (&optional arg)
11898 "User command for updating dynamic blocks.
11899 Update the dynamic block at point. With prefix ARG, update all dynamic
11900 blocks in the buffer."
11901 (interactive "P")
11902 (if arg
11903 (org-update-all-dblocks)
11904 (or (looking-at org-dblock-start-re)
11905 (org-beginning-of-dblock))
11906 (org-update-dblock)))
11908 (defun org-update-dblock ()
11909 "Update the dynamic block at point.
11910 This means to empty the block, parse for parameters and then call
11911 the correct writing function."
11912 (interactive)
11913 (save-window-excursion
11914 (let* ((pos (point))
11915 (line (org-current-line))
11916 (params (org-prepare-dblock))
11917 (name (plist-get params :name))
11918 (indent (plist-get params :indentation-column))
11919 (cmd (intern (concat "org-dblock-write:" name))))
11920 (message "Updating dynamic block `%s' at line %d..." name line)
11921 (funcall cmd params)
11922 (message "Updating dynamic block `%s' at line %d...done" name line)
11923 (goto-char pos)
11924 (when (and indent (> indent 0))
11925 (setq indent (make-string indent ?\ ))
11926 (save-excursion
11927 (org-beginning-of-dblock)
11928 (forward-line 1)
11929 (while (not (looking-at org-dblock-end-re))
11930 (insert indent)
11931 (beginning-of-line 2))
11932 (when (looking-at org-dblock-end-re)
11933 (and (looking-at "[ \t]+")
11934 (replace-match ""))
11935 (insert indent)))))))
11937 (defun org-beginning-of-dblock ()
11938 "Find the beginning of the dynamic block at point.
11939 Error if there is no such block at point."
11940 (let ((pos (point))
11941 beg)
11942 (end-of-line 1)
11943 (if (and (re-search-backward org-dblock-start-re nil t)
11944 (setq beg (match-beginning 0))
11945 (re-search-forward org-dblock-end-re nil t)
11946 (> (match-end 0) pos))
11947 (goto-char beg)
11948 (goto-char pos)
11949 (error "Not in a dynamic block"))))
11951 (defun org-update-all-dblocks ()
11952 "Update all dynamic blocks in the buffer.
11953 This function can be used in a hook."
11954 (interactive)
11955 (when (derived-mode-p 'org-mode)
11956 (org-map-dblocks 'org-update-dblock)))
11959 ;;;; Completion
11961 (declare-function org-export-backend-name "org-export" (cl-x))
11962 (declare-function org-export-backend-options "org-export" (cl-x))
11963 (defun org-get-export-keywords ()
11964 "Return a list of all currently understood export keywords.
11965 Export keywords include options, block names, attributes and
11966 keywords relative to each registered export back-end."
11967 (let (keywords)
11968 (dolist (backend
11969 (org-bound-and-true-p org-export--registered-backends)
11970 (delq nil keywords))
11971 ;; Back-end name (for keywords, like #+LATEX:)
11972 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
11973 (dolist (option-entry (org-export-backend-options backend))
11974 ;; Back-end options.
11975 (push (nth 1 option-entry) keywords)))))
11977 (defconst org-options-keywords
11978 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11979 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11980 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11981 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11982 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11984 (defcustom org-structure-template-alist
11985 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC" "<src lang=\"?\">\n\n</src>")
11986 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE" "<example>\n?\n</example>")
11987 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE" "<quote>\n?\n</quote>")
11988 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE" "<verse>\n?\n</verse>")
11989 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM" "<verbatim>\n?\n</verbatim>")
11990 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER" "<center>\n?\n</center>")
11991 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11992 "<literal style=\"latex\">\n?\n</literal>")
11993 ("L" "#+LaTeX: " "<literal style=\"latex\">?</literal>")
11994 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11995 "<literal style=\"html\">\n?\n</literal>")
11996 ("H" "#+HTML: " "<literal style=\"html\">?</literal>")
11997 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII" "")
11998 ("A" "#+ASCII: " "")
11999 ("i" "#+INDEX: ?" "#+INDEX: ?")
12000 ("I" "#+INCLUDE: %file ?"
12001 "<include file=%file markup=\"?\">"))
12002 "Structure completion elements.
12003 This is a list of abbreviation keys and values. The value gets inserted
12004 if you type `<' followed by the key and then press the completion key,
12005 usually `M-TAB'. %file will be replaced by a file name after prompting
12006 for the file using completion. The cursor will be placed at the position
12007 of the `?` in the template.
12008 There are two templates for each key, the first uses the original Org syntax,
12009 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12010 the default when the /org-mtags.el/ module has been loaded. See also the
12011 variable `org-mtags-prefer-muse-templates'."
12012 :group 'org-completion
12013 :type '(repeat
12014 (list
12015 (string :tag "Key")
12016 (string :tag "Template")
12017 (string :tag "Muse Template"))))
12019 (defun org-try-structure-completion ()
12020 "Try to complete a structure template before point.
12021 This looks for strings like \"<e\" on an otherwise empty line and
12022 expands them."
12023 (let ((l (buffer-substring (point-at-bol) (point)))
12025 (when (and (looking-at "[ \t]*$")
12026 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12027 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12028 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12029 (match-beginning 1)) a)
12030 t)))
12032 (defun org-complete-expand-structure-template (start cell)
12033 "Expand a structure template."
12034 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
12035 (rpl (nth (if musep 2 1) cell))
12036 (ind ""))
12037 (delete-region start (point))
12038 (when (string-match "\\`#\\+" rpl)
12039 (cond
12040 ((bolp))
12041 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12042 (setq ind (buffer-substring (point-at-bol) (point))))
12043 (t (newline))))
12044 (setq start (point))
12045 (if (string-match "%file" rpl)
12046 (setq rpl (replace-match
12047 (concat
12048 "\""
12049 (save-match-data
12050 (abbreviate-file-name (read-file-name "Include file: ")))
12051 "\"")
12052 t t rpl)))
12053 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12054 (concat "\n" ind)))
12055 (insert rpl)
12056 (if (re-search-backward "\\?" start t) (delete-char 1))))
12058 ;;;; TODO, DEADLINE, Comments
12060 (defun org-toggle-comment ()
12061 "Change the COMMENT state of an entry."
12062 (interactive)
12063 (save-excursion
12064 (org-back-to-heading)
12065 (let (case-fold-search)
12066 (cond
12067 ((looking-at (format org-heading-keyword-regexp-format
12068 org-comment-string))
12069 (goto-char (match-end 1))
12070 (looking-at (concat " +" org-comment-string))
12071 (replace-match "" t t)
12072 (when (eolp) (insert " ")))
12073 ((looking-at org-outline-regexp)
12074 (goto-char (match-end 0))
12075 (insert org-comment-string " "))))))
12077 (defvar org-last-todo-state-is-todo nil
12078 "This is non-nil when the last TODO state change led to a TODO state.
12079 If the last change removed the TODO tag or switched to DONE, then
12080 this is nil.")
12082 (defvar org-setting-tags nil) ; dynamically skipped
12084 (defvar org-todo-setup-filter-hook nil
12085 "Hook for functions that pre-filter todo specs.
12086 Each function takes a todo spec and returns either nil or the spec
12087 transformed into canonical form." )
12089 (defvar org-todo-get-default-hook nil
12090 "Hook for functions that get a default item for todo.
12091 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12092 nil or a string to be used for the todo mark." )
12094 (defvar org-agenda-headline-snapshot-before-repeat)
12096 (defun org-current-effective-time ()
12097 "Return current time adjusted for `org-extend-today-until' variable."
12098 (let* ((ct (org-current-time))
12099 (dct (decode-time ct))
12100 (ct1
12101 (cond
12102 (org-use-last-clock-out-time-as-effective-time
12103 (or (org-clock-get-last-clock-out-time) ct))
12104 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12105 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12106 (t ct))))
12107 ct1))
12109 (defun org-todo-yesterday (&optional arg)
12110 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12111 (interactive "P")
12112 (if (eq major-mode 'org-agenda-mode)
12113 (apply 'org-agenda-todo-yesterday arg)
12114 (let* ((hour (third (decode-time
12115 (org-current-time))))
12116 (org-extend-today-until (1+ hour)))
12117 (org-todo arg))))
12119 (defvar org-block-entry-blocking ""
12120 "First entry preventing the TODO state change.")
12122 (defun org-todo (&optional arg)
12123 "Change the TODO state of an item.
12124 The state of an item is given by a keyword at the start of the heading,
12125 like
12126 *** TODO Write paper
12127 *** DONE Call mom
12129 The different keywords are specified in the variable `org-todo-keywords'.
12130 By default the available states are \"TODO\" and \"DONE\".
12131 So for this example: when the item starts with TODO, it is changed to DONE.
12132 When it starts with DONE, the DONE is removed. And when neither TODO nor
12133 DONE are present, add TODO at the beginning of the heading.
12135 With \\[universal-argument] prefix arg, use completion to determine the new \
12136 state.
12137 With numeric prefix arg, switch to that state.
12138 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12139 keywords (nextset).
12140 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12141 With a numeric prefix arg of 0, inhibit note taking for the change.
12143 For calling through lisp, arg is also interpreted in the following way:
12144 'none -> empty state
12145 \"\"(empty string) -> switch to empty state
12146 'done -> switch to DONE
12147 'nextset -> switch to the next set of keywords
12148 'previousset -> switch to the previous set of keywords
12149 \"WAITING\" -> switch to the specified keyword, but only if it
12150 really is a member of `org-todo-keywords'."
12151 (interactive "P")
12152 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12153 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12154 'region-start-level 'region))
12155 org-loop-over-headlines-in-active-region)
12156 (org-map-entries
12157 `(org-todo ,arg)
12158 org-loop-over-headlines-in-active-region
12159 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12160 (if (equal arg '(16)) (setq arg 'nextset))
12161 (let ((org-blocker-hook org-blocker-hook)
12162 commentp
12163 case-fold-search)
12164 (when (equal arg '(64))
12165 (setq arg nil org-blocker-hook nil))
12166 (when (and org-blocker-hook
12167 (or org-inhibit-blocking
12168 (org-entry-get nil "NOBLOCKING")))
12169 (setq org-blocker-hook nil))
12170 (save-excursion
12171 (catch 'exit
12172 (org-back-to-heading t)
12173 (when (looking-at (concat "^\\*+ " org-comment-string))
12174 (org-toggle-comment)
12175 (setq commentp t))
12176 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12177 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12178 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12179 (let* ((match-data (match-data))
12180 (startpos (point-at-bol))
12181 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12182 (org-log-done org-log-done)
12183 (org-log-repeat org-log-repeat)
12184 (org-todo-log-states org-todo-log-states)
12185 (org-inhibit-logging
12186 (if (equal arg 0)
12187 (progn (setq arg nil) 'note) org-inhibit-logging))
12188 (this (match-string 1))
12189 (hl-pos (match-beginning 0))
12190 (head (org-get-todo-sequence-head this))
12191 (ass (assoc head org-todo-kwd-alist))
12192 (interpret (nth 1 ass))
12193 (done-word (nth 3 ass))
12194 (final-done-word (nth 4 ass))
12195 (org-last-state (or this ""))
12196 (completion-ignore-case t)
12197 (member (member this org-todo-keywords-1))
12198 (tail (cdr member))
12199 (org-state (cond
12200 ((and org-todo-key-trigger
12201 (or (and (equal arg '(4))
12202 (eq org-use-fast-todo-selection 'prefix))
12203 (and (not arg) org-use-fast-todo-selection
12204 (not (eq org-use-fast-todo-selection
12205 'prefix)))))
12206 ;; Use fast selection
12207 (org-fast-todo-selection))
12208 ((and (equal arg '(4))
12209 (or (not org-use-fast-todo-selection)
12210 (not org-todo-key-trigger)))
12211 ;; Read a state with completion
12212 (org-icompleting-read
12213 "State: " (mapcar 'list org-todo-keywords-1)
12214 nil t))
12215 ((eq arg 'right)
12216 (if this
12217 (if tail (car tail) nil)
12218 (car org-todo-keywords-1)))
12219 ((eq arg 'left)
12220 (if (equal member org-todo-keywords-1)
12222 (if this
12223 (nth (- (length org-todo-keywords-1)
12224 (length tail) 2)
12225 org-todo-keywords-1)
12226 (org-last org-todo-keywords-1))))
12227 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12228 (setq arg nil))) ; hack to fall back to cycling
12229 (arg
12230 ;; user or caller requests a specific state
12231 (cond
12232 ((equal arg "") nil)
12233 ((eq arg 'none) nil)
12234 ((eq arg 'done) (or done-word (car org-done-keywords)))
12235 ((eq arg 'nextset)
12236 (or (car (cdr (member head org-todo-heads)))
12237 (car org-todo-heads)))
12238 ((eq arg 'previousset)
12239 (let ((org-todo-heads (reverse org-todo-heads)))
12240 (or (car (cdr (member head org-todo-heads)))
12241 (car org-todo-heads))))
12242 ((car (member arg org-todo-keywords-1)))
12243 ((stringp arg)
12244 (user-error "State `%s' not valid in this file" arg))
12245 ((nth (1- (prefix-numeric-value arg))
12246 org-todo-keywords-1))))
12247 ((null member) (or head (car org-todo-keywords-1)))
12248 ((equal this final-done-word) nil) ;; -> make empty
12249 ((null tail) nil) ;; -> first entry
12250 ((memq interpret '(type priority))
12251 (if (eq this-command last-command)
12252 (car tail)
12253 (if (> (length tail) 0)
12254 (or done-word (car org-done-keywords))
12255 nil)))
12257 (car tail))))
12258 (org-state (or
12259 (run-hook-with-args-until-success
12260 'org-todo-get-default-hook org-state org-last-state)
12261 org-state))
12262 (next (if org-state (concat " " org-state " ") " "))
12263 (change-plist (list :type 'todo-state-change :from this :to org-state
12264 :position startpos))
12265 dolog now-done-p)
12266 (when org-blocker-hook
12267 (setq org-last-todo-state-is-todo
12268 (not (member this org-done-keywords)))
12269 (unless (save-excursion
12270 (save-match-data
12271 (org-with-wide-buffer
12272 (run-hook-with-args-until-failure
12273 'org-blocker-hook change-plist))))
12274 (if (org-called-interactively-p 'interactive)
12275 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12276 this org-state org-block-entry-blocking)
12277 ;; fail silently
12278 (message "TODO state change from %s to %s blocked (by \"%s\")"
12279 this org-state org-block-entry-blocking)
12280 (throw 'exit nil))))
12281 (store-match-data match-data)
12282 (replace-match next t t)
12283 (unless (pos-visible-in-window-p hl-pos)
12284 (message "TODO state changed to %s" (org-trim next)))
12285 (unless head
12286 (setq head (org-get-todo-sequence-head org-state)
12287 ass (assoc head org-todo-kwd-alist)
12288 interpret (nth 1 ass)
12289 done-word (nth 3 ass)
12290 final-done-word (nth 4 ass)))
12291 (when (memq arg '(nextset previousset))
12292 (message "Keyword-Set %d/%d: %s"
12293 (- (length org-todo-sets) -1
12294 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12295 (length org-todo-sets)
12296 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12297 (setq org-last-todo-state-is-todo
12298 (not (member org-state org-done-keywords)))
12299 (setq now-done-p (and (member org-state org-done-keywords)
12300 (not (member this org-done-keywords))))
12301 (and logging (org-local-logging logging))
12302 (when (and (or org-todo-log-states org-log-done)
12303 (not (eq org-inhibit-logging t))
12304 (not (memq arg '(nextset previousset))))
12305 ;; we need to look at recording a time and note
12306 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12307 (nth 2 (assoc this org-todo-log-states))))
12308 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12309 (setq dolog 'time))
12310 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12311 (and org-state
12312 (member org-state org-not-done-keywords)
12313 (not (member this org-not-done-keywords))))
12314 ;; This is now a todo state and was not one before
12315 ;; If there was a CLOSED time stamp, get rid of it.
12316 (org-add-planning-info nil nil 'closed))
12317 (when (and now-done-p org-log-done)
12318 ;; It is now done, and it was not done before
12319 (org-add-planning-info 'closed (org-current-effective-time))
12320 (if (and (not dolog) (eq 'note org-log-done))
12321 (org-add-log-setup 'done org-state this 'findpos 'note)))
12322 (when (and org-state dolog)
12323 ;; This is a non-nil state, and we need to log it
12324 (org-add-log-setup 'state org-state this 'findpos dolog)))
12325 ;; Fixup tag positioning
12326 (org-todo-trigger-tag-changes org-state)
12327 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12328 (when org-provide-todo-statistics
12329 (org-update-parent-todo-statistics))
12330 (run-hooks 'org-after-todo-state-change-hook)
12331 (if (and arg (not (member org-state org-done-keywords)))
12332 (setq head (org-get-todo-sequence-head org-state)))
12333 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12334 ;; Do we need to trigger a repeat?
12335 (when now-done-p
12336 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12337 ;; This is for the agenda, take a snapshot of the headline.
12338 (save-match-data
12339 (setq org-agenda-headline-snapshot-before-repeat
12340 (org-get-heading))))
12341 (org-auto-repeat-maybe org-state))
12342 ;; Fixup cursor location if close to the keyword
12343 (if (and (outline-on-heading-p)
12344 (not (bolp))
12345 (save-excursion (beginning-of-line 1)
12346 (looking-at org-todo-line-regexp))
12347 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12348 (progn
12349 (goto-char (or (match-end 2) (match-end 1)))
12350 (and (looking-at " ") (just-one-space))))
12351 (when org-trigger-hook
12352 (save-excursion
12353 (run-hook-with-args 'org-trigger-hook change-plist)))
12354 (when commentp (org-toggle-comment))))))))
12356 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12357 "Block turning an entry into a TODO, using the hierarchy.
12358 This checks whether the current task should be blocked from state
12359 changes. Such blocking occurs when:
12361 1. The task has children which are not all in a completed state.
12363 2. A task has a parent with the property :ORDERED:, and there
12364 are siblings prior to the current task with incomplete
12365 status.
12367 3. The parent of the task is blocked because it has siblings that should
12368 be done first, or is child of a block grandparent TODO entry."
12370 (if (not org-enforce-todo-dependencies)
12371 t ; if locally turned off don't block
12372 (catch 'dont-block
12373 ;; If this is not a todo state change, or if this entry is already DONE,
12374 ;; do not block
12375 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12376 (member (plist-get change-plist :from)
12377 (cons 'done org-done-keywords))
12378 (member (plist-get change-plist :to)
12379 (cons 'todo org-not-done-keywords))
12380 (not (plist-get change-plist :to)))
12381 (throw 'dont-block t))
12382 ;; If this task has children, and any are undone, it's blocked
12383 (save-excursion
12384 (org-back-to-heading t)
12385 (let ((this-level (funcall outline-level)))
12386 (outline-next-heading)
12387 (let ((child-level (funcall outline-level)))
12388 (while (and (not (eobp))
12389 (> child-level this-level))
12390 ;; this todo has children, check whether they are all
12391 ;; completed
12392 (if (and (not (org-entry-is-done-p))
12393 (org-entry-is-todo-p))
12394 (progn (setq org-block-entry-blocking (org-get-heading))
12395 (throw 'dont-block nil)))
12396 (outline-next-heading)
12397 (setq child-level (funcall outline-level))))))
12398 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12399 ;; any previous siblings are undone, it's blocked
12400 (save-excursion
12401 (org-back-to-heading t)
12402 (let* ((pos (point))
12403 (parent-pos (and (org-up-heading-safe) (point))))
12404 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12405 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12406 (forward-line 1)
12407 (re-search-forward org-not-done-heading-regexp pos t))
12408 (setq org-block-entry-blocking (match-string 0))
12409 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12410 ;; Search further up the hierarchy, to see if an ancestor is blocked
12411 (while t
12412 (goto-char parent-pos)
12413 (if (not (looking-at org-not-done-heading-regexp))
12414 (throw 'dont-block t)) ; do not block, parent is not a TODO
12415 (setq pos (point))
12416 (setq parent-pos (and (org-up-heading-safe) (point)))
12417 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12418 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12419 (forward-line 1)
12420 (re-search-forward org-not-done-heading-regexp pos t)
12421 (setq org-block-entry-blocking (org-get-heading)))
12422 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12424 (defcustom org-track-ordered-property-with-tag nil
12425 "Should the ORDERED property also be shown as a tag?
12426 The ORDERED property decides if an entry should require subtasks to be
12427 completed in sequence. Since a property is not very visible, setting
12428 this option means that toggling the ORDERED property with the command
12429 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12430 not relevant for the behavior, but it makes things more visible.
12432 Note that toggling the tag with tags commands will not change the property
12433 and therefore not influence behavior!
12435 This can be t, meaning the tag ORDERED should be used, It can also be a
12436 string to select a different tag for this task."
12437 :group 'org-todo
12438 :type '(choice
12439 (const :tag "No tracking" nil)
12440 (const :tag "Track with ORDERED tag" t)
12441 (string :tag "Use other tag")))
12443 (defun org-toggle-ordered-property ()
12444 "Toggle the ORDERED property of the current entry.
12445 For better visibility, you can track the value of this property with a tag.
12446 See variable `org-track-ordered-property-with-tag'."
12447 (interactive)
12448 (let* ((t1 org-track-ordered-property-with-tag)
12449 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12450 (save-excursion
12451 (org-back-to-heading)
12452 (if (org-entry-get nil "ORDERED")
12453 (progn
12454 (org-delete-property "ORDERED" "PROPERTIES")
12455 (and tag (org-toggle-tag tag 'off))
12456 (message "Subtasks can be completed in arbitrary order"))
12457 (org-entry-put nil "ORDERED" "t")
12458 (and tag (org-toggle-tag tag 'on))
12459 (message "Subtasks must be completed in sequence")))))
12461 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12462 (defun org-block-todo-from-checkboxes (change-plist)
12463 "Block turning an entry into a TODO, using checkboxes.
12464 This checks whether the current task should be blocked from state
12465 changes because there are unchecked boxes in this entry."
12466 (if (not org-enforce-todo-checkbox-dependencies)
12467 t ; if locally turned off don't block
12468 (catch 'dont-block
12469 ;; If this is not a todo state change, or if this entry is already DONE,
12470 ;; do not block
12471 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12472 (member (plist-get change-plist :from)
12473 (cons 'done org-done-keywords))
12474 (member (plist-get change-plist :to)
12475 (cons 'todo org-not-done-keywords))
12476 (not (plist-get change-plist :to)))
12477 (throw 'dont-block t))
12478 ;; If this task has checkboxes that are not checked, it's blocked
12479 (save-excursion
12480 (org-back-to-heading t)
12481 (let ((beg (point)) end)
12482 (outline-next-heading)
12483 (setq end (point))
12484 (goto-char beg)
12485 (if (org-list-search-forward
12486 (concat (org-item-beginning-re)
12487 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12488 "\\[[- ]\\]")
12489 end t)
12490 (progn
12491 (if (boundp 'org-blocked-by-checkboxes)
12492 (setq org-blocked-by-checkboxes t))
12493 (throw 'dont-block nil)))))
12494 t))) ; do not block
12496 (defun org-entry-blocked-p ()
12497 "Is the current entry blocked?"
12498 (org-with-silent-modifications
12499 (if (org-entry-get nil "NOBLOCKING")
12500 nil ;; Never block this entry
12501 (not (run-hook-with-args-until-failure
12502 'org-blocker-hook
12503 (list :type 'todo-state-change
12504 :position (point)
12505 :from 'todo
12506 :to 'done))))))
12508 (defun org-update-statistics-cookies (all)
12509 "Update the statistics cookie, either from TODO or from checkboxes.
12510 This should be called with the cursor in a line with a statistics cookie."
12511 (interactive "P")
12512 (if all
12513 (progn
12514 (org-update-checkbox-count 'all)
12515 (org-map-entries 'org-update-parent-todo-statistics))
12516 (if (not (org-at-heading-p))
12517 (org-update-checkbox-count)
12518 (let ((pos (point-marker))
12519 end l1 l2)
12520 (ignore-errors (org-back-to-heading t))
12521 (if (not (org-at-heading-p))
12522 (org-update-checkbox-count)
12523 (setq l1 (org-outline-level))
12524 (setq end (save-excursion
12525 (outline-next-heading)
12526 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12527 (point)))
12528 (if (and (save-excursion
12529 (re-search-forward
12530 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12531 (not (save-excursion (re-search-forward
12532 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12533 (org-update-checkbox-count)
12534 (if (and l2 (> l2 l1))
12535 (progn
12536 (goto-char end)
12537 (org-update-parent-todo-statistics))
12538 (goto-char pos)
12539 (beginning-of-line 1)
12540 (while (re-search-forward
12541 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12542 (point-at-eol) t)
12543 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12544 (goto-char pos)
12545 (move-marker pos nil)))))
12547 (defvar org-entry-property-inherited-from) ;; defined below
12548 (defun org-update-parent-todo-statistics ()
12549 "Update any statistics cookie in the parent of the current headline.
12550 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12551 the entire subtree and this will travel up the hierarchy and update
12552 statistics everywhere."
12553 (let* ((prop (save-excursion (org-up-heading-safe)
12554 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12555 (recursive (or (not org-hierarchical-todo-statistics)
12556 (and prop (string-match "\\<recursive\\>" prop))))
12557 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12559 (first t)
12560 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12561 level ltoggle l1 new ndel
12562 (cnt-all 0) (cnt-done 0) is-percent kwd
12563 checkbox-beg ov ovs ove cookie-present)
12564 (catch 'exit
12565 (save-excursion
12566 (beginning-of-line 1)
12567 (setq ltoggle (funcall outline-level))
12568 ;; Three situations are to consider:
12570 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12571 ;; to the top-level ancestor on the headline;
12573 ;; 2. If parent has "recursive" property, repeat up to the
12574 ;; headline setting that property, taking inheritance into
12575 ;; account;
12577 ;; 3. Else, move up to direct parent and proceed only once.
12578 (while (and (setq level (org-up-heading-safe))
12579 (or recursive first)
12580 (>= (point) lim))
12581 (setq first nil cookie-present nil)
12582 (unless (and level
12583 (not (string-match
12584 "\\<checkbox\\>"
12585 (downcase (or (org-entry-get nil "COOKIE_DATA")
12586 "")))))
12587 (throw 'exit nil))
12588 (while (re-search-forward box-re (point-at-eol) t)
12589 (setq cnt-all 0 cnt-done 0 cookie-present t)
12590 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12591 (save-match-data
12592 (unless (outline-next-heading) (throw 'exit nil))
12593 (while (and (looking-at org-complex-heading-regexp)
12594 (> (setq l1 (length (match-string 1))) level))
12595 (setq kwd (and (or recursive (= l1 ltoggle))
12596 (match-string 2)))
12597 (if (or (eq org-provide-todo-statistics 'all-headlines)
12598 (and (listp org-provide-todo-statistics)
12599 (or (member kwd org-provide-todo-statistics)
12600 (member kwd org-done-keywords))))
12601 (setq cnt-all (1+ cnt-all))
12602 (if (eq org-provide-todo-statistics t)
12603 (and kwd (setq cnt-all (1+ cnt-all)))))
12604 (and (member kwd org-done-keywords)
12605 (setq cnt-done (1+ cnt-done)))
12606 (outline-next-heading)))
12607 (setq new
12608 (if is-percent
12609 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12610 (format "[%d/%d]" cnt-done cnt-all))
12611 ndel (- (match-end 0) checkbox-beg))
12612 ;; handle overlays when updating cookie from column view
12613 (when (setq ov (car (overlays-at checkbox-beg)))
12614 (setq ovs (overlay-start ov) ove (overlay-end ov))
12615 (delete-overlay ov))
12616 (goto-char checkbox-beg)
12617 (insert new)
12618 (delete-region (point) (+ (point) ndel))
12619 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12620 (when ov (move-overlay ov ovs ove)))
12621 (when cookie-present
12622 (run-hook-with-args 'org-after-todo-statistics-hook
12623 cnt-done (- cnt-all cnt-done))))))
12624 (run-hooks 'org-todo-statistics-hook)))
12626 (defvar org-after-todo-statistics-hook nil
12627 "Hook that is called after a TODO statistics cookie has been updated.
12628 Each function is called with two arguments: the number of not-done entries
12629 and the number of done entries.
12631 For example, the following function, when added to this hook, will switch
12632 an entry to DONE when all children are done, and back to TODO when new
12633 entries are set to a TODO status. Note that this hook is only called
12634 when there is a statistics cookie in the headline!
12636 (defun org-summary-todo (n-done n-not-done)
12637 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12638 (let (org-log-done org-log-states) ; turn off logging
12639 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12642 (defvar org-todo-statistics-hook nil
12643 "Hook that is run whenever Org thinks TODO statistics should be updated.
12644 This hook runs even if there is no statistics cookie present, in which case
12645 `org-after-todo-statistics-hook' would not run.")
12647 (defun org-todo-trigger-tag-changes (state)
12648 "Apply the changes defined in `org-todo-state-tags-triggers'."
12649 (let ((l org-todo-state-tags-triggers)
12650 changes)
12651 (when (or (not state) (equal state ""))
12652 (setq changes (append changes (cdr (assoc "" l)))))
12653 (when (and (stringp state) (> (length state) 0))
12654 (setq changes (append changes (cdr (assoc state l)))))
12655 (when (member state org-not-done-keywords)
12656 (setq changes (append changes (cdr (assoc 'todo l)))))
12657 (when (member state org-done-keywords)
12658 (setq changes (append changes (cdr (assoc 'done l)))))
12659 (dolist (c changes)
12660 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12662 (defun org-local-logging (value)
12663 "Get logging settings from a property VALUE."
12664 (let* (words w a)
12665 ;; directly set the variables, they are already local.
12666 (setq org-log-done nil
12667 org-log-repeat nil
12668 org-todo-log-states nil)
12669 (setq words (org-split-string value))
12670 (while (setq w (pop words))
12671 (cond
12672 ((setq a (assoc w org-startup-options))
12673 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12674 (set (nth 1 a) (nth 2 a))))
12675 ((setq a (org-extract-log-state-settings w))
12676 (and (member (car a) org-todo-keywords-1)
12677 (push a org-todo-log-states)))))))
12679 (defun org-get-todo-sequence-head (kwd)
12680 "Return the head of the TODO sequence to which KWD belongs.
12681 If KWD is not set, check if there is a text property remembering the
12682 right sequence."
12683 (let (p)
12684 (cond
12685 ((not kwd)
12686 (or (get-text-property (point-at-bol) 'org-todo-head)
12687 (progn
12688 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12689 nil (point-at-eol)))
12690 (get-text-property p 'org-todo-head))))
12691 ((not (member kwd org-todo-keywords-1))
12692 (car org-todo-keywords-1))
12693 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12695 (defun org-fast-todo-selection ()
12696 "Fast TODO keyword selection with single keys.
12697 Returns the new TODO keyword, or nil if no state change should occur."
12698 (let* ((fulltable org-todo-key-alist)
12699 (done-keywords org-done-keywords) ;; needed for the faces.
12700 (maxlen (apply 'max (mapcar
12701 (lambda (x)
12702 (if (stringp (car x)) (string-width (car x)) 0))
12703 fulltable)))
12704 (expert nil)
12705 (fwidth (+ maxlen 3 1 3))
12706 (ncol (/ (- (window-width) 4) fwidth))
12707 tg cnt e c tbl
12708 groups ingroup)
12709 (save-excursion
12710 (save-window-excursion
12711 (if expert
12712 (set-buffer (get-buffer-create " *Org todo*"))
12713 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12714 (erase-buffer)
12715 (org-set-local 'org-done-keywords done-keywords)
12716 (setq tbl fulltable cnt 0)
12717 (while (setq e (pop tbl))
12718 (cond
12719 ((equal e '(:startgroup))
12720 (push '() groups) (setq ingroup t)
12721 (when (not (= cnt 0))
12722 (setq cnt 0)
12723 (insert "\n"))
12724 (insert "{ "))
12725 ((equal e '(:endgroup))
12726 (setq ingroup nil cnt 0)
12727 (insert "}\n"))
12728 ((equal e '(:newline))
12729 (when (not (= cnt 0))
12730 (setq cnt 0)
12731 (insert "\n")
12732 (setq e (car tbl))
12733 (while (equal (car tbl) '(:newline))
12734 (insert "\n")
12735 (setq tbl (cdr tbl)))))
12737 (setq tg (car e) c (cdr e))
12738 (if ingroup (push tg (car groups)))
12739 (setq tg (org-add-props tg nil 'face
12740 (org-get-todo-face tg)))
12741 (if (and (= cnt 0) (not ingroup)) (insert " "))
12742 (insert "[" c "] " tg (make-string
12743 (- fwidth 4 (length tg)) ?\ ))
12744 (when (= (setq cnt (1+ cnt)) ncol)
12745 (insert "\n")
12746 (if ingroup (insert " "))
12747 (setq cnt 0)))))
12748 (insert "\n")
12749 (goto-char (point-min))
12750 (if (not expert) (org-fit-window-to-buffer))
12751 (message "[a-z..]:Set [SPC]:clear")
12752 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12753 (cond
12754 ((or (= c ?\C-g)
12755 (and (= c ?q) (not (rassoc c fulltable))))
12756 (setq quit-flag t))
12757 ((= c ?\ ) nil)
12758 ((setq e (rassoc c fulltable) tg (car e))
12760 (t (setq quit-flag t)))))))
12762 (defun org-entry-is-todo-p ()
12763 (member (org-get-todo-state) org-not-done-keywords))
12765 (defun org-entry-is-done-p ()
12766 (member (org-get-todo-state) org-done-keywords))
12768 (defun org-get-todo-state ()
12769 "Return the TODO keyword of the current subtree."
12770 (save-excursion
12771 (org-back-to-heading t)
12772 (and (looking-at org-todo-line-regexp)
12773 (match-end 2)
12774 (match-string 2))))
12776 (defun org-at-date-range-p (&optional inactive-ok)
12777 "Is the cursor inside a date range?"
12778 (interactive)
12779 (save-excursion
12780 (catch 'exit
12781 (let ((pos (point)))
12782 (skip-chars-backward "^[<\r\n")
12783 (skip-chars-backward "<[")
12784 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12785 (>= (match-end 0) pos)
12786 (throw 'exit t))
12787 (skip-chars-backward "^<[\r\n")
12788 (skip-chars-backward "<[")
12789 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12790 (>= (match-end 0) pos)
12791 (throw 'exit t)))
12792 nil)))
12794 (defun org-get-repeat (&optional tagline)
12795 "Check if there is a deadline/schedule with repeater in this entry."
12796 (save-match-data
12797 (save-excursion
12798 (org-back-to-heading t)
12799 (and (re-search-forward (if tagline
12800 (concat tagline "\\s-*" org-repeat-re)
12801 org-repeat-re)
12802 (org-entry-end-position) t)
12803 (match-string-no-properties 1)))))
12805 (defvar org-last-changed-timestamp)
12806 (defvar org-last-inserted-timestamp)
12807 (defvar org-log-post-message)
12808 (defvar org-log-note-purpose)
12809 (defvar org-log-note-how)
12810 (defvar org-log-note-extra)
12811 (defun org-auto-repeat-maybe (done-word)
12812 "Check if the current headline contains a repeated deadline/schedule.
12813 If yes, set TODO state back to what it was and change the base date
12814 of repeating deadline/scheduled time stamps to new date.
12815 This function is run automatically after each state change to a DONE state."
12816 ;; last-state is dynamically scoped into this function
12817 (let* ((repeat (org-get-repeat))
12818 (aa (assoc org-last-state org-todo-kwd-alist))
12819 (interpret (nth 1 aa))
12820 (head (nth 2 aa))
12821 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12822 (msg "Entry repeats: ")
12823 (org-log-done nil)
12824 (org-todo-log-states nil)
12825 re type n what ts time to-state)
12826 (when repeat
12827 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12828 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12829 org-todo-repeat-to-state))
12830 (unless (and to-state (member to-state org-todo-keywords-1))
12831 (setq to-state (if (eq interpret 'type) org-last-state head)))
12832 (org-todo to-state)
12833 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12834 (org-entry-put nil "LAST_REPEAT" (format-time-string
12835 (org-time-stamp-format t t))))
12836 (when org-log-repeat
12837 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12838 (memq 'org-add-log-note post-command-hook))
12839 ;; OK, we are already setup for some record
12840 (if (eq org-log-repeat 'note)
12841 ;; make sure we take a note, not only a time stamp
12842 (setq org-log-note-how 'note))
12843 ;; Set up for taking a record
12844 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12845 org-last-state
12846 'findpos org-log-repeat)))
12847 (org-back-to-heading t)
12848 (org-add-planning-info nil nil 'closed)
12849 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12850 org-deadline-time-regexp "\\)\\|\\("
12851 org-ts-regexp "\\)"))
12852 (while (re-search-forward
12853 re (save-excursion (outline-next-heading) (point)) t)
12854 (setq type (if (match-end 1) org-scheduled-string
12855 (if (match-end 3) org-deadline-string "Plain:"))
12856 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12857 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12858 (setq n (string-to-number (match-string 2 ts))
12859 what (match-string 3 ts))
12860 (if (equal what "w") (setq n (* n 7) what "d"))
12861 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12862 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12863 ;; Preparation, see if we need to modify the start date for the change
12864 (when (match-end 1)
12865 (setq time (save-match-data (org-time-string-to-time ts)))
12866 (cond
12867 ((equal (match-string 1 ts) ".")
12868 ;; Shift starting date to today
12869 (org-timestamp-change
12870 (- (org-today) (time-to-days time))
12871 'day))
12872 ((equal (match-string 1 ts) "+")
12873 (let ((nshiftmax 10) (nshift 0))
12874 (while (or (= nshift 0)
12875 (<= (time-to-days time)
12876 (time-to-days (current-time))))
12877 (when (= (incf nshift) nshiftmax)
12878 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12879 (error "Abort")))
12880 (org-timestamp-change n (cdr (assoc what whata)))
12881 (org-at-timestamp-p t)
12882 (setq ts (match-string 1))
12883 (setq time (save-match-data (org-time-string-to-time ts)))))
12884 (org-timestamp-change (- n) (cdr (assoc what whata)))
12885 ;; rematch, so that we have everything in place for the real shift
12886 (org-at-timestamp-p t)
12887 (setq ts (match-string 1))
12888 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12889 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12890 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12891 (setq org-log-post-message msg)
12892 (message "%s" msg))))
12894 (defun org-show-todo-tree (arg)
12895 "Make a compact tree which shows all headlines marked with TODO.
12896 The tree will show the lines where the regexp matches, and all higher
12897 headlines above the match.
12898 With a \\[universal-argument] prefix, prompt for a regexp to match.
12899 With a numeric prefix N, construct a sparse tree for the Nth element
12900 of `org-todo-keywords-1'."
12901 (interactive "P")
12902 (let ((case-fold-search nil)
12903 (kwd-re
12904 (cond ((null arg) org-not-done-regexp)
12905 ((equal arg '(4))
12906 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12907 (mapcar 'list org-todo-keywords-1))))
12908 (concat "\\("
12909 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12910 "\\)\\>")))
12911 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12912 (regexp-quote (nth (1- (prefix-numeric-value arg))
12913 org-todo-keywords-1)))
12914 (t (user-error "Invalid prefix argument: %s" arg)))))
12915 (message "%d TODO entries found"
12916 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12918 (defun org-deadline (arg &optional time)
12919 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12920 With one universal prefix argument, remove any deadline from the item.
12921 With two universal prefix arguments, prompt for a warning delay.
12922 With argument TIME, set the deadline at the corresponding date. TIME
12923 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12924 (interactive "P")
12925 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12926 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12927 'region-start-level 'region))
12928 org-loop-over-headlines-in-active-region)
12929 (org-map-entries
12930 `(org-deadline ',arg ,time)
12931 org-loop-over-headlines-in-active-region
12932 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12933 (let* ((old-date (org-entry-get nil "DEADLINE"))
12934 (old-date-time (if old-date (org-time-string-to-time old-date)))
12935 (repeater (and old-date
12936 (string-match
12937 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12938 old-date)
12939 (match-string 1 old-date))))
12940 (cond
12941 ((equal arg '(4))
12942 (when (and old-date org-log-redeadline)
12943 (org-add-log-setup 'deldeadline nil old-date 'findpos
12944 org-log-redeadline))
12945 (org-remove-timestamp-with-keyword org-deadline-string)
12946 (message "Item no longer has a deadline."))
12947 ((equal arg '(16))
12948 (save-excursion
12949 (if (re-search-forward
12950 org-deadline-time-regexp
12951 (save-excursion (outline-next-heading) (point)) t)
12952 (let* ((rpl0 (match-string 1))
12953 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12954 (replace-match
12955 (concat org-deadline-string
12956 " <" rpl
12957 (format " -%dd"
12958 (abs
12959 (- (time-to-days
12960 (save-match-data
12961 (org-read-date nil t nil "Warn starting from" old-date-time)))
12962 (time-to-days old-date-time))))
12963 ">") t t))
12964 (user-error "No deadline information to update"))))
12966 (org-add-planning-info 'deadline time 'closed)
12967 (when (and old-date org-log-redeadline
12968 (not (equal old-date
12969 (substring org-last-inserted-timestamp 1 -1))))
12970 (org-add-log-setup 'redeadline nil old-date 'findpos
12971 org-log-redeadline))
12972 (when repeater
12973 (save-excursion
12974 (org-back-to-heading t)
12975 (when (re-search-forward (concat org-deadline-string " "
12976 org-last-inserted-timestamp)
12977 (save-excursion
12978 (outline-next-heading) (point)) t)
12979 (goto-char (1- (match-end 0)))
12980 (insert " " repeater)
12981 (setq org-last-inserted-timestamp
12982 (concat (substring org-last-inserted-timestamp 0 -1)
12983 " " repeater
12984 (substring org-last-inserted-timestamp -1))))))
12985 (message "Deadline on %s" org-last-inserted-timestamp))))))
12987 (defun org-schedule (arg &optional time)
12988 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12989 With one universal prefix argument, remove any scheduling date from the item.
12990 With two universal prefix arguments, prompt for a delay cookie.
12991 With argument TIME, scheduled at the corresponding date. TIME can
12992 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12993 (interactive "P")
12994 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12995 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12996 'region-start-level 'region))
12997 org-loop-over-headlines-in-active-region)
12998 (org-map-entries
12999 `(org-schedule ',arg ,time)
13000 org-loop-over-headlines-in-active-region
13001 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13002 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13003 (old-date-time (if old-date (org-time-string-to-time old-date)))
13004 (repeater (and old-date
13005 (string-match
13006 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13007 old-date)
13008 (match-string 1 old-date))))
13009 (cond
13010 ((equal arg '(4))
13011 (progn
13012 (when (and old-date org-log-reschedule)
13013 (org-add-log-setup 'delschedule nil old-date 'findpos
13014 org-log-reschedule))
13015 (org-remove-timestamp-with-keyword org-scheduled-string)
13016 (message "Item is no longer scheduled.")))
13017 ((equal arg '(16))
13018 (save-excursion
13019 (if (re-search-forward
13020 org-scheduled-time-regexp
13021 (save-excursion (outline-next-heading) (point)) t)
13022 (let* ((rpl0 (match-string 1))
13023 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13024 (replace-match
13025 (concat org-scheduled-string
13026 " <" rpl
13027 (format " -%dd"
13028 (abs
13029 (- (time-to-days
13030 (save-match-data
13031 (org-read-date nil t nil "Delay until" old-date-time)))
13032 (time-to-days old-date-time))))
13033 ">") t t))
13034 (user-error "No scheduled information to update"))))
13036 (org-add-planning-info 'scheduled time 'closed)
13037 (when (and old-date org-log-reschedule
13038 (not (equal old-date
13039 (substring org-last-inserted-timestamp 1 -1))))
13040 (org-add-log-setup 'reschedule nil old-date 'findpos
13041 org-log-reschedule))
13042 (when repeater
13043 (save-excursion
13044 (org-back-to-heading t)
13045 (when (re-search-forward (concat org-scheduled-string " "
13046 org-last-inserted-timestamp)
13047 (save-excursion
13048 (outline-next-heading) (point)) t)
13049 (goto-char (1- (match-end 0)))
13050 (insert " " repeater)
13051 (setq org-last-inserted-timestamp
13052 (concat (substring org-last-inserted-timestamp 0 -1)
13053 " " repeater
13054 (substring org-last-inserted-timestamp -1))))))
13055 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13057 (defun org-get-scheduled-time (pom &optional inherit)
13058 "Get the scheduled time as a time tuple, of a format suitable
13059 for calling org-schedule with, or if there is no scheduling,
13060 returns nil."
13061 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13062 (when time
13063 (apply 'encode-time (org-parse-time-string time)))))
13065 (defun org-get-deadline-time (pom &optional inherit)
13066 "Get the deadline as a time tuple, of a format suitable for
13067 calling org-deadline with, or if there is no scheduling, returns
13068 nil."
13069 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13070 (when time
13071 (apply 'encode-time (org-parse-time-string time)))))
13073 (defun org-remove-timestamp-with-keyword (keyword)
13074 "Remove all time stamps with KEYWORD in the current entry."
13075 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13076 beg)
13077 (save-excursion
13078 (org-back-to-heading t)
13079 (setq beg (point))
13080 (outline-next-heading)
13081 (while (re-search-backward re beg t)
13082 (replace-match "")
13083 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13084 (equal (char-before) ?\ ))
13085 (backward-delete-char 1)
13086 (if (string-match "^[ \t]*$" (buffer-substring
13087 (point-at-bol) (point-at-eol)))
13088 (delete-region (point-at-bol)
13089 (min (point-max) (1+ (point-at-eol))))))))))
13091 (defun org-add-planning-info (what &optional time &rest remove)
13092 "Insert new timestamp with keyword in the line directly after the headline.
13093 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13094 If non is given, the user is prompted for a date.
13095 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13096 be removed."
13097 (interactive)
13098 (let (org-time-was-given org-end-time-was-given ts
13099 end default-time default-input)
13101 (catch 'exit
13102 (when (and (memq what '(scheduled deadline))
13103 (or (not time)
13104 (and (stringp time)
13105 (string-match "^[-+]+[0-9]" time))))
13106 ;; Try to get a default date/time from existing timestamp
13107 (save-excursion
13108 (org-back-to-heading t)
13109 (setq end (save-excursion (outline-next-heading) (point)))
13110 (when (re-search-forward (if (eq what 'scheduled)
13111 org-scheduled-time-regexp
13112 org-deadline-time-regexp)
13113 end t)
13114 (setq ts (match-string 1)
13115 default-time
13116 (apply 'encode-time (org-parse-time-string ts))
13117 default-input (and ts (org-get-compact-tod ts))))))
13118 (when what
13119 (setq time
13120 (if (stringp time)
13121 ;; This is a string (relative or absolute), set proper date
13122 (apply 'encode-time
13123 (org-read-date-analyze
13124 time default-time (decode-time default-time)))
13125 ;; If necessary, get the time from the user
13126 (or time (org-read-date nil 'to-time nil nil
13127 default-time default-input)))))
13129 (when (and org-insert-labeled-timestamps-at-point
13130 (member what '(scheduled deadline)))
13131 (insert
13132 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13133 (org-insert-time-stamp time org-time-was-given
13134 nil nil nil (list org-end-time-was-given))
13135 (setq what nil))
13136 (save-excursion
13137 (save-restriction
13138 (let (col list elt ts buffer-invisibility-spec)
13139 (org-back-to-heading t)
13140 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13141 (goto-char (match-end 1))
13142 (setq col (current-column))
13143 (goto-char (match-end 0))
13144 (if (eobp) (insert "\n") (forward-char 1))
13145 (when (and (not what)
13146 (not (looking-at
13147 (concat "[ \t]*"
13148 org-keyword-time-not-clock-regexp))))
13149 ;; Nothing to add, nothing to remove...... :-)
13150 (throw 'exit nil))
13151 (if (and (not (looking-at org-outline-regexp))
13152 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13153 "[^\r\n]*"))
13154 (not (equal (match-string 1) org-clock-string)))
13155 (narrow-to-region (match-beginning 0) (match-end 0))
13156 (insert-before-markers "\n")
13157 (backward-char 1)
13158 (narrow-to-region (point) (point))
13159 (and org-adapt-indentation (org-indent-to-column col)))
13160 ;; Check if we have to remove something.
13161 (setq list (cons what remove))
13162 (while list
13163 (setq elt (pop list))
13164 (when (or (and (eq elt 'scheduled)
13165 (re-search-forward org-scheduled-time-regexp nil t))
13166 (and (eq elt 'deadline)
13167 (re-search-forward org-deadline-time-regexp nil t))
13168 (and (eq elt 'closed)
13169 (re-search-forward org-closed-time-regexp nil t)))
13170 (replace-match "")
13171 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13172 (and (looking-at "[ \t]+") (replace-match ""))
13173 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13174 (when what
13175 (insert
13176 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13177 (cond ((eq what 'scheduled) org-scheduled-string)
13178 ((eq what 'deadline) org-deadline-string)
13179 ((eq what 'closed) org-closed-string))
13180 " ")
13181 (setq ts (org-insert-time-stamp
13182 time
13183 (or org-time-was-given
13184 (and (eq what 'closed) org-log-done-with-time))
13185 (eq what 'closed)
13186 nil nil (list org-end-time-was-given)))
13187 (insert
13188 (if (not (or (bolp) (eq (char-before) ?\ )
13189 (memq (char-after) '(32 10))
13190 (eobp))) " " ""))
13191 (end-of-line 1))
13192 (goto-char (point-min))
13193 (widen)
13194 (if (and (looking-at "[ \t]*\n")
13195 (equal (char-before) ?\n))
13196 (delete-region (1- (point)) (point-at-eol)))
13197 ts))))))
13199 (defvar org-log-note-marker (make-marker))
13200 (defvar org-log-note-purpose nil)
13201 (defvar org-log-note-state nil)
13202 (defvar org-log-note-previous-state nil)
13203 (defvar org-log-note-how nil)
13204 (defvar org-log-note-extra nil)
13205 (defvar org-log-note-window-configuration nil)
13206 (defvar org-log-note-return-to (make-marker))
13207 (defvar org-log-note-effective-time nil
13208 "Remembered current time so that dynamically scoped
13209 `org-extend-today-until' affects tha timestamps in state change
13210 log")
13212 (defvar org-log-post-message nil
13213 "Message to be displayed after a log note has been stored.
13214 The auto-repeater uses this.")
13216 (defun org-add-note ()
13217 "Add a note to the current entry.
13218 This is done in the same way as adding a state change note."
13219 (interactive)
13220 (org-add-log-setup 'note nil nil 'findpos nil))
13222 (defvar org-property-end-re)
13223 (defun org-add-log-setup (&optional purpose state prev-state
13224 findpos how extra)
13225 "Set up the post command hook to take a note.
13226 If this is about to TODO state change, the new state is expected in STATE.
13227 When FINDPOS is non-nil, find the correct position for the note in
13228 the current entry. If not, assume that it can be inserted at point.
13229 HOW is an indicator what kind of note should be created.
13230 EXTRA is additional text that will be inserted into the notes buffer."
13231 (let* ((org-log-into-drawer (org-log-into-drawer))
13232 (drawer (cond ((stringp org-log-into-drawer)
13233 org-log-into-drawer)
13234 (org-log-into-drawer "LOGBOOK"))))
13235 (save-restriction
13236 (save-excursion
13237 (when findpos
13238 (org-back-to-heading t)
13239 (narrow-to-region (point) (save-excursion
13240 (outline-next-heading) (point)))
13241 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13242 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13243 "[^\r\n]*\\)?"))
13244 (goto-char (match-end 0))
13245 (cond
13246 (drawer
13247 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13248 nil t)
13249 (progn
13250 (goto-char (match-end 0))
13251 (or org-log-states-order-reversed
13252 (and (re-search-forward org-property-end-re nil t)
13253 (goto-char (1- (match-beginning 0))))))
13254 (insert "\n:" drawer ":\n:END:")
13255 (beginning-of-line 0)
13256 (org-indent-line)
13257 (beginning-of-line 2)
13258 (org-indent-line)
13259 (end-of-line 0)))
13260 ((and org-log-state-notes-insert-after-drawers
13261 (save-excursion
13262 (forward-line) (looking-at org-drawer-regexp)))
13263 (forward-line)
13264 (while (looking-at org-drawer-regexp)
13265 (goto-char (match-end 0))
13266 (re-search-forward org-property-end-re (point-max) t)
13267 (forward-line))
13268 (forward-line -1)))
13269 (unless org-log-states-order-reversed
13270 (and (= (char-after) ?\n) (forward-char 1))
13271 (org-skip-over-state-notes)
13272 (skip-chars-backward " \t\n\r")))
13273 (move-marker org-log-note-marker (point))
13274 (setq org-log-note-purpose purpose
13275 org-log-note-state state
13276 org-log-note-previous-state prev-state
13277 org-log-note-how how
13278 org-log-note-extra extra
13279 org-log-note-effective-time (org-current-effective-time))
13280 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13282 (defun org-skip-over-state-notes ()
13283 "Skip past the list of State notes in an entry."
13284 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13285 (when (ignore-errors (goto-char (org-in-item-p)))
13286 (let* ((struct (org-list-struct))
13287 (prevs (org-list-prevs-alist struct)))
13288 (while (looking-at "[ \t]*- State")
13289 (goto-char (or (org-list-get-next-item (point) struct prevs)
13290 (org-list-get-item-end (point) struct)))))))
13292 (defun org-add-log-note (&optional purpose)
13293 "Pop up a window for taking a note, and add this note later at point."
13294 (remove-hook 'post-command-hook 'org-add-log-note)
13295 (setq org-log-note-window-configuration (current-window-configuration))
13296 (delete-other-windows)
13297 (move-marker org-log-note-return-to (point))
13298 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13299 (goto-char org-log-note-marker)
13300 (org-switch-to-buffer-other-window "*Org Note*")
13301 (erase-buffer)
13302 (if (memq org-log-note-how '(time state))
13303 (let (current-prefix-arg) (org-store-log-note))
13304 (let ((org-inhibit-startup t)) (org-mode))
13305 (insert (format "# Insert note for %s.
13306 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13307 (cond
13308 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13309 ((eq org-log-note-purpose 'done) "closed todo item")
13310 ((eq org-log-note-purpose 'state)
13311 (format "state change from \"%s\" to \"%s\""
13312 (or org-log-note-previous-state "")
13313 (or org-log-note-state "")))
13314 ((eq org-log-note-purpose 'reschedule)
13315 "rescheduling")
13316 ((eq org-log-note-purpose 'delschedule)
13317 "no longer scheduled")
13318 ((eq org-log-note-purpose 'redeadline)
13319 "changing deadline")
13320 ((eq org-log-note-purpose 'deldeadline)
13321 "removing deadline")
13322 ((eq org-log-note-purpose 'refile)
13323 "refiling")
13324 ((eq org-log-note-purpose 'note)
13325 "this entry")
13326 (t (error "This should not happen")))))
13327 (if org-log-note-extra (insert org-log-note-extra))
13328 (org-set-local 'org-finish-function 'org-store-log-note)
13329 (run-hooks 'org-log-buffer-setup-hook)))
13331 (defvar org-note-abort nil) ; dynamically scoped
13332 (defun org-store-log-note ()
13333 "Finish taking a log note, and insert it to where it belongs."
13334 (let ((txt (buffer-string)))
13335 (kill-buffer (current-buffer))
13336 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13337 lines ind bul)
13338 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13339 (setq txt (replace-match "" t t txt)))
13340 (if (string-match "\\s-+\\'" txt)
13341 (setq txt (replace-match "" t t txt)))
13342 (setq lines (org-split-string txt "\n"))
13343 (when (and note (string-match "\\S-" note))
13344 (setq note
13345 (org-replace-escapes
13346 note
13347 (list (cons "%u" (user-login-name))
13348 (cons "%U" user-full-name)
13349 (cons "%t" (format-time-string
13350 (org-time-stamp-format 'long 'inactive)
13351 org-log-note-effective-time))
13352 (cons "%T" (format-time-string
13353 (org-time-stamp-format 'long nil)
13354 org-log-note-effective-time))
13355 (cons "%d" (format-time-string
13356 (org-time-stamp-format nil 'inactive)
13357 org-log-note-effective-time))
13358 (cons "%D" (format-time-string
13359 (org-time-stamp-format nil nil)
13360 org-log-note-effective-time))
13361 (cons "%s" (if org-log-note-state
13362 (concat "\"" org-log-note-state "\"")
13363 ""))
13364 (cons "%S" (if org-log-note-previous-state
13365 (concat "\"" org-log-note-previous-state "\"")
13366 "\"\"")))))
13367 (if lines (setq note (concat note " \\\\")))
13368 (push note lines))
13369 (when (or current-prefix-arg org-note-abort)
13370 (when org-log-into-drawer
13371 (org-remove-empty-drawer-at
13372 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
13373 org-log-note-marker))
13374 (setq lines nil))
13375 (when lines
13376 (with-current-buffer (marker-buffer org-log-note-marker)
13377 (save-excursion
13378 (goto-char org-log-note-marker)
13379 (move-marker org-log-note-marker nil)
13380 (end-of-line 1)
13381 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13382 (setq ind (save-excursion
13383 (if (ignore-errors (goto-char (org-in-item-p)))
13384 (let ((struct (org-list-struct)))
13385 (org-list-get-ind
13386 (org-list-get-top-point struct) struct))
13387 (skip-chars-backward " \r\t\n")
13388 (cond
13389 ((and (org-at-heading-p)
13390 org-adapt-indentation)
13391 (1+ (org-current-level)))
13392 ((org-at-heading-p) 0)
13393 (t (org-get-indentation))))))
13394 (setq bul (org-list-bullet-string "-"))
13395 (org-indent-line-to ind)
13396 (insert bul (pop lines))
13397 (let ((ind-body (+ (length bul) ind)))
13398 (while lines
13399 (insert "\n")
13400 (org-indent-line-to ind-body)
13401 (insert (pop lines))))
13402 (message "Note stored")
13403 (org-back-to-heading t)
13404 (org-cycle-hide-drawers 'children))
13405 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13406 ;; from within `org-add-log-note' because `buffer-undo-list'
13407 ;; is then modified outside of `org-with-remote-undo'.
13408 (when (eq this-command 'org-agenda-todo)
13409 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13410 ;; Don't add undo information when called from `org-agenda-todo'
13411 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13412 (set-window-configuration org-log-note-window-configuration)
13413 (with-current-buffer (marker-buffer org-log-note-return-to)
13414 (goto-char org-log-note-return-to))
13415 (move-marker org-log-note-return-to nil)
13416 (and org-log-post-message (message "%s" org-log-post-message))))
13418 (defun org-remove-empty-drawer-at (drawer pos)
13419 "Remove an empty drawer DRAWER at position POS.
13420 POS may also be a marker."
13421 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13422 (save-excursion
13423 (save-restriction
13424 (widen)
13425 (goto-char pos)
13426 (if (org-in-regexp
13427 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13428 (replace-match ""))))))
13430 (defvar org-ts-type nil)
13431 (defun org-sparse-tree (&optional arg type)
13432 "Create a sparse tree, prompt for the details.
13433 This command can create sparse trees. You first need to select the type
13434 of match used to create the tree:
13436 t Show all TODO entries.
13437 T Show entries with a specific TODO keyword.
13438 m Show entries selected by a tags/property match.
13439 p Enter a property name and its value (both with completion on existing
13440 names/values) and show entries with that property.
13441 r Show entries matching a regular expression (`/' can be used as well).
13442 b Show deadlines and scheduled items before a date.
13443 a Show deadlines and scheduled items after a date.
13444 d Show deadlines due within `org-deadline-warning-days'.
13445 D Show deadlines and scheduled items between a date range."
13446 (interactive "P")
13447 (let (ans kwd value ts-type)
13448 (setq type (or type org-sparse-tree-default-date-type))
13449 (setq org-ts-type type)
13450 (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"
13451 (cond ((eq type 'all) "all timestamps")
13452 ((eq type 'scheduled) "only scheduled")
13453 ((eq type 'deadline) "only deadline")
13454 ((eq type 'active) "only active timestamps")
13455 ((eq type 'inactive) "only inactive timestamps")
13456 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13457 ((eq type 'closed) "with a closed time-stamp")
13458 (t "scheduled/deadline")))
13459 (setq ans (read-char-exclusive))
13460 (cond
13461 ((equal ans ?c)
13462 (org-sparse-tree
13463 arg (cadr (member type '(scheduled-or-deadline
13464 all scheduled deadline active inactive closed)))))
13465 ((equal ans ?d)
13466 (call-interactively 'org-check-deadlines))
13467 ((equal ans ?b)
13468 (call-interactively 'org-check-before-date))
13469 ((equal ans ?a)
13470 (call-interactively 'org-check-after-date))
13471 ((equal ans ?D)
13472 (call-interactively 'org-check-dates-range))
13473 ((equal ans ?t)
13474 (call-interactively 'org-show-todo-tree))
13475 ((equal ans ?T)
13476 (org-show-todo-tree '(4)))
13477 ((member ans '(?T ?m))
13478 (call-interactively 'org-match-sparse-tree))
13479 ((member ans '(?p ?P))
13480 (setq kwd (org-icompleting-read "Property: "
13481 (mapcar 'list (org-buffer-property-keys))))
13482 (setq value (org-icompleting-read "Value: "
13483 (mapcar 'list (org-property-values kwd))))
13484 (unless (string-match "\\`{.*}\\'" value)
13485 (setq value (concat "\"" value "\"")))
13486 (org-match-sparse-tree arg (concat kwd "=" value)))
13487 ((member ans '(?r ?R ?/))
13488 (call-interactively 'org-occur))
13489 (t (user-error "No such sparse tree command \"%c\"" ans)))))
13491 (defvar org-occur-highlights nil
13492 "List of overlays used for occur matches.")
13493 (make-variable-buffer-local 'org-occur-highlights)
13494 (defvar org-occur-parameters nil
13495 "Parameters of the active org-occur calls.
13496 This is a list, each call to org-occur pushes as cons cell,
13497 containing the regular expression and the callback, onto the list.
13498 The list can contain several entries if `org-occur' has been called
13499 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13500 will only contain one set of parameters. When the highlights are
13501 removed (for example with `C-c C-c', or with the next edit (depending
13502 on `org-remove-highlights-with-change'), this variable is emptied
13503 as well.")
13504 (make-variable-buffer-local 'org-occur-parameters)
13506 (defun org-occur (regexp &optional keep-previous callback)
13507 "Make a compact tree which shows all matches of REGEXP.
13508 The tree will show the lines where the regexp matches, and all higher
13509 headlines above the match. It will also show the heading after the match,
13510 to make sure editing the matching entry is easy.
13511 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13512 call to `org-occur' will be kept, to allow stacking of calls to this
13513 command.
13514 If CALLBACK is non-nil, it is a function which is called to confirm
13515 that the match should indeed be shown."
13516 (interactive "sRegexp: \nP")
13517 (when (equal regexp "")
13518 (user-error "Regexp cannot be empty"))
13519 (unless keep-previous
13520 (org-remove-occur-highlights nil nil t))
13521 (push (cons regexp callback) org-occur-parameters)
13522 (let ((cnt 0))
13523 (save-excursion
13524 (goto-char (point-min))
13525 (if (or (not keep-previous) ; do not want to keep
13526 (not org-occur-highlights)) ; no previous matches
13527 ;; hide everything
13528 (org-overview))
13529 (while (re-search-forward regexp nil t)
13530 (when (or (not callback)
13531 (save-match-data (funcall callback)))
13532 (setq cnt (1+ cnt))
13533 (when org-highlight-sparse-tree-matches
13534 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13535 (org-show-context 'occur-tree))))
13536 (when org-remove-highlights-with-change
13537 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13538 nil 'local))
13539 (unless org-sparse-tree-open-archived-trees
13540 (org-hide-archived-subtrees (point-min) (point-max)))
13541 (run-hooks 'org-occur-hook)
13542 (if (org-called-interactively-p 'interactive)
13543 (message "%d match(es) for regexp %s" cnt regexp))
13544 cnt))
13546 (defun org-occur-next-match (&optional n reset)
13547 "Function for `next-error-function' to find sparse tree matches.
13548 N is the number of matches to move, when negative move backwards.
13549 RESET is entirely ignored - this function always goes back to the
13550 starting point when no match is found."
13551 (let* ((limit (if (< n 0) (point-min) (point-max)))
13552 (search-func (if (< n 0)
13553 'previous-single-char-property-change
13554 'next-single-char-property-change))
13555 (n (abs n))
13556 (pos (point))
13558 (catch 'exit
13559 (while (setq p1 (funcall search-func (point) 'org-type))
13560 (when (equal p1 limit)
13561 (goto-char pos)
13562 (error "No more matches"))
13563 (when (equal (get-char-property p1 'org-type) 'org-occur)
13564 (setq n (1- n))
13565 (when (= n 0)
13566 (goto-char p1)
13567 (throw 'exit (point))))
13568 (goto-char p1))
13569 (goto-char p1)
13570 (error "No more matches"))))
13572 (defun org-show-context (&optional key)
13573 "Make sure point and context are visible.
13574 How much context is shown depends upon the variables
13575 `org-show-hierarchy-above', `org-show-following-heading',
13576 `org-show-entry-below' and `org-show-siblings'."
13577 (let ((heading-p (org-at-heading-p t))
13578 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13579 (following-p (org-get-alist-option org-show-following-heading key))
13580 (entry-p (org-get-alist-option org-show-entry-below key))
13581 (siblings-p (org-get-alist-option org-show-siblings key)))
13582 ;; Show heading or entry text
13583 (if (and heading-p (not entry-p))
13584 (org-flag-heading nil) ; only show the heading
13585 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13586 (org-show-hidden-entry))) ; show entire entry
13587 (when following-p
13588 ;; Show next sibling, or heading below text
13589 (save-excursion
13590 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13591 (org-flag-heading nil))))
13592 (when siblings-p (org-show-siblings))
13593 (when hierarchy-p
13594 ;; show all higher headings, possibly with siblings
13595 (save-excursion
13596 (while (and (condition-case nil
13597 (progn (org-up-heading-all 1) t)
13598 (error nil))
13599 (not (bobp)))
13600 (org-flag-heading nil)
13601 (when siblings-p (org-show-siblings)))))
13602 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13604 (defvar org-reveal-start-hook nil
13605 "Hook run before revealing a location.")
13607 (defun org-reveal (&optional siblings)
13608 "Show current entry, hierarchy above it, and the following headline.
13609 This can be used to show a consistent set of context around locations
13610 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13611 not t for the search context.
13613 With optional argument SIBLINGS, on each level of the hierarchy all
13614 siblings are shown. This repairs the tree structure to what it would
13615 look like when opened with hierarchical calls to `org-cycle'.
13616 With double optional argument \\[universal-argument] \\[universal-argument], \
13617 go to the parent and show the
13618 entire tree."
13619 (interactive "P")
13620 (run-hooks 'org-reveal-start-hook)
13621 (let ((org-show-hierarchy-above t)
13622 (org-show-following-heading t)
13623 (org-show-siblings (if siblings t org-show-siblings)))
13624 (org-show-context nil))
13625 (when (equal siblings '(16))
13626 (save-excursion
13627 (when (org-up-heading-safe)
13628 (org-show-subtree)
13629 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13631 (defun org-highlight-new-match (beg end)
13632 "Highlight from BEG to END and mark the highlight is an occur headline."
13633 (let ((ov (make-overlay beg end)))
13634 (overlay-put ov 'face 'secondary-selection)
13635 (overlay-put ov 'org-type 'org-occur)
13636 (push ov org-occur-highlights)))
13638 (defun org-remove-occur-highlights (&optional beg end noremove)
13639 "Remove the occur highlights from the buffer.
13640 BEG and END are ignored. If NOREMOVE is nil, remove this function
13641 from the `before-change-functions' in the current buffer."
13642 (interactive)
13643 (unless org-inhibit-highlight-removal
13644 (mapc 'delete-overlay org-occur-highlights)
13645 (setq org-occur-highlights nil)
13646 (setq org-occur-parameters nil)
13647 (unless noremove
13648 (remove-hook 'before-change-functions
13649 'org-remove-occur-highlights 'local))))
13651 ;;;; Priorities
13653 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13654 "Regular expression matching the priority indicator.")
13656 (defvar org-remove-priority-next-time nil)
13658 (defun org-priority-up ()
13659 "Increase the priority of the current item."
13660 (interactive)
13661 (org-priority 'up))
13663 (defun org-priority-down ()
13664 "Decrease the priority of the current item."
13665 (interactive)
13666 (org-priority 'down))
13668 (defun org-priority (&optional action show)
13669 "Change the priority of an item.
13670 ACTION can be `set', `up', `down', or a character."
13671 (interactive "P")
13672 (if (equal action '(4))
13673 (org-show-priority)
13674 (unless org-enable-priority-commands
13675 (user-error "Priority commands are disabled"))
13676 (setq action (or action 'set))
13677 (let (current new news have remove)
13678 (save-excursion
13679 (org-back-to-heading t)
13680 (if (looking-at org-priority-regexp)
13681 (setq current (string-to-char (match-string 2))
13682 have t))
13683 (cond
13684 ((eq action 'remove)
13685 (setq remove t new ?\ ))
13686 ((or (eq action 'set)
13687 (if (featurep 'xemacs) (characterp action) (integerp action)))
13688 (if (not (eq action 'set))
13689 (setq new action)
13690 (message "Priority %c-%c, SPC to remove: "
13691 org-highest-priority org-lowest-priority)
13692 (save-match-data
13693 (setq new (read-char-exclusive))))
13694 (if (and (= (upcase org-highest-priority) org-highest-priority)
13695 (= (upcase org-lowest-priority) org-lowest-priority))
13696 (setq new (upcase new)))
13697 (cond ((equal new ?\ ) (setq remove t))
13698 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13699 (user-error "Priority must be between `%c' and `%c'"
13700 org-highest-priority org-lowest-priority))))
13701 ((eq action 'up)
13702 (setq new (if have
13703 (1- current) ; normal cycling
13704 ;; last priority was empty
13705 (if (eq last-command this-command)
13706 org-lowest-priority ; wrap around empty to lowest
13707 ;; default
13708 (if org-priority-start-cycle-with-default
13709 org-default-priority
13710 (1- org-default-priority))))))
13711 ((eq action 'down)
13712 (setq new (if have
13713 (1+ current) ; normal cycling
13714 ;; last priority was empty
13715 (if (eq last-command this-command)
13716 org-highest-priority ; wrap around empty to highest
13717 ;; default
13718 (if org-priority-start-cycle-with-default
13719 org-default-priority
13720 (1+ org-default-priority))))))
13721 (t (user-error "Invalid action")))
13722 (if (or (< (upcase new) org-highest-priority)
13723 (> (upcase new) org-lowest-priority))
13724 (if (and (memq action '(up down))
13725 (not have) (not (eq last-command this-command)))
13726 ;; `new' is from default priority
13727 (error
13728 "The default can not be set, see `org-default-priority' why")
13729 ;; normal cycling: `new' is beyond highest/lowest priority
13730 ;; and is wrapped around to the empty priority
13731 (setq remove t)))
13732 (setq news (format "%c" new))
13733 (if have
13734 (if remove
13735 (replace-match "" t t nil 1)
13736 (replace-match news t t nil 2))
13737 (if remove
13738 (user-error "No priority cookie found in line")
13739 (let ((case-fold-search nil))
13740 (looking-at org-todo-line-regexp))
13741 (if (match-end 2)
13742 (progn
13743 (goto-char (match-end 2))
13744 (insert " [#" news "]"))
13745 (goto-char (match-beginning 3))
13746 (insert "[#" news "] "))))
13747 (org-preserve-lc (org-set-tags nil 'align)))
13748 (if remove
13749 (message "Priority removed")
13750 (message "Priority of current item set to %s" news)))))
13752 (defun org-show-priority ()
13753 "Show the priority of the current item.
13754 This priority is composed of the main priority given with the [#A] cookies,
13755 and by additional input from the age of a schedules or deadline entry."
13756 (interactive)
13757 (let ((pri (if (eq major-mode 'org-agenda-mode)
13758 (org-get-at-bol 'priority)
13759 (save-excursion
13760 (save-match-data
13761 (beginning-of-line)
13762 (and (looking-at org-heading-regexp)
13763 (org-get-priority (match-string 0))))))))
13764 (message "Priority is %d" (if pri pri -1000))))
13766 (defun org-get-priority (s)
13767 "Find priority cookie and return priority."
13768 (save-match-data
13769 (if (functionp org-get-priority-function)
13770 (funcall org-get-priority-function)
13771 (if (not (string-match org-priority-regexp s))
13772 (* 1000 (- org-lowest-priority org-default-priority))
13773 (* 1000 (- org-lowest-priority
13774 (string-to-char (match-string 2 s))))))))
13776 ;;;; Tags
13778 (defvar org-agenda-archives-mode)
13779 (defvar org-map-continue-from nil
13780 "Position from where mapping should continue.
13781 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13783 (defvar org-scanner-tags nil
13784 "The current tag list while the tags scanner is running.")
13785 (defvar org-trust-scanner-tags nil
13786 "Should `org-get-tags-at' use the tags for the scanner.
13787 This is for internal dynamical scoping only.
13788 When this is non-nil, the function `org-get-tags-at' will return the value
13789 of `org-scanner-tags' instead of building the list by itself. This
13790 can lead to large speed-ups when the tags scanner is used in a file with
13791 many entries, and when the list of tags is retrieved, for example to
13792 obtain a list of properties. Building the tags list for each entry in such
13793 a file becomes an N^2 operation - but with this variable set, it scales
13794 as N.")
13796 (defun org-scan-tags (action matcher todo-only &optional start-level)
13797 "Sca headline tags with inheritance and produce output ACTION.
13799 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13800 or `agenda' to produce an entry list for an agenda view. It can also be
13801 a Lisp form or a function that should be called at each matched headline, in
13802 this case the return value is a list of all return values from these calls.
13804 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13805 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13806 only lines with a not-done TODO keyword are included in the output.
13807 This should be the same variable that was scoped into
13808 and set by `org-make-tags-matcher' when it constructed MATCHER.
13810 START-LEVEL can be a string with asterisks, reducing the scope to
13811 headlines matching this string."
13812 (require 'org-agenda)
13813 (let* ((re (concat "^"
13814 (if start-level
13815 ;; Get the correct level to match
13816 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13817 org-outline-regexp)
13818 " *\\(\\<\\("
13819 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13820 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13821 (props (list 'face 'default
13822 'done-face 'org-agenda-done
13823 'undone-face 'default
13824 'mouse-face 'highlight
13825 'org-not-done-regexp org-not-done-regexp
13826 'org-todo-regexp org-todo-regexp
13827 'org-complex-heading-regexp org-complex-heading-regexp
13828 'help-echo
13829 (format "mouse-2 or RET jump to org file %s"
13830 (abbreviate-file-name
13831 (or (buffer-file-name (buffer-base-buffer))
13832 (buffer-name (buffer-base-buffer)))))))
13833 (org-map-continue-from nil)
13834 lspos tags tags-list
13835 (tags-alist (list (cons 0 org-file-tags)))
13836 (llast 0) rtn rtn1 level category i txt
13837 todo marker entry priority)
13838 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13839 (setq action (list 'lambda nil action)))
13840 (save-excursion
13841 (goto-char (point-min))
13842 (when (eq action 'sparse-tree)
13843 (org-overview)
13844 (org-remove-occur-highlights))
13845 (while (let (case-fold-search)
13846 (re-search-forward re nil t))
13847 (setq org-map-continue-from nil)
13848 (catch :skip
13849 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13850 tags (if (match-end 4) (org-match-string-no-properties 4)))
13851 (goto-char (setq lspos (match-beginning 0)))
13852 (setq level (org-reduced-level (org-outline-level))
13853 category (org-get-category))
13854 (setq i llast llast level)
13855 ;; remove tag lists from same and sublevels
13856 (while (>= i level)
13857 (when (setq entry (assoc i tags-alist))
13858 (setq tags-alist (delete entry tags-alist)))
13859 (setq i (1- i)))
13860 ;; add the next tags
13861 (when tags
13862 (setq tags (org-split-string tags ":")
13863 tags-alist
13864 (cons (cons level tags) tags-alist)))
13865 ;; compile tags for current headline
13866 (setq tags-list
13867 (if org-use-tag-inheritance
13868 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13869 tags)
13870 org-scanner-tags tags-list)
13871 (when org-use-tag-inheritance
13872 (setcdr (car tags-alist)
13873 (mapcar (lambda (x)
13874 (setq x (copy-sequence x))
13875 (org-add-prop-inherited x))
13876 (cdar tags-alist))))
13877 (when (and tags org-use-tag-inheritance
13878 (or (not (eq t org-use-tag-inheritance))
13879 org-tags-exclude-from-inheritance))
13880 ;; selective inheritance, remove uninherited ones
13881 (setcdr (car tags-alist)
13882 (org-remove-uninherited-tags (cdar tags-alist))))
13883 (when (and
13885 ;; eval matcher only when the todo condition is OK
13886 (and (or (not todo-only) (member todo org-not-done-keywords))
13887 (let ((case-fold-search t) (org-trust-scanner-tags t))
13888 (eval matcher)))
13890 ;; Call the skipper, but return t if it does not skip,
13891 ;; so that the `and' form continues evaluating
13892 (progn
13893 (unless (eq action 'sparse-tree) (org-agenda-skip))
13896 ;; Check if timestamps are deselecting this entry
13897 (or (not todo-only)
13898 (and (member todo org-not-done-keywords)
13899 (or (not org-agenda-tags-todo-honor-ignore-options)
13900 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13902 ;; select this headline
13903 (cond
13904 ((eq action 'sparse-tree)
13905 (and org-highlight-sparse-tree-matches
13906 (org-get-heading) (match-end 0)
13907 (org-highlight-new-match
13908 (match-beginning 1) (match-end 1)))
13909 (org-show-context 'tags-tree))
13910 ((eq action 'agenda)
13911 (setq txt (org-agenda-format-item
13913 (concat
13914 (if (eq org-tags-match-list-sublevels 'indented)
13915 (make-string (1- level) ?.) "")
13916 (org-get-heading))
13917 level category
13918 tags-list)
13919 priority (org-get-priority txt))
13920 (goto-char lspos)
13921 (setq marker (org-agenda-new-marker))
13922 (org-add-props txt props
13923 'org-marker marker 'org-hd-marker marker 'org-category category
13924 'todo-state todo
13925 'priority priority 'type "tagsmatch")
13926 (push txt rtn))
13927 ((functionp action)
13928 (setq org-map-continue-from nil)
13929 (save-excursion
13930 (setq rtn1 (funcall action))
13931 (push rtn1 rtn)))
13932 (t (user-error "Invalid action")))
13934 ;; if we are to skip sublevels, jump to end of subtree
13935 (unless org-tags-match-list-sublevels
13936 (org-end-of-subtree t)
13937 (backward-char 1))))
13938 ;; Get the correct position from where to continue
13939 (if org-map-continue-from
13940 (goto-char org-map-continue-from)
13941 (and (= (point) lspos) (end-of-line 1)))))
13942 (when (and (eq action 'sparse-tree)
13943 (not org-sparse-tree-open-archived-trees))
13944 (org-hide-archived-subtrees (point-min) (point-max)))
13945 (nreverse rtn)))
13947 (defun org-remove-uninherited-tags (tags)
13948 "Remove all tags that are not inherited from the list TAGS."
13949 (cond
13950 ((eq org-use-tag-inheritance t)
13951 (if org-tags-exclude-from-inheritance
13952 (org-delete-all org-tags-exclude-from-inheritance tags)
13953 tags))
13954 ((not org-use-tag-inheritance) nil)
13955 ((stringp org-use-tag-inheritance)
13956 (delq nil (mapcar
13957 (lambda (x)
13958 (if (and (string-match org-use-tag-inheritance x)
13959 (not (member x org-tags-exclude-from-inheritance)))
13960 x nil))
13961 tags)))
13962 ((listp org-use-tag-inheritance)
13963 (delq nil (mapcar
13964 (lambda (x)
13965 (if (member x org-use-tag-inheritance) x nil))
13966 tags)))))
13968 (defun org-match-sparse-tree (&optional todo-only match)
13969 "Create a sparse tree according to tags string MATCH.
13970 MATCH can contain positive and negative selection of tags, like
13971 \"+WORK+URGENT-WITHBOSS\".
13972 If optional argument TODO-ONLY is non-nil, only select lines that are
13973 also TODO lines."
13974 (interactive "P")
13975 (org-agenda-prepare-buffers (list (current-buffer)))
13976 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13978 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13980 (defvar org-cached-props nil)
13981 (defun org-cached-entry-get (pom property)
13982 (if (or (eq t org-use-property-inheritance)
13983 (and (stringp org-use-property-inheritance)
13984 (string-match org-use-property-inheritance property))
13985 (and (listp org-use-property-inheritance)
13986 (member property org-use-property-inheritance)))
13987 ;; Caching is not possible, check it directly
13988 (org-entry-get pom property 'inherit)
13989 ;; Get all properties, so that we can do complicated checks easily
13990 (cdr (assoc property (or org-cached-props
13991 (setq org-cached-props
13992 (org-entry-properties pom)))))))
13994 (defun org-global-tags-completion-table (&optional files)
13995 "Return the list of all tags in all agenda buffer/files.
13996 Optional FILES argument is a list of files which can be used
13997 instead of the agenda files."
13998 (save-excursion
13999 (org-uniquify
14000 (delq nil
14001 (apply 'append
14002 (mapcar
14003 (lambda (file)
14004 (set-buffer (find-file-noselect file))
14005 (append (org-get-buffer-tags)
14006 (mapcar (lambda (x) (if (stringp (car-safe x))
14007 (list (car-safe x)) nil))
14008 org-tag-alist)))
14009 (if (and files (car files))
14010 files
14011 (org-agenda-files))))))))
14013 (defun org-make-tags-matcher (match)
14014 "Create the TAGS/TODO matcher form for the selection string MATCH.
14016 The variable `todo-only' is scoped dynamically into this function.
14017 It will be set to t if the matcher restricts matching to TODO entries,
14018 otherwise will not be touched.
14020 Returns a cons of the selection string MATCH and the constructed
14021 lisp form implementing the matcher. The matcher is to be evaluated
14022 at an Org entry, with point on the headline, and returns t if the
14023 entry matches the selection string MATCH. The returned lisp form
14024 references two variables with information about the entry, which
14025 must be bound around the form's evaluation: todo, the TODO keyword
14026 at the entry (or nil of none); and tags-list, the list of all tags
14027 at the entry including inherited ones. Additionally, the category
14028 of the entry (if any) must be specified as the text property
14029 'org-category on the headline.
14031 See also `org-scan-tags'.
14033 (declare (special todo-only))
14034 (unless (boundp 'todo-only)
14035 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14036 (unless match
14037 ;; Get a new match request, with completion against the global
14038 ;; tags table and the local tags in current buffer
14039 (let ((org-last-tags-completion-table
14040 (org-uniquify
14041 (delq nil (append (org-get-buffer-tags)
14042 (org-global-tags-completion-table))))))
14043 (setq match (org-completing-read-no-i
14044 "Match: " 'org-tags-completion-function nil nil nil
14045 'org-tags-history))))
14047 ;; Parse the string and create a lisp form
14048 (let ((match0 match)
14049 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14050 minus tag mm
14051 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14052 orterms term orlist re-p str-p level-p level-op time-p
14053 prop-p pn pv po gv rest)
14054 ;; Expand group tags
14055 (setq match (org-tags-expand match))
14056 (if (string-match "/+" match)
14057 ;; match contains also a todo-matching request
14058 (progn
14059 (setq tagsmatch (substring match 0 (match-beginning 0))
14060 todomatch (substring match (match-end 0)))
14061 (if (string-match "^!" todomatch)
14062 (setq todo-only t todomatch (substring todomatch 1)))
14063 (if (string-match "^\\s-*$" todomatch)
14064 (setq todomatch nil)))
14065 ;; only matching tags
14066 (setq tagsmatch match todomatch nil))
14068 ;; Make the tags matcher
14069 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14070 (setq tagsmatcher t)
14071 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14072 (while (setq term (pop orterms))
14073 (while (and (equal (substring term -1) "\\") orterms)
14074 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14075 (while (string-match re term)
14076 (setq rest (substring term (match-end 0))
14077 minus (and (match-end 1)
14078 (equal (match-string 1 term) "-"))
14079 tag (save-match-data (replace-regexp-in-string
14080 "\\\\-" "-"
14081 (match-string 2 term)))
14082 re-p (equal (string-to-char tag) ?{)
14083 level-p (match-end 4)
14084 prop-p (match-end 5)
14085 mm (cond
14086 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14087 (level-p
14088 (setq level-op (org-op-to-function (match-string 3 term)))
14089 `(,level-op level ,(string-to-number
14090 (match-string 4 term))))
14091 (prop-p
14092 (setq pn (match-string 5 term)
14093 po (match-string 6 term)
14094 pv (match-string 7 term)
14095 re-p (equal (string-to-char pv) ?{)
14096 str-p (equal (string-to-char pv) ?\")
14097 time-p (save-match-data
14098 (string-match "^\"[[<].*[]>]\"$" pv))
14099 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14100 (if time-p (setq pv (org-matcher-time pv)))
14101 (setq po (org-op-to-function po (if time-p 'time str-p)))
14102 (cond
14103 ((equal pn "CATEGORY")
14104 (setq gv '(get-text-property (point) 'org-category)))
14105 ((equal pn "TODO")
14106 (setq gv 'todo))
14108 (setq gv `(org-cached-entry-get nil ,pn))))
14109 (if re-p
14110 (if (eq po 'org<>)
14111 `(not (string-match ,pv (or ,gv "")))
14112 `(string-match ,pv (or ,gv "")))
14113 (if str-p
14114 `(,po (or ,gv "") ,pv)
14115 `(,po (string-to-number (or ,gv ""))
14116 ,(string-to-number pv) ))))
14117 (t `(member ,tag tags-list)))
14118 mm (if minus (list 'not mm) mm)
14119 term rest)
14120 (push mm tagsmatcher))
14121 (push (if (> (length tagsmatcher) 1)
14122 (cons 'and tagsmatcher)
14123 (car tagsmatcher))
14124 orlist)
14125 (setq tagsmatcher nil))
14126 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14127 (setq tagsmatcher
14128 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14129 ;; Make the todo matcher
14130 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14131 (setq todomatcher t)
14132 (setq orterms (org-split-string todomatch "|") orlist nil)
14133 (while (setq term (pop orterms))
14134 (while (string-match re term)
14135 (setq minus (and (match-end 1)
14136 (equal (match-string 1 term) "-"))
14137 kwd (match-string 2 term)
14138 re-p (equal (string-to-char kwd) ?{)
14139 term (substring term (match-end 0))
14140 mm (if re-p
14141 `(string-match ,(substring kwd 1 -1) todo)
14142 (list 'equal 'todo kwd))
14143 mm (if minus (list 'not mm) mm))
14144 (push mm todomatcher))
14145 (push (if (> (length todomatcher) 1)
14146 (cons 'and todomatcher)
14147 (car todomatcher))
14148 orlist)
14149 (setq todomatcher nil))
14150 (setq todomatcher (if (> (length orlist) 1)
14151 (cons 'or orlist) (car orlist))))
14153 ;; Return the string and lisp forms of the matcher
14154 (setq matcher (if todomatcher
14155 (list 'and tagsmatcher todomatcher)
14156 tagsmatcher))
14157 (when todo-only
14158 (setq matcher (list 'and '(member todo org-not-done-keywords)
14159 matcher)))
14160 (cons match0 matcher)))
14162 (defun org-tags-expand (match &optional single-as-list downcased)
14163 "Expand group tags in MATCH.
14165 This replaces every group tag in MATCH with a regexp tag search.
14166 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14167 will be replaced like this:
14169 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14170 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14171 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14173 Replacing by a regexp preserves the structure of the match.
14174 E.g., this expansion
14176 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14178 will match anything tagged with \"Lab\" and \"Home\", or tagged
14179 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14181 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14182 assumed to be a single group tag, and the function will return
14183 the list of tags in this group.
14185 When DOWNCASE is non-nil, expand downcased TAGS."
14186 (if org-group-tags
14187 (let* ((case-fold-search t)
14188 (stable org-mode-syntax-table)
14189 (tal (or org-tag-groups-alist-for-agenda
14190 org-tag-groups-alist))
14191 (tal (if downcased
14192 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14193 (tml (mapcar 'car tal))
14194 (rtnmatch match) rpl)
14195 ;; @ and _ are allowed as word-components in tags
14196 (modify-syntax-entry ?@ "w" stable)
14197 (modify-syntax-entry ?_ "w" stable)
14198 (while (and tml
14199 (with-syntax-table stable
14200 (string-match
14201 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14202 (regexp-opt tml) "\\>\\)") rtnmatch)))
14203 (let* ((dir (match-string 1 rtnmatch))
14204 (tag (match-string 2 rtnmatch))
14205 (tag (if downcased (downcase tag) tag)))
14206 (setq tml (delete tag tml))
14207 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14208 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14209 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14210 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14211 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14212 (if single-as-list
14213 (or (reverse rpl) (list rtnmatch))
14214 rtnmatch))
14215 (if single-as-list (list (if downcased (downcase match) match))
14216 match)))
14218 (defun org-op-to-function (op &optional stringp)
14219 "Turn an operator into the appropriate function."
14220 (setq op
14221 (cond
14222 ((equal op "<" ) '(< string< org-time<))
14223 ((equal op ">" ) '(> org-string> org-time>))
14224 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14225 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14226 ((member op '("=" "==")) '(= string= org-time=))
14227 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14228 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14230 (defun org<> (a b) (not (= a b)))
14231 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14232 (defun org-string>= (a b) (not (string< a b)))
14233 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14234 (defun org-string<> (a b) (not (string= a b)))
14235 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14236 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14237 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14238 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14239 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14240 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14241 (defun org-2ft (s)
14242 "Convert S to a floating point time.
14243 If S is already a number, just return it. If it is a string, parse
14244 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14245 (cond
14246 ((numberp s) s)
14247 ((stringp s)
14248 (condition-case nil
14249 (float-time (apply 'encode-time (org-parse-time-string s)))
14250 (error 0.)))
14251 (t 0.)))
14253 (defun org-time-today ()
14254 "Time in seconds today at 0:00.
14255 Returns the float number of seconds since the beginning of the
14256 epoch to the beginning of today (00:00)."
14257 (float-time (apply 'encode-time
14258 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14260 (defun org-matcher-time (s)
14261 "Interpret a time comparison value."
14262 (save-match-data
14263 (cond
14264 ((string= s "<now>") (float-time))
14265 ((string= s "<today>") (org-time-today))
14266 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14267 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14268 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14269 (+ (org-time-today)
14270 (* (string-to-number (match-string 1 s))
14271 (cdr (assoc (match-string 2 s)
14272 '(("d" . 86400.0) ("w" . 604800.0)
14273 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14274 (t (org-2ft s)))))
14276 (defun org-match-any-p (re list)
14277 "Does re match any element of list?"
14278 (setq list (mapcar (lambda (x) (string-match re x)) list))
14279 (delq nil list))
14281 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14282 (defvar org-tags-overlay (make-overlay 1 1))
14283 (org-detach-overlay org-tags-overlay)
14285 (defun org-get-local-tags-at (&optional pos)
14286 "Get a list of tags defined in the current headline."
14287 (org-get-tags-at pos 'local))
14289 (defun org-get-local-tags ()
14290 "Get a list of tags defined in the current headline."
14291 (org-get-tags-at nil 'local))
14293 (defun org-get-tags-at (&optional pos local)
14294 "Get a list of all headline tags applicable at POS.
14295 POS defaults to point. If tags are inherited, the list contains
14296 the targets in the same sequence as the headlines appear, i.e.
14297 the tags of the current headline come last.
14298 When LOCAL is non-nil, only return tags from the current headline,
14299 ignore inherited ones."
14300 (interactive)
14301 (if (and org-trust-scanner-tags
14302 (or (not pos) (equal pos (point)))
14303 (not local))
14304 org-scanner-tags
14305 (let (tags ltags lastpos parent)
14306 (save-excursion
14307 (save-restriction
14308 (widen)
14309 (goto-char (or pos (point)))
14310 (save-match-data
14311 (catch 'done
14312 (condition-case nil
14313 (progn
14314 (org-back-to-heading t)
14315 (while (not (equal lastpos (point)))
14316 (setq lastpos (point))
14317 (when (looking-at
14318 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14319 (setq ltags (org-split-string
14320 (org-match-string-no-properties 1) ":"))
14321 (when parent
14322 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14323 (setq tags (append
14324 (if parent
14325 (org-remove-uninherited-tags ltags)
14326 ltags)
14327 tags)))
14328 (or org-use-tag-inheritance (throw 'done t))
14329 (if local (throw 'done t))
14330 (or (org-up-heading-safe) (error nil))
14331 (setq parent t)))
14332 (error nil)))))
14333 (if local
14334 tags
14335 (reverse (delete-dups
14336 (reverse (append
14337 (org-remove-uninherited-tags
14338 org-file-tags) tags)))))))))
14340 (defun org-add-prop-inherited (s)
14341 (add-text-properties 0 (length s) '(inherited t) s)
14344 (defun org-toggle-tag (tag &optional onoff)
14345 "Toggle the tag TAG for the current line.
14346 If ONOFF is `on' or `off', don't toggle but set to this state."
14347 (let (res current)
14348 (save-excursion
14349 (org-back-to-heading t)
14350 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14351 (point-at-eol) t)
14352 (progn
14353 (setq current (match-string 1))
14354 (replace-match ""))
14355 (setq current ""))
14356 (setq current (nreverse (org-split-string current ":")))
14357 (cond
14358 ((eq onoff 'on)
14359 (setq res t)
14360 (or (member tag current) (push tag current)))
14361 ((eq onoff 'off)
14362 (or (not (member tag current)) (setq current (delete tag current))))
14363 (t (if (member tag current)
14364 (setq current (delete tag current))
14365 (setq res t)
14366 (push tag current))))
14367 (end-of-line 1)
14368 (if current
14369 (progn
14370 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14371 (org-set-tags nil t))
14372 (delete-horizontal-space))
14373 (run-hooks 'org-after-tags-change-hook))
14374 res))
14376 (defun org-align-tags-here (to-col)
14377 ;; Assumes that this is a headline
14378 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14379 (beginning-of-line 1)
14380 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14381 (< pos (match-beginning 2)))
14382 (progn
14383 (setq tags-l (- (match-end 2) (match-beginning 2)))
14384 (goto-char (match-beginning 1))
14385 (insert " ")
14386 (delete-region (point) (1+ (match-beginning 2)))
14387 (setq ncol (max (current-column)
14388 (1+ col)
14389 (if (> to-col 0)
14390 to-col
14391 (- (abs to-col) tags-l))))
14392 (setq p (point))
14393 (insert (make-string (- ncol (current-column)) ?\ ))
14394 (setq ncol (current-column))
14395 (when indent-tabs-mode (tabify p (point-at-eol)))
14396 (org-move-to-column (min ncol col) t))
14397 (goto-char pos))))
14399 (defun org-set-tags-command (&optional arg just-align)
14400 "Call the set-tags command for the current entry."
14401 (interactive "P")
14402 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14403 (org-set-tags arg just-align)
14404 (save-excursion
14405 (unless (and (org-region-active-p)
14406 org-loop-over-headlines-in-active-region)
14407 (org-back-to-heading t))
14408 (org-set-tags arg just-align))))
14410 (defun org-set-tags-to (data)
14411 "Set the tags of the current entry to DATA, replacing the current tags.
14412 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14413 If DATA is nil or the empty string, any tags will be removed."
14414 (interactive "sTags: ")
14415 (setq data
14416 (cond
14417 ((eq data nil) "")
14418 ((equal data "") "")
14419 ((stringp data)
14420 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14421 ":"))
14422 ((listp data)
14423 (concat ":" (mapconcat 'identity data ":") ":"))))
14424 (when data
14425 (save-excursion
14426 (org-back-to-heading t)
14427 (when (looking-at org-complex-heading-regexp)
14428 (if (match-end 5)
14429 (progn
14430 (goto-char (match-beginning 5))
14431 (insert data)
14432 (delete-region (point) (point-at-eol))
14433 (org-set-tags nil 'align))
14434 (goto-char (point-at-eol))
14435 (insert " " data)
14436 (org-set-tags nil 'align)))
14437 (beginning-of-line 1)
14438 (if (looking-at ".*?\\([ \t]+\\)$")
14439 (delete-region (match-beginning 1) (match-end 1))))))
14441 (defun org-align-all-tags ()
14442 "Align the tags i all headings."
14443 (interactive)
14444 (save-excursion
14445 (or (ignore-errors (org-back-to-heading t))
14446 (outline-next-heading))
14447 (if (org-at-heading-p)
14448 (org-set-tags t)
14449 (message "No headings"))))
14451 (defvar org-indent-indentation-per-level)
14452 (defun org-set-tags (&optional arg just-align)
14453 "Set the tags for the current headline.
14454 With prefix ARG, realign all tags in headings in the current buffer."
14455 (interactive "P")
14456 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14457 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14458 'region-start-level 'region))
14459 org-loop-over-headlines-in-active-region)
14460 (org-map-entries
14461 ;; We don't use ARG and JUST-ALIGN here these args are not
14462 ;; useful when looping over headlines
14463 `(org-set-tags)
14464 org-loop-over-headlines-in-active-region
14465 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14466 (let* ((re org-outline-regexp-bol)
14467 (current (unless arg (org-get-tags-string)))
14468 (col (current-column))
14469 (org-setting-tags t)
14470 table current-tags inherited-tags ; computed below when needed
14471 tags p0 c0 c1 rpl di tc level)
14472 (if arg
14473 (save-excursion
14474 (goto-char (point-min))
14475 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14476 (while (re-search-forward re nil t)
14477 (org-set-tags nil t)
14478 (end-of-line 1)))
14479 (message "All tags realigned to column %d" org-tags-column))
14480 (if just-align
14481 (setq tags current)
14482 ;; Get a new set of tags from the user
14483 (save-excursion
14484 (setq table (append org-tag-persistent-alist
14485 (or org-tag-alist (org-get-buffer-tags))
14486 (and
14487 org-complete-tags-always-offer-all-agenda-tags
14488 (org-global-tags-completion-table
14489 (org-agenda-files))))
14490 org-last-tags-completion-table table
14491 current-tags (org-split-string current ":")
14492 inherited-tags (nreverse
14493 (nthcdr (length current-tags)
14494 (nreverse (org-get-tags-at))))
14495 tags
14496 (if (or (eq t org-use-fast-tag-selection)
14497 (and org-use-fast-tag-selection
14498 (delq nil (mapcar 'cdr table))))
14499 (org-fast-tag-selection
14500 current-tags inherited-tags table
14501 (if org-fast-tag-selection-include-todo
14502 org-todo-key-alist))
14503 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14504 (org-trim
14505 (org-icompleting-read "Tags: "
14506 'org-tags-completion-function
14507 nil nil current 'org-tags-history))))))
14508 (while (string-match "[-+&]+" tags)
14509 ;; No boolean logic, just a list
14510 (setq tags (replace-match ":" t t tags))))
14512 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14514 (if org-tags-sort-function
14515 (setq tags (mapconcat 'identity
14516 (sort (org-split-string
14517 tags (org-re "[^[:alnum:]_@#%]+"))
14518 org-tags-sort-function) ":")))
14520 (if (string-match "\\`[\t ]*\\'" tags)
14521 (setq tags "")
14522 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14523 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14525 ;; Insert new tags at the correct column
14526 (beginning-of-line 1)
14527 (setq level (or (and (looking-at org-outline-regexp)
14528 (- (match-end 0) (point) 1))
14530 (cond
14531 ((and (equal current "") (equal tags "")))
14532 ((re-search-forward
14533 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14534 (point-at-eol) t)
14535 (if (equal tags "")
14536 (setq rpl "")
14537 (goto-char (match-beginning 0))
14538 (setq c0 (current-column)
14539 ;; compute offset for the case of org-indent-mode active
14540 di (if org-indent-mode
14541 (* (1- org-indent-indentation-per-level) (1- level))
14543 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14544 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14545 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14546 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14547 (replace-match rpl t t)
14548 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14549 tags)
14550 (t (error "Tags alignment failed")))
14551 (org-move-to-column col)
14552 (unless just-align
14553 (run-hooks 'org-after-tags-change-hook))))))
14555 (defun org-change-tag-in-region (beg end tag off)
14556 "Add or remove TAG for each entry in the region.
14557 This works in the agenda, and also in an org-mode buffer."
14558 (interactive
14559 (list (region-beginning) (region-end)
14560 (let ((org-last-tags-completion-table
14561 (if (derived-mode-p 'org-mode)
14562 (org-uniquify
14563 (delq nil (append (org-get-buffer-tags)
14564 (org-global-tags-completion-table))))
14565 (org-global-tags-completion-table))))
14566 (org-icompleting-read
14567 "Tag: " 'org-tags-completion-function nil nil nil
14568 'org-tags-history))
14569 (progn
14570 (message "[s]et or [r]emove? ")
14571 (equal (read-char-exclusive) ?r))))
14572 (if (fboundp 'deactivate-mark) (deactivate-mark))
14573 (let ((agendap (equal major-mode 'org-agenda-mode))
14574 l1 l2 m buf pos newhead (cnt 0))
14575 (goto-char end)
14576 (setq l2 (1- (org-current-line)))
14577 (goto-char beg)
14578 (setq l1 (org-current-line))
14579 (loop for l from l1 to l2 do
14580 (org-goto-line l)
14581 (setq m (get-text-property (point) 'org-hd-marker))
14582 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14583 (and agendap m))
14584 (setq buf (if agendap (marker-buffer m) (current-buffer))
14585 pos (if agendap m (point)))
14586 (with-current-buffer buf
14587 (save-excursion
14588 (save-restriction
14589 (goto-char pos)
14590 (setq cnt (1+ cnt))
14591 (org-toggle-tag tag (if off 'off 'on))
14592 (setq newhead (org-get-heading)))))
14593 (and agendap (org-agenda-change-all-lines newhead m))))
14594 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14596 (defun org-tags-completion-function (string predicate &optional flag)
14597 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14598 (confirm (lambda (x) (stringp (car x)))))
14599 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14600 (setq s1 (match-string 1 string)
14601 s2 (match-string 2 string))
14602 (setq s1 "" s2 string))
14603 (cond
14604 ((eq flag nil)
14605 ;; try completion
14606 (setq rtn (try-completion s2 ctable confirm))
14607 (if (stringp rtn)
14608 (setq rtn
14609 (concat s1 s2 (substring rtn (length s2))
14610 (if (and org-add-colon-after-tag-completion
14611 (assoc rtn ctable))
14612 ":" ""))))
14613 rtn)
14614 ((eq flag t)
14615 ;; all-completions
14616 (all-completions s2 ctable confirm))
14617 ((eq flag 'lambda)
14618 ;; exact match?
14619 (assoc s2 ctable)))))
14621 (defun org-fast-tag-insert (kwd tags face &optional end)
14622 "Insert KDW, and the TAGS, the latter with face FACE.
14623 Also insert END."
14624 (insert (format "%-12s" (concat kwd ":"))
14625 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14626 (or end "")))
14628 (defun org-fast-tag-show-exit (flag)
14629 (save-excursion
14630 (org-goto-line 3)
14631 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14632 (replace-match ""))
14633 (when flag
14634 (end-of-line 1)
14635 (org-move-to-column (- (window-width) 19) t)
14636 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14638 (defun org-set-current-tags-overlay (current prefix)
14639 "Add an overlay to CURRENT tag with PREFIX."
14640 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14641 (if (featurep 'xemacs)
14642 (org-overlay-display org-tags-overlay (concat prefix s)
14643 'secondary-selection)
14644 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14645 (org-overlay-display org-tags-overlay (concat prefix s)))))
14647 (defvar org-last-tag-selection-key nil)
14648 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14649 "Fast tag selection with single keys.
14650 CURRENT is the current list of tags in the headline, INHERITED is the
14651 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14652 possibly with grouping information. TODO-TABLE is a similar table with
14653 TODO keywords, should these have keys assigned to them.
14654 If the keys are nil, a-z are automatically assigned.
14655 Returns the new tags string, or nil to not change the current settings."
14656 (let* ((fulltable (append table todo-table))
14657 (maxlen (apply 'max (mapcar
14658 (lambda (x)
14659 (if (stringp (car x)) (string-width (car x)) 0))
14660 fulltable)))
14661 (buf (current-buffer))
14662 (expert (eq org-fast-tag-selection-single-key 'expert))
14663 (buffer-tags nil)
14664 (fwidth (+ maxlen 3 1 3))
14665 (ncol (/ (- (window-width) 4) fwidth))
14666 (i-face 'org-done)
14667 (c-face 'org-todo)
14668 tg cnt e c char c1 c2 ntable tbl rtn
14669 ov-start ov-end ov-prefix
14670 (exit-after-next org-fast-tag-selection-single-key)
14671 (done-keywords org-done-keywords)
14672 groups ingroup)
14673 (save-excursion
14674 (beginning-of-line 1)
14675 (if (looking-at
14676 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14677 (setq ov-start (match-beginning 1)
14678 ov-end (match-end 1)
14679 ov-prefix "")
14680 (setq ov-start (1- (point-at-eol))
14681 ov-end (1+ ov-start))
14682 (skip-chars-forward "^\n\r")
14683 (setq ov-prefix
14684 (concat
14685 (buffer-substring (1- (point)) (point))
14686 (if (> (current-column) org-tags-column)
14688 (make-string (- org-tags-column (current-column)) ?\ ))))))
14689 (move-overlay org-tags-overlay ov-start ov-end)
14690 (save-window-excursion
14691 (if expert
14692 (set-buffer (get-buffer-create " *Org tags*"))
14693 (delete-other-windows)
14694 (split-window-vertically)
14695 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14696 (erase-buffer)
14697 (org-set-local 'org-done-keywords done-keywords)
14698 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14699 (org-fast-tag-insert "Current" current c-face "\n\n")
14700 (org-fast-tag-show-exit exit-after-next)
14701 (org-set-current-tags-overlay current ov-prefix)
14702 (setq tbl fulltable char ?a cnt 0)
14703 (while (setq e (pop tbl))
14704 (cond
14705 ((equal (car e) :startgroup)
14706 (push '() groups) (setq ingroup t)
14707 (when (not (= cnt 0))
14708 (setq cnt 0)
14709 (insert "\n"))
14710 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14711 ((equal (car e) :endgroup)
14712 (setq ingroup nil cnt 0)
14713 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14714 ((equal e '(:newline))
14715 (when (not (= cnt 0))
14716 (setq cnt 0)
14717 (insert "\n")
14718 (setq e (car tbl))
14719 (while (equal (car tbl) '(:newline))
14720 (insert "\n")
14721 (setq tbl (cdr tbl)))))
14722 ((equal e '(:grouptags)) nil)
14724 (setq tg (copy-sequence (car e)) c2 nil)
14725 (if (cdr e)
14726 (setq c (cdr e))
14727 ;; automatically assign a character.
14728 (setq c1 (string-to-char
14729 (downcase (substring
14730 tg (if (= (string-to-char tg) ?@) 1 0)))))
14731 (if (or (rassoc c1 ntable) (rassoc c1 table))
14732 (while (or (rassoc char ntable) (rassoc char table))
14733 (setq char (1+ char)))
14734 (setq c2 c1))
14735 (setq c (or c2 char)))
14736 (if ingroup (push tg (car groups)))
14737 (setq tg (org-add-props tg nil 'face
14738 (cond
14739 ((not (assoc tg table))
14740 (org-get-todo-face tg))
14741 ((member tg current) c-face)
14742 ((member tg inherited) i-face))))
14743 (if (equal (caar tbl) :grouptags)
14744 (org-add-props tg nil 'face 'org-tag-group))
14745 (if (and (= cnt 0) (not ingroup)) (insert " "))
14746 (insert "[" c "] " tg (make-string
14747 (- fwidth 4 (length tg)) ?\ ))
14748 (push (cons tg c) ntable)
14749 (when (= (setq cnt (1+ cnt)) ncol)
14750 (insert "\n")
14751 (if ingroup (insert " "))
14752 (setq cnt 0)))))
14753 (setq ntable (nreverse ntable))
14754 (insert "\n")
14755 (goto-char (point-min))
14756 (if (not expert) (org-fit-window-to-buffer))
14757 (setq rtn
14758 (catch 'exit
14759 (while t
14760 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14761 (if (not groups) "no " "")
14762 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14763 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14764 (setq org-last-tag-selection-key c)
14765 (cond
14766 ((= c ?\r) (throw 'exit t))
14767 ((= c ?!)
14768 (setq groups (not groups))
14769 (goto-char (point-min))
14770 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14771 ((= c ?\C-c)
14772 (if (not expert)
14773 (org-fast-tag-show-exit
14774 (setq exit-after-next (not exit-after-next)))
14775 (setq expert nil)
14776 (delete-other-windows)
14777 (set-window-buffer (split-window-vertically) " *Org tags*")
14778 (org-switch-to-buffer-other-window " *Org tags*")
14779 (org-fit-window-to-buffer)))
14780 ((or (= c ?\C-g)
14781 (and (= c ?q) (not (rassoc c ntable))))
14782 (org-detach-overlay org-tags-overlay)
14783 (setq quit-flag t))
14784 ((= c ?\ )
14785 (setq current nil)
14786 (if exit-after-next (setq exit-after-next 'now)))
14787 ((= c ?\t)
14788 (condition-case nil
14789 (setq tg (org-icompleting-read
14790 "Tag: "
14791 (or buffer-tags
14792 (with-current-buffer buf
14793 (org-get-buffer-tags)))))
14794 (quit (setq tg "")))
14795 (when (string-match "\\S-" tg)
14796 (add-to-list 'buffer-tags (list tg))
14797 (if (member tg current)
14798 (setq current (delete tg current))
14799 (push tg current)))
14800 (if exit-after-next (setq exit-after-next 'now)))
14801 ((setq e (rassoc c todo-table) tg (car e))
14802 (with-current-buffer buf
14803 (save-excursion (org-todo tg)))
14804 (if exit-after-next (setq exit-after-next 'now)))
14805 ((setq e (rassoc c ntable) tg (car e))
14806 (if (member tg current)
14807 (setq current (delete tg current))
14808 (loop for g in groups do
14809 (if (member tg g)
14810 (mapc (lambda (x)
14811 (setq current (delete x current)))
14812 g)))
14813 (push tg current))
14814 (if exit-after-next (setq exit-after-next 'now))))
14816 ;; Create a sorted list
14817 (setq current
14818 (sort current
14819 (lambda (a b)
14820 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14821 (if (eq exit-after-next 'now) (throw 'exit t))
14822 (goto-char (point-min))
14823 (beginning-of-line 2)
14824 (delete-region (point) (point-at-eol))
14825 (org-fast-tag-insert "Current" current c-face)
14826 (org-set-current-tags-overlay current ov-prefix)
14827 (while (re-search-forward
14828 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14829 (setq tg (match-string 1))
14830 (add-text-properties
14831 (match-beginning 1) (match-end 1)
14832 (list 'face
14833 (cond
14834 ((member tg current) c-face)
14835 ((member tg inherited) i-face)
14836 (t (get-text-property (match-beginning 1) 'face))))))
14837 (goto-char (point-min)))))
14838 (org-detach-overlay org-tags-overlay)
14839 (if rtn
14840 (mapconcat 'identity current ":")
14841 nil))))
14843 (defun org-get-tags-string ()
14844 "Get the TAGS string in the current headline."
14845 (unless (org-at-heading-p t)
14846 (user-error "Not on a heading"))
14847 (save-excursion
14848 (beginning-of-line 1)
14849 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14850 (org-match-string-no-properties 1)
14851 "")))
14853 (defun org-get-tags ()
14854 "Get the list of tags specified in the current headline."
14855 (org-split-string (org-get-tags-string) ":"))
14857 (defun org-get-buffer-tags ()
14858 "Get a table of all tags used in the buffer, for completion."
14859 (let (tags)
14860 (save-excursion
14861 (goto-char (point-min))
14862 (while (re-search-forward
14863 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14864 (when (equal (char-after (point-at-bol 0)) ?*)
14865 (mapc (lambda (x) (add-to-list 'tags x))
14866 (org-split-string (org-match-string-no-properties 1) ":")))))
14867 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14868 (mapcar 'list tags)))
14870 ;;;; The mapping API
14872 (defun org-map-entries (func &optional match scope &rest skip)
14873 "Call FUNC at each headline selected by MATCH in SCOPE.
14875 FUNC is a function or a lisp form. The function will be called without
14876 arguments, with the cursor positioned at the beginning of the headline.
14877 The return values of all calls to the function will be collected and
14878 returned as a list.
14880 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14881 does not need to preserve point. After evaluation, the cursor will be
14882 moved to the end of the line (presumably of the headline of the
14883 processed entry) and search continues from there. Under some
14884 circumstances, this may not produce the wanted results. For example,
14885 if you have removed (e.g. archived) the current (sub)tree it could
14886 mean that the next entry will be skipped entirely. In such cases, you
14887 can specify the position from where search should continue by making
14888 FUNC set the variable `org-map-continue-from' to the desired buffer
14889 position.
14891 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14892 Only headlines that are matched by this query will be considered during
14893 the iteration. When MATCH is nil or t, all headlines will be
14894 visited by the iteration.
14896 SCOPE determines the scope of this command. It can be any of:
14898 nil The current buffer, respecting the restriction if any
14899 tree The subtree started with the entry at point
14900 region The entries within the active region, if any
14901 region-start-level
14902 The entries within the active region, but only those at
14903 the same level than the first one.
14904 file The current buffer, without restriction
14905 file-with-archives
14906 The current buffer, and any archives associated with it
14907 agenda All agenda files
14908 agenda-with-archives
14909 All agenda files with any archive files associated with them
14910 \(file1 file2 ...)
14911 If this is a list, all files in the list will be scanned
14913 The remaining args are treated as settings for the skipping facilities of
14914 the scanner. The following items can be given here:
14916 archive skip trees with the archive tag
14917 comment skip trees with the COMMENT keyword
14918 function or Emacs Lisp form:
14919 will be used as value for `org-agenda-skip-function', so
14920 whenever the function returns a position, FUNC will not be
14921 called for that entry and search will continue from the
14922 position returned
14924 If your function needs to retrieve the tags including inherited tags
14925 at the *current* entry, you can use the value of the variable
14926 `org-scanner-tags' which will be much faster than getting the value
14927 with `org-get-tags-at'. If your function gets properties with
14928 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14929 to t around the call to `org-entry-properties' to get the same speedup.
14930 Note that if your function moves around to retrieve tags and properties at
14931 a *different* entry, you cannot use these techniques."
14932 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14933 (not (org-region-active-p)))
14934 (let* ((org-agenda-archives-mode nil) ; just to make sure
14935 (org-agenda-skip-archived-trees (memq 'archive skip))
14936 (org-agenda-skip-comment-trees (memq 'comment skip))
14937 (org-agenda-skip-function
14938 (car (org-delete-all '(comment archive) skip)))
14939 (org-tags-match-list-sublevels t)
14940 (start-level (eq scope 'region-start-level))
14941 matcher file res
14942 org-todo-keywords-for-agenda
14943 org-done-keywords-for-agenda
14944 org-todo-keyword-alist-for-agenda
14945 org-drawers-for-agenda
14946 org-tag-alist-for-agenda
14947 todo-only)
14949 (cond
14950 ((eq match t) (setq matcher t))
14951 ((eq match nil) (setq matcher t))
14952 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14954 (save-window-excursion
14955 (save-restriction
14956 (cond ((eq scope 'tree)
14957 (org-back-to-heading t)
14958 (org-narrow-to-subtree)
14959 (setq scope nil))
14960 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14961 (org-region-active-p))
14962 ;; If needed, set start-level to a string like "2"
14963 (when start-level
14964 (save-excursion
14965 (goto-char (region-beginning))
14966 (unless (org-at-heading-p) (outline-next-heading))
14967 (setq start-level (org-current-level))))
14968 (narrow-to-region (region-beginning)
14969 (save-excursion
14970 (goto-char (region-end))
14971 (unless (and (bolp) (org-at-heading-p))
14972 (outline-next-heading))
14973 (point)))
14974 (setq scope nil)))
14976 (if (not scope)
14977 (progn
14978 (org-agenda-prepare-buffers
14979 (list (buffer-file-name (current-buffer))))
14980 (setq res (org-scan-tags func matcher todo-only start-level)))
14981 ;; Get the right scope
14982 (cond
14983 ((and scope (listp scope) (symbolp (car scope)))
14984 (setq scope (eval scope)))
14985 ((eq scope 'agenda)
14986 (setq scope (org-agenda-files t)))
14987 ((eq scope 'agenda-with-archives)
14988 (setq scope (org-agenda-files t))
14989 (setq scope (org-add-archive-files scope)))
14990 ((eq scope 'file)
14991 (setq scope (list (buffer-file-name))))
14992 ((eq scope 'file-with-archives)
14993 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14994 (org-agenda-prepare-buffers scope)
14995 (while (setq file (pop scope))
14996 (with-current-buffer (org-find-base-buffer-visiting file)
14997 (save-excursion
14998 (save-restriction
14999 (widen)
15000 (goto-char (point-min))
15001 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
15002 res)))
15004 ;;;; Properties
15006 ;;; Setting and retrieving properties
15008 (defconst org-special-properties
15009 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
15010 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
15011 "The special properties valid in Org-mode.
15013 These are properties that are not defined in the property drawer,
15014 but in some other way.")
15016 (defconst org-default-properties
15017 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15018 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15019 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15020 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15021 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
15022 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15023 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15024 "Some properties that are used by Org-mode for various purposes.
15025 Being in this list makes sure that they are offered for completion.")
15027 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
15028 "Regular expression matching the first line of a property drawer.")
15030 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
15031 "Regular expression matching the last line of a property drawer.")
15033 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
15034 "Regular expression matching the first line of a property drawer.")
15036 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
15037 "Regular expression matching the first line of a property drawer.")
15039 (defconst org-property-drawer-re
15040 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
15041 org-property-end-re "\\)\n?")
15042 "Matches an entire property drawer.")
15044 (defconst org-clock-drawer-re
15045 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
15046 org-property-end-re "\\)\n?")
15047 "Matches an entire clock drawer.")
15049 (defun org-property-action ()
15050 "Do an action on properties."
15051 (interactive)
15052 (let (c)
15053 (org-at-property-p)
15054 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15055 (setq c (read-char-exclusive))
15056 (cond
15057 ((equal c ?s)
15058 (call-interactively 'org-set-property))
15059 ((equal c ?d)
15060 (call-interactively 'org-delete-property))
15061 ((equal c ?D)
15062 (call-interactively 'org-delete-property-globally))
15063 ((equal c ?c)
15064 (call-interactively 'org-compute-property-at-point))
15065 (t (user-error "No such property action %c" c)))))
15067 (defun org-inc-effort ()
15068 "Increment the value of the effort property in the current entry."
15069 (interactive)
15070 (org-set-effort nil t))
15072 (defvar org-clock-effort) ;; Defined in org-clock.el
15073 (defvar org-clock-current-task) ;; Defined in org-clock.el
15074 (defun org-set-effort (&optional value increment)
15075 "Set the effort property of the current entry.
15076 With numerical prefix arg, use the nth allowed value, 0 stands for the
15077 10th allowed value.
15079 When INCREMENT is non-nil, set the property to the next allowed value."
15080 (interactive "P")
15081 (if (equal value 0) (setq value 10))
15082 (let* ((completion-ignore-case t)
15083 (prop org-effort-property)
15084 (cur (org-entry-get nil prop))
15085 (allowed (org-property-get-allowed-values nil prop 'table))
15086 (existing (mapcar 'list (org-property-values prop)))
15087 (heading (nth 4 (org-heading-components)))
15089 (val (cond
15090 ((stringp value) value)
15091 ((and allowed (integerp value))
15092 (or (car (nth (1- value) allowed))
15093 (car (org-last allowed))))
15094 ((and allowed increment)
15095 (or (caadr (member (list cur) allowed))
15096 (user-error "Allowed effort values are not set")))
15097 (allowed
15098 (message "Select 1-9,0, [RET%s]: %s"
15099 (if cur (concat "=" cur) "")
15100 (mapconcat 'car allowed " "))
15101 (setq rpl (read-char-exclusive))
15102 (if (equal rpl ?\r)
15104 (setq rpl (- rpl ?0))
15105 (if (equal rpl 0) (setq rpl 10))
15106 (if (and (> rpl 0) (<= rpl (length allowed)))
15107 (car (nth (1- rpl) allowed))
15108 (org-completing-read "Effort: " allowed nil))))
15110 (let (org-completion-use-ido org-completion-use-iswitchb)
15111 (org-completing-read
15112 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15113 (concat "[" cur "]") "")
15114 ": ")
15115 existing nil nil "" nil cur))))))
15116 (unless (equal (org-entry-get nil prop) val)
15117 (org-entry-put nil prop val))
15118 (save-excursion
15119 (org-back-to-heading t)
15120 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
15121 (when (string= heading org-clock-current-task)
15122 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
15123 (org-clock-update-mode-line))
15124 (message "%s is now %s" prop val)))
15126 (defun org-at-property-p ()
15127 "Is cursor inside a property drawer?"
15128 (save-excursion
15129 (when (equal 'node-property (car (org-element-at-point)))
15130 (beginning-of-line 1)
15131 (looking-at org-property-re))))
15133 (defun org-get-property-block (&optional beg end force)
15134 "Return the (beg . end) range of the body of the property drawer.
15135 BEG and END are the beginning and end of the current subtree, or of
15136 the part before the first headline. If they are not given, they will
15137 be found. If the drawer does not exist and FORCE is non-nil, create
15138 the drawer."
15139 (catch 'exit
15140 (save-excursion
15141 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15142 (progn (org-back-to-heading t) (point))))
15143 (end (or end (and (not (outline-next-heading)) (point-max))
15144 (point))))
15145 (goto-char beg)
15146 (if (re-search-forward org-property-start-re end t)
15147 (setq beg (1+ (match-end 0)))
15148 (if force
15149 (save-excursion
15150 (org-insert-property-drawer)
15151 (setq end (progn (outline-next-heading) (point))))
15152 (throw 'exit nil))
15153 (goto-char beg)
15154 (if (re-search-forward org-property-start-re end t)
15155 (setq beg (1+ (match-end 0)))))
15156 (if (re-search-forward org-property-end-re end t)
15157 (setq end (match-beginning 0))
15158 (or force (throw 'exit nil))
15159 (goto-char beg)
15160 (setq end beg)
15161 (org-indent-line)
15162 (insert ":END:\n"))
15163 (cons beg end)))))
15165 (defun org-entry-properties (&optional pom which specific)
15166 "Get all properties of the entry at point-or-marker POM.
15167 This includes the TODO keyword, the tags, time strings for deadline,
15168 scheduled, and clocking, and any additional properties defined in the
15169 entry. The return value is an alist, keys may occur multiple times
15170 if the property key was used several times.
15171 POM may also be nil, in which case the current entry is used.
15172 If WHICH is nil or `all', get all properties. If WHICH is
15173 `special' or `standard', only get that subclass. If WHICH
15174 is a string only get exactly this property. SPECIFIC can be a string, the
15175 specific property we are interested in. Specifying it can speed
15176 things up because then unnecessary parsing is avoided."
15177 (setq which (or which 'all))
15178 (org-with-point-at pom
15179 (let ((clockstr (substring org-clock-string 0 -1))
15180 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15181 (case-fold-search nil)
15182 beg end range props sum-props key key1 value string clocksum clocksumt)
15183 (save-excursion
15184 (when (condition-case nil
15185 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
15186 (error nil))
15187 (setq beg (point))
15188 (setq sum-props (get-text-property (point) 'org-summaries))
15189 (setq clocksum (get-text-property (point) :org-clock-minutes)
15190 clocksumt (get-text-property (point) :org-clock-minutes-today))
15191 (outline-next-heading)
15192 (setq end (point))
15193 (when (memq which '(all special))
15194 ;; Get the special properties, like TODO and tags
15195 (goto-char beg)
15196 (when (and (or (not specific) (string= specific "TODO"))
15197 (looking-at org-todo-line-regexp) (match-end 2))
15198 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15199 (when (and (or (not specific) (string= specific "PRIORITY"))
15200 (looking-at org-priority-regexp))
15201 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15202 (when (or (not specific) (string= specific "FILE"))
15203 (push (cons "FILE" buffer-file-name) props))
15204 (when (and (or (not specific) (string= specific "TAGS"))
15205 (setq value (org-get-tags-string))
15206 (string-match "\\S-" value))
15207 (push (cons "TAGS" value) props))
15208 (when (and (or (not specific) (string= specific "ALLTAGS"))
15209 (setq value (org-get-tags-at)))
15210 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15211 ":"))
15212 props))
15213 (when (or (not specific) (string= specific "BLOCKED"))
15214 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15215 (when (or (not specific)
15216 (member specific
15217 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15218 "TIMESTAMP" "TIMESTAMP_IA")))
15219 (catch 'match
15220 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15221 (setq key (if (match-end 1)
15222 (substring (org-match-string-no-properties 1)
15223 0 -1))
15224 string (if (equal key clockstr)
15225 (org-trim
15226 (buffer-substring-no-properties
15227 (match-beginning 3) (goto-char
15228 (point-at-eol))))
15229 (substring (org-match-string-no-properties 3)
15230 1 -1)))
15231 ;; Get the correct property name from the key. This is
15232 ;; necessary if the user has configured time keywords.
15233 (setq key1 (concat key ":"))
15234 (cond
15235 ((not key)
15236 (setq key
15237 (if (= (char-after (match-beginning 3)) ?\[)
15238 "TIMESTAMP_IA" "TIMESTAMP")))
15239 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15240 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15241 ((equal key1 org-closed-string) (setq key "CLOSED"))
15242 ((equal key1 org-clock-string) (setq key "CLOCK")))
15243 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15244 (progn
15245 (push (cons key string) props)
15246 ;; no need to search further if match is found
15247 (throw 'match t))
15248 (when (or (equal key "CLOCK") (not (assoc key props)))
15249 (push (cons key string) props)))))))
15251 (when (memq which '(all standard))
15252 ;; Get the standard properties, like :PROP: ...
15253 (setq range (org-get-property-block beg end))
15254 (when range
15255 (goto-char (car range))
15256 (while (re-search-forward org-property-re
15257 (cdr range) t)
15258 (setq key (org-match-string-no-properties 2)
15259 value (org-trim (or (org-match-string-no-properties 3) "")))
15260 (unless (member key excluded)
15261 (push (cons key (or value "")) props)))))
15262 (if clocksum
15263 (push (cons "CLOCKSUM"
15264 (org-columns-number-to-string (/ (float clocksum) 60.)
15265 'add_times))
15266 props))
15267 (if clocksumt
15268 (push (cons "CLOCKSUM_T"
15269 (org-columns-number-to-string (/ (float clocksumt) 60.)
15270 'add_times))
15271 props))
15272 (unless (assoc "CATEGORY" props)
15273 (push (cons "CATEGORY" (org-get-category)) props))
15274 (append sum-props (nreverse props)))))))
15276 (defun org-entry-get (pom property &optional inherit literal-nil)
15277 "Get value of PROPERTY for entry or content at point-or-marker POM.
15278 If INHERIT is non-nil and the entry does not have the property,
15279 then also check higher levels of the hierarchy.
15280 If INHERIT is the symbol `selective', use inheritance only if the setting
15281 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15282 If the property is present but empty, the return value is the empty string.
15283 If the property is not present at all, nil is returned.
15285 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15286 do not interpret it as the list atom nil. This is used for inheritance
15287 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15288 (org-with-point-at pom
15289 (if (and inherit (if (eq inherit 'selective)
15290 (org-property-inherit-p property)
15292 (org-entry-get-with-inheritance property literal-nil)
15293 (if (member property org-special-properties)
15294 ;; We need a special property. Use `org-entry-properties' to
15295 ;; retrieve it, but specify the wanted property
15296 (cdr (assoc property (org-entry-properties nil 'special property)))
15297 (let ((range (org-get-property-block)))
15298 (when (and range (not (eq (car range) (cdr range))))
15299 (let* ((props (list (or (assoc property org-file-properties)
15300 (assoc property org-global-properties)
15301 (assoc property org-global-properties-fixed))))
15302 (ap (lambda (key)
15303 (when (re-search-forward
15304 (org-re-property key) (cdr range) t)
15305 (setq props
15306 (org-update-property-plist
15308 (if (match-end 3)
15309 (org-match-string-no-properties 3) "")
15310 props)))))
15311 val)
15312 (goto-char (car range))
15313 (funcall ap property)
15314 (goto-char (car range))
15315 (while (funcall ap (concat property "+")))
15316 (setq val (cdr (assoc property props)))
15317 (when val (if literal-nil val (org-not-nil val))))))))))
15319 (defun org-property-or-variable-value (var &optional inherit)
15320 "Check if there is a property fixing the value of VAR.
15321 If yes, return this value. If not, return the current value of the variable."
15322 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15323 (if (and prop (stringp prop) (string-match "\\S-" prop))
15324 (read prop)
15325 (symbol-value var))))
15327 (defun org-entry-delete (pom property &optional delete-empty-drawer)
15328 "Delete the property PROPERTY from entry at point-or-marker POM.
15329 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15330 an empty drawer to delete."
15331 (org-with-point-at pom
15332 (if (member property org-special-properties)
15333 nil ; cannot delete these properties.
15334 (let ((range (org-get-property-block)))
15335 (if (and range
15336 (goto-char (car range))
15337 (re-search-forward
15338 (org-re-property property)
15339 (cdr range) t))
15340 (progn
15341 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15342 (and delete-empty-drawer
15343 (org-remove-empty-drawer-at
15344 delete-empty-drawer (car range)))
15346 nil)))))
15348 ;; Multi-values properties are properties that contain multiple values
15349 ;; These values are assumed to be single words, separated by whitespace.
15350 (defun org-entry-add-to-multivalued-property (pom property value)
15351 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15352 (let* ((old (org-entry-get pom property))
15353 (values (and old (org-split-string old "[ \t]"))))
15354 (setq value (org-entry-protect-space value))
15355 (unless (member value values)
15356 (setq values (append values (list value)))
15357 (org-entry-put pom property
15358 (mapconcat 'identity values " ")))))
15360 (defun org-entry-remove-from-multivalued-property (pom property value)
15361 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15362 (let* ((old (org-entry-get pom property))
15363 (values (and old (org-split-string old "[ \t]"))))
15364 (setq value (org-entry-protect-space value))
15365 (when (member value values)
15366 (setq values (delete value values))
15367 (org-entry-put pom property
15368 (mapconcat 'identity values " ")))))
15370 (defun org-entry-member-in-multivalued-property (pom property value)
15371 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15372 (let* ((old (org-entry-get pom property))
15373 (values (and old (org-split-string old "[ \t]"))))
15374 (setq value (org-entry-protect-space value))
15375 (member value values)))
15377 (defun org-entry-get-multivalued-property (pom property)
15378 "Return a list of values in a multivalued property."
15379 (let* ((value (org-entry-get pom property))
15380 (values (and value (org-split-string value "[ \t]"))))
15381 (mapcar 'org-entry-restore-space values)))
15383 (defun org-entry-put-multivalued-property (pom property &rest values)
15384 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15385 VALUES should be a list of strings. Spaces will be protected."
15386 (org-entry-put pom property
15387 (mapconcat 'org-entry-protect-space values " "))
15388 (let* ((value (org-entry-get pom property))
15389 (values (and value (org-split-string value "[ \t]"))))
15390 (mapcar 'org-entry-restore-space values)))
15392 (defun org-entry-protect-space (s)
15393 "Protect spaces and newline in string S."
15394 (while (string-match " " s)
15395 (setq s (replace-match "%20" t t s)))
15396 (while (string-match "\n" s)
15397 (setq s (replace-match "%0A" t t s)))
15400 (defun org-entry-restore-space (s)
15401 "Restore spaces and newline in string S."
15402 (while (string-match "%20" s)
15403 (setq s (replace-match " " t t s)))
15404 (while (string-match "%0A" s)
15405 (setq s (replace-match "\n" t t s)))
15408 (defvar org-entry-property-inherited-from (make-marker)
15409 "Marker pointing to the entry from where a property was inherited.
15410 Each call to `org-entry-get-with-inheritance' will set this marker to the
15411 location of the entry where the inheritance search matched. If there was
15412 no match, the marker will point nowhere.
15413 Note that also `org-entry-get' calls this function, if the INHERIT flag
15414 is set.")
15416 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15417 "Get PROPERTY of entry or content at point, search higher levels if needed.
15418 The search will stop at the first ancestor which has the property defined.
15419 If the value found is \"nil\", return nil to show that the property
15420 should be considered as undefined (this is the meaning of nil here).
15421 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15422 (move-marker org-entry-property-inherited-from nil)
15423 (let (tmp)
15424 (save-excursion
15425 (save-restriction
15426 (widen)
15427 (catch 'ex
15428 (while t
15429 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
15430 (or (ignore-errors (org-back-to-heading t))
15431 (goto-char (point-min)))
15432 (move-marker org-entry-property-inherited-from (point))
15433 (throw 'ex tmp))
15434 (or (ignore-errors (org-up-heading-safe))
15435 (throw 'ex nil))))))
15436 (setq tmp (or tmp
15437 (cdr (assoc property org-file-properties))
15438 (cdr (assoc property org-global-properties))
15439 (cdr (assoc property org-global-properties-fixed))))
15440 (if literal-nil tmp (org-not-nil tmp))))
15442 (defvar org-property-changed-functions nil
15443 "Hook called when the value of a property has changed.
15444 Each hook function should accept two arguments, the name of the property
15445 and the new value.")
15447 (defun org-entry-put (pom property value)
15448 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15449 (org-with-point-at pom
15450 (org-back-to-heading t)
15451 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15452 range)
15453 (cond
15454 ((equal property "TODO")
15455 (when (and (stringp value) (string-match "\\S-" value)
15456 (not (member value org-todo-keywords-1)))
15457 (user-error "\"%s\" is not a valid TODO state" value))
15458 (if (or (not value)
15459 (not (string-match "\\S-" value)))
15460 (setq value 'none))
15461 (org-todo value)
15462 (org-set-tags nil 'align))
15463 ((equal property "PRIORITY")
15464 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15465 (string-to-char value) ?\ ))
15466 (org-set-tags nil 'align))
15467 ((equal property "CLOCKSUM")
15468 (if (not (re-search-forward
15469 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15470 (error "Cannot find a clock log")
15471 (goto-char (- (match-end 1) 2))
15472 (cond
15473 ((eq value 'earlier) (org-timestamp-down))
15474 ((eq value 'later) (org-timestamp-up)))
15475 (org-clock-sum-current-item)))
15476 ((equal property "SCHEDULED")
15477 (if (re-search-forward org-scheduled-time-regexp end t)
15478 (cond
15479 ((eq value 'earlier) (org-timestamp-change -1 'day))
15480 ((eq value 'later) (org-timestamp-change 1 'day))
15481 (t (call-interactively 'org-schedule)))
15482 (call-interactively 'org-schedule)))
15483 ((equal property "DEADLINE")
15484 (if (re-search-forward org-deadline-time-regexp end t)
15485 (cond
15486 ((eq value 'earlier) (org-timestamp-change -1 'day))
15487 ((eq value 'later) (org-timestamp-change 1 'day))
15488 (t (call-interactively 'org-deadline)))
15489 (call-interactively 'org-deadline)))
15490 ((member property org-special-properties)
15491 (error "The %s property can not yet be set with `org-entry-put'"
15492 property))
15493 (t ; a non-special property
15494 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15495 (setq range (org-get-property-block beg end 'force))
15496 (goto-char (car range))
15497 (if (re-search-forward
15498 (org-re-property property) (cdr range) t)
15499 (progn
15500 (delete-region (match-beginning 0) (match-end 0))
15501 (goto-char (match-beginning 0)))
15502 (goto-char (cdr range))
15503 (insert "\n")
15504 (backward-char 1)
15505 (org-indent-line))
15506 (insert ":" property ":")
15507 (and value (insert " " value))
15508 (org-indent-line)))))
15509 (run-hook-with-args 'org-property-changed-functions property value)))
15511 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15512 "Get all property keys in the current buffer.
15513 With INCLUDE-SPECIALS, also list the special properties that reflect things
15514 like tags and TODO state.
15515 With INCLUDE-DEFAULTS, also include properties that has special meaning
15516 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15517 and others.
15518 With INCLUDE-COLUMNS, also include property names given in COLUMN
15519 formats in the current buffer."
15520 (let (rtn range cfmt s p)
15521 (save-excursion
15522 (save-restriction
15523 (widen)
15524 (goto-char (point-min))
15525 (while (re-search-forward org-property-start-re nil t)
15526 (setq range (org-get-property-block))
15527 (goto-char (car range))
15528 (while (re-search-forward org-property-re
15529 (cdr range) t)
15530 (add-to-list 'rtn (org-match-string-no-properties 2)))
15531 (outline-next-heading))))
15533 (when include-specials
15534 (setq rtn (append org-special-properties rtn)))
15536 (when include-defaults
15537 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15538 (add-to-list 'rtn org-effort-property))
15540 (when include-columns
15541 (save-excursion
15542 (save-restriction
15543 (widen)
15544 (goto-char (point-min))
15545 (while (re-search-forward
15546 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15547 nil t)
15548 (setq cfmt (match-string 2) s 0)
15549 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15550 cfmt s)
15551 (setq s (match-end 0)
15552 p (match-string 1 cfmt))
15553 (unless (or (equal p "ITEM")
15554 (member p org-special-properties))
15555 (add-to-list 'rtn (match-string 1 cfmt))))))))
15557 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15559 (defun org-property-values (key)
15560 "Return a list of all values of property KEY in the current buffer."
15561 (save-excursion
15562 (save-restriction
15563 (widen)
15564 (goto-char (point-min))
15565 (let ((re (org-re-property key))
15566 values)
15567 (while (re-search-forward re nil t)
15568 (add-to-list 'values (org-trim (match-string 3))))
15569 (delete "" values)))))
15571 (defun org-insert-property-drawer ()
15572 "Insert a property drawer into the current entry."
15573 (org-back-to-heading t)
15574 (looking-at org-outline-regexp)
15575 (let ((indent (if org-adapt-indentation
15576 (- (match-end 0) (match-beginning 0))
15578 (beg (point))
15579 (re (concat "^[ \t]*" org-keyword-time-regexp))
15580 end hiddenp)
15581 (outline-next-heading)
15582 (setq end (point))
15583 (goto-char beg)
15584 (while (re-search-forward re end t))
15585 (setq hiddenp (outline-invisible-p))
15586 (end-of-line 1)
15587 (and (equal (char-after) ?\n) (forward-char 1))
15588 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15589 (if (member (match-string 1) '("CLOCK:" ":END:"))
15590 ;; just skip this line
15591 (beginning-of-line 2)
15592 ;; Drawer start, find the end
15593 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15594 (beginning-of-line 1)))
15595 (org-skip-over-state-notes)
15596 (skip-chars-backward " \t\n\r")
15597 (if (eq (char-before) ?*) (forward-char 1))
15598 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15599 (beginning-of-line 0)
15600 (org-indent-to-column indent)
15601 (beginning-of-line 2)
15602 (org-indent-to-column indent)
15603 (beginning-of-line 0)
15604 (if hiddenp
15605 (save-excursion
15606 (org-back-to-heading t)
15607 (hide-entry))
15608 (org-flag-drawer t))))
15610 (defun org-insert-drawer (&optional arg drawer)
15611 "Insert a drawer at point.
15613 Optional argument DRAWER, when non-nil, is a string representing
15614 drawer's name. Otherwise, the user is prompted for a name.
15616 If a region is active, insert the drawer around that region
15617 instead.
15619 Point is left between drawer's boundaries."
15620 (interactive "P")
15621 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15622 "LOGBOOK"))
15623 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15624 ;; internally by Org. They are meant to be inserted
15625 ;; automatically.
15626 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15627 ;; Remove system drawers from list. Note: For some reason,
15628 ;; `org-completing-read' ignores the predicate while
15629 ;; `completing-read' handles it fine.
15630 (drawer (if arg "PROPERTIES"
15631 (or drawer
15632 (completing-read
15633 "Drawer: " org-drawers
15634 (lambda (d) (not (member d system-drawers))))))))
15635 (cond
15636 ;; With C-u, fall back on `org-insert-property-drawer'
15637 (arg (org-insert-property-drawer))
15638 ;; With an active region, insert a drawer at point.
15639 ((not (org-region-active-p))
15640 (progn
15641 (unless (bolp) (insert "\n"))
15642 (insert (format ":%s:\n\n:END:\n" drawer))
15643 (forward-line -2)))
15644 ;; Otherwise, insert the drawer at point
15646 (let ((rbeg (region-beginning))
15647 (rend (copy-marker (region-end))))
15648 (unwind-protect
15649 (progn
15650 (goto-char rbeg)
15651 (beginning-of-line)
15652 (when (save-excursion
15653 (re-search-forward org-outline-regexp-bol rend t))
15654 (user-error "Drawers cannot contain headlines"))
15655 ;; Position point at the beginning of the first
15656 ;; non-blank line in region. Insert drawer's opening
15657 ;; there, then indent it.
15658 (org-skip-whitespace)
15659 (beginning-of-line)
15660 (insert ":" drawer ":\n")
15661 (forward-line -1)
15662 (indent-for-tab-command)
15663 ;; Move point to the beginning of the first blank line
15664 ;; after the last non-blank line in region. Insert
15665 ;; drawer's closing, then indent it.
15666 (goto-char rend)
15667 (skip-chars-backward " \r\t\n")
15668 (insert "\n:END:")
15669 (deactivate-mark t)
15670 (indent-for-tab-command)
15671 (unless (eolp) (insert "\n")))
15672 ;; Clear marker, whatever the outcome of insertion is.
15673 (set-marker rend nil)))))))
15675 (defvar org-property-set-functions-alist nil
15676 "Property set function alist.
15677 Each entry should have the following format:
15679 (PROPERTY . READ-FUNCTION)
15681 The read function will be called with the same argument as
15682 `org-completing-read'.")
15684 (defun org-set-property-function (property)
15685 "Get the function that should be used to set PROPERTY.
15686 This is computed according to `org-property-set-functions-alist'."
15687 (or (cdr (assoc property org-property-set-functions-alist))
15688 'org-completing-read))
15690 (defun org-read-property-value (property)
15691 "Read PROPERTY value from user."
15692 (let* ((completion-ignore-case t)
15693 (allowed (org-property-get-allowed-values nil property 'table))
15694 (cur (org-entry-get nil property))
15695 (prompt (concat property " value"
15696 (if (and cur (string-match "\\S-" cur))
15697 (concat " [" cur "]") "") ": "))
15698 (set-function (org-set-property-function property))
15699 (val (if allowed
15700 (funcall set-function prompt allowed nil
15701 (not (get-text-property 0 'org-unrestricted
15702 (caar allowed))))
15703 (let (org-completion-use-ido org-completion-use-iswitchb)
15704 (funcall set-function prompt
15705 (mapcar 'list (org-property-values property))
15706 nil nil "" nil cur)))))
15707 (if (equal val "")
15709 val)))
15711 (defvar org-last-set-property nil)
15712 (defvar org-last-set-property-value nil)
15713 (defun org-read-property-name ()
15714 "Read a property name."
15715 (let* ((completion-ignore-case t)
15716 (keys (org-buffer-property-keys nil t t))
15717 (default-prop (or (save-excursion
15718 (save-match-data
15719 (beginning-of-line)
15720 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15721 (null (string= (match-string 1) "END"))
15722 (match-string 1))))
15723 org-last-set-property))
15724 (property (org-icompleting-read
15725 (concat "Property"
15726 (if default-prop (concat " [" default-prop "]") "")
15727 ": ")
15728 (mapcar 'list keys)
15729 nil nil nil nil
15730 default-prop)))
15731 (if (member property keys)
15732 property
15733 (or (cdr (assoc (downcase property)
15734 (mapcar (lambda (x) (cons (downcase x) x))
15735 keys)))
15736 property))))
15738 (defun org-set-property-and-value (use-last)
15739 "Allow to set [PROPERTY]: [value] direction from prompt.
15740 When use-default, don't even ask, just use the last
15741 \"[PROPERTY]: [value]\" string from the history."
15742 (interactive "P")
15743 (let* ((completion-ignore-case t)
15744 (pv (or (and use-last org-last-set-property-value)
15745 (org-completing-read
15746 "Enter a \"[Property]: [value]\" pair: "
15747 nil nil nil nil nil
15748 org-last-set-property-value)))
15749 prop val)
15750 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15751 (setq prop (match-string 1 pv)
15752 val (match-string 2 pv))
15753 (org-set-property prop val))))
15755 (defun org-set-property (property value)
15756 "In the current entry, set PROPERTY to VALUE.
15757 When called interactively, this will prompt for a property name, offering
15758 completion on existing and default properties. And then it will prompt
15759 for a value, offering completion either on allowed values (via an inherited
15760 xxx_ALL property) or on existing values in other instances of this property
15761 in the current file."
15762 (interactive (list nil nil))
15763 (let* ((property (or property (org-read-property-name)))
15764 (value (or value (org-read-property-value property)))
15765 (fn (cdr (assoc property org-properties-postprocess-alist))))
15766 (setq org-last-set-property property)
15767 (setq org-last-set-property-value (concat property ": " value))
15768 ;; Possibly postprocess the inserted value:
15769 (when fn (setq value (funcall fn value)))
15770 (unless (equal (org-entry-get nil property) value)
15771 (org-entry-put nil property value))))
15773 (defun org-delete-property (property &optional delete-empty-drawer)
15774 "In the current entry, delete PROPERTY.
15775 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15776 an empty drawer to delete."
15777 (interactive
15778 (let* ((completion-ignore-case t)
15779 (prop (org-icompleting-read "Property: "
15780 (org-entry-properties nil 'standard))))
15781 (list prop)))
15782 (message "Property %s %s" property
15783 (if (org-entry-delete nil property delete-empty-drawer)
15784 "deleted"
15785 "was not present in the entry")))
15787 (defun org-delete-property-globally (property)
15788 "Remove PROPERTY globally, from all entries."
15789 (interactive
15790 (let* ((completion-ignore-case t)
15791 (prop (org-icompleting-read
15792 "Globally remove property: "
15793 (mapcar 'list (org-buffer-property-keys)))))
15794 (list prop)))
15795 (save-excursion
15796 (save-restriction
15797 (widen)
15798 (goto-char (point-min))
15799 (let ((cnt 0))
15800 (while (re-search-forward
15801 (org-re-property property)
15802 nil t)
15803 (setq cnt (1+ cnt))
15804 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15805 (message "Property \"%s\" removed from %d entries" property cnt)))))
15807 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15809 (defun org-compute-property-at-point ()
15810 "Compute the property at point.
15811 This looks for an enclosing column format, extracts the operator and
15812 then applies it to the property in the column format's scope."
15813 (interactive)
15814 (unless (org-at-property-p)
15815 (user-error "Not at a property"))
15816 (let ((prop (org-match-string-no-properties 2)))
15817 (org-columns-get-format-and-top-level)
15818 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15819 (user-error "No operator defined for property %s" prop))
15820 (org-columns-compute prop)))
15822 (defvar org-property-allowed-value-functions nil
15823 "Hook for functions supplying allowed values for a specific property.
15824 The functions must take a single argument, the name of the property, and
15825 return a flat list of allowed values. If \":ETC\" is one of
15826 the values, this means that these values are intended as defaults for
15827 completion, but that other values should be allowed too.
15828 The functions must return nil if they are not responsible for this
15829 property.")
15831 (defun org-property-get-allowed-values (pom property &optional table)
15832 "Get allowed values for the property PROPERTY.
15833 When TABLE is non-nil, return an alist that can directly be used for
15834 completion."
15835 (let (vals)
15836 (cond
15837 ((equal property "TODO")
15838 (setq vals (org-with-point-at pom
15839 (append org-todo-keywords-1 '("")))))
15840 ((equal property "PRIORITY")
15841 (let ((n org-lowest-priority))
15842 (while (>= n org-highest-priority)
15843 (push (char-to-string n) vals)
15844 (setq n (1- n)))))
15845 ((member property org-special-properties))
15846 ((setq vals (run-hook-with-args-until-success
15847 'org-property-allowed-value-functions property)))
15849 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15850 (when (and vals (string-match "\\S-" vals))
15851 (setq vals (car (read-from-string (concat "(" vals ")"))))
15852 (setq vals (mapcar (lambda (x)
15853 (cond ((stringp x) x)
15854 ((numberp x) (number-to-string x))
15855 ((symbolp x) (symbol-name x))
15856 (t "???")))
15857 vals)))))
15858 (when (member ":ETC" vals)
15859 (setq vals (remove ":ETC" vals))
15860 (org-add-props (car vals) '(org-unrestricted t)))
15861 (if table (mapcar 'list vals) vals)))
15863 (defun org-property-previous-allowed-value (&optional previous)
15864 "Switch to the next allowed value for this property."
15865 (interactive)
15866 (org-property-next-allowed-value t))
15868 (defun org-property-next-allowed-value (&optional previous)
15869 "Switch to the next allowed value for this property."
15870 (interactive)
15871 (unless (org-at-property-p)
15872 (user-error "Not at a property"))
15873 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15874 (key (match-string 2))
15875 (value (match-string 3))
15876 (allowed (or (org-property-get-allowed-values (point) key)
15877 (and (member value '("[ ]" "[-]" "[X]"))
15878 '("[ ]" "[X]"))))
15879 (heading (save-match-data (nth 4 (org-heading-components))))
15880 nval)
15881 (unless allowed
15882 (user-error "Allowed values for this property have not been defined"))
15883 (if previous (setq allowed (reverse allowed)))
15884 (if (member value allowed)
15885 (setq nval (car (cdr (member value allowed)))))
15886 (setq nval (or nval (car allowed)))
15887 (if (equal nval value)
15888 (user-error "Only one allowed value for this property"))
15889 (org-at-property-p)
15890 (replace-match (concat " :" key ": " nval) t t)
15891 (org-indent-line)
15892 (beginning-of-line 1)
15893 (skip-chars-forward " \t")
15894 (when (equal prop org-effort-property)
15895 (save-excursion
15896 (org-back-to-heading t)
15897 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
15898 (when (string= org-clock-current-task heading)
15899 (setq org-clock-effort nval)
15900 (org-clock-update-mode-line)))
15901 (run-hook-with-args 'org-property-changed-functions key nval)))
15903 (defun org-find-olp (path &optional this-buffer)
15904 "Return a marker pointing to the entry at outline path OLP.
15905 If anything goes wrong, throw an error.
15906 You can wrap this call to catch the error like this:
15908 (condition-case msg
15909 (org-mobile-locate-entry (match-string 4))
15910 (error (nth 1 msg)))
15912 The return value will then be either a string with the error message,
15913 or a marker if everything is OK.
15915 If THIS-BUFFER is set, the outline path does not contain a file,
15916 only headings."
15917 (let* ((file (if this-buffer buffer-file-name (pop path)))
15918 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15919 (level 1)
15920 (lmin 1)
15921 (lmax 1)
15922 limit re end found pos heading cnt flevel)
15923 (unless buffer (error "File not found :%s" file))
15924 (with-current-buffer buffer
15925 (save-excursion
15926 (save-restriction
15927 (widen)
15928 (setq limit (point-max))
15929 (goto-char (point-min))
15930 (while (setq heading (pop path))
15931 (setq re (format org-complex-heading-regexp-format
15932 (regexp-quote heading)))
15933 (setq cnt 0 pos (point))
15934 (while (re-search-forward re end t)
15935 (setq level (- (match-end 1) (match-beginning 1)))
15936 (if (and (>= level lmin) (<= level lmax))
15937 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15938 (when (= cnt 0) (error "Heading not found on level %d: %s"
15939 lmax heading))
15940 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15941 lmax heading))
15942 (goto-char found)
15943 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15944 (setq end (save-excursion (org-end-of-subtree t t))))
15945 (when (org-at-heading-p)
15946 (point-marker)))))))
15948 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15949 "Find node HEADING in BUFFER.
15950 Return a marker to the heading if it was found, or nil if not.
15951 If POS-ONLY is set, return just the position instead of a marker.
15953 The heading text must match exact, but it may have a TODO keyword,
15954 a priority cookie and tags in the standard locations."
15955 (with-current-buffer (or buffer (current-buffer))
15956 (save-excursion
15957 (save-restriction
15958 (widen)
15959 (goto-char (point-min))
15960 (let (case-fold-search)
15961 (if (re-search-forward
15962 (format org-complex-heading-regexp-format
15963 (regexp-quote heading)) nil t)
15964 (if pos-only
15965 (match-beginning 0)
15966 (move-marker (make-marker) (match-beginning 0)))))))))
15968 (defun org-find-exact-heading-in-directory (heading &optional dir)
15969 "Find Org node headline HEADING in all .org files in directory DIR.
15970 When the target headline is found, return a marker to this location."
15971 (let ((files (directory-files (or dir default-directory)
15972 nil "\\`[^.#].*\\.org\\'"))
15973 file visiting m buffer)
15974 (catch 'found
15975 (while (setq file (pop files))
15976 (message "trying %s" file)
15977 (setq visiting (org-find-base-buffer-visiting file))
15978 (setq buffer (or visiting (find-file-noselect file)))
15979 (setq m (org-find-exact-headline-in-buffer
15980 heading buffer))
15981 (when (and (not m) (not visiting)) (kill-buffer buffer))
15982 (and m (throw 'found m))))))
15984 (defun org-find-entry-with-id (ident)
15985 "Locate the entry that contains the ID property with exact value IDENT.
15986 IDENT can be a string, a symbol or a number, this function will search for
15987 the string representation of it.
15988 Return the position where this entry starts, or nil if there is no such entry."
15989 (interactive "sID: ")
15990 (let ((id (cond
15991 ((stringp ident) ident)
15992 ((symbol-name ident) (symbol-name ident))
15993 ((numberp ident) (number-to-string ident))
15994 (t (error "IDENT %s must be a string, symbol or number" ident))))
15995 (case-fold-search nil))
15996 (save-excursion
15997 (save-restriction
15998 (widen)
15999 (goto-char (point-min))
16000 (when (re-search-forward
16001 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16002 nil t)
16003 (org-back-to-heading t)
16004 (point))))))
16006 ;;;; Timestamps
16008 (defvar org-last-changed-timestamp nil)
16009 (defvar org-last-inserted-timestamp nil
16010 "The last time stamp inserted with `org-insert-time-stamp'.")
16011 (defvar org-time-was-given) ; dynamically scoped parameter
16012 (defvar org-end-time-was-given) ; dynamically scoped parameter
16013 (defvar org-ts-what) ; dynamically scoped parameter
16015 (defun org-time-stamp (arg &optional inactive)
16016 "Prompt for a date/time and insert a time stamp.
16017 If the user specifies a time like HH:MM or if this command is
16018 called with at least one prefix argument, the time stamp contains
16019 the date and the time. Otherwise, only the date is be included.
16021 All parts of a date not specified by the user is filled in from
16022 the current date/time. So if you just press return without
16023 typing anything, the time stamp will represent the current
16024 date/time.
16026 If there is already a timestamp at the cursor, it will be
16027 modified.
16029 With two universal prefix arguments, insert an active timestamp
16030 with the current time without prompting the user."
16031 (interactive "P")
16032 (let* ((ts nil)
16033 (default-time
16034 ;; Default time is either today, or, when entering a range,
16035 ;; the range start.
16036 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16037 (save-excursion
16038 (re-search-backward
16039 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16040 (- (point) 20) t)))
16041 (apply 'encode-time (org-parse-time-string (match-string 1)))
16042 (current-time)))
16043 (default-input (and ts (org-get-compact-tod ts)))
16044 (repeater (save-excursion
16045 (save-match-data
16046 (beginning-of-line)
16047 (when (re-search-forward
16048 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16049 (save-excursion (progn (end-of-line) (point))) t)
16050 (match-string 0)))))
16051 org-time-was-given org-end-time-was-given time)
16052 (cond
16053 ((and (org-at-timestamp-p t)
16054 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16055 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16056 (insert "--")
16057 (setq time (let ((this-command this-command))
16058 (org-read-date arg 'totime nil nil
16059 default-time default-input inactive)))
16060 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16061 ((org-at-timestamp-p t)
16062 (setq time (let ((this-command this-command))
16063 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16064 (when (org-at-timestamp-p t) ; just to get the match data
16065 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16066 (replace-match "")
16067 (setq org-last-changed-timestamp
16068 (org-insert-time-stamp
16069 time (or org-time-was-given arg)
16070 inactive nil nil (list org-end-time-was-given)))
16071 (when repeater (goto-char (1- (point))) (insert " " repeater)
16072 (setq org-last-changed-timestamp
16073 (concat (substring org-last-inserted-timestamp 0 -1)
16074 " " repeater ">"))))
16075 (message "Timestamp updated"))
16076 ((equal arg '(16))
16077 (org-insert-time-stamp (current-time) t))
16079 (setq time (let ((this-command this-command))
16080 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16081 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16082 nil nil (list org-end-time-was-given))))))
16084 ;; FIXME: can we use this for something else, like computing time differences?
16085 (defun org-get-compact-tod (s)
16086 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16087 (let* ((t1 (match-string 1 s))
16088 (h1 (string-to-number (match-string 2 s)))
16089 (m1 (string-to-number (match-string 3 s)))
16090 (t2 (and (match-end 4) (match-string 5 s)))
16091 (h2 (and t2 (string-to-number (match-string 6 s))))
16092 (m2 (and t2 (string-to-number (match-string 7 s))))
16093 dh dm)
16094 (if (not t2)
16096 (setq dh (- h2 h1) dm (- m2 m1))
16097 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16098 (concat t1 "+" (number-to-string dh)
16099 (and (/= 0 dm) (format ":%02d" dm)))))))
16101 (defun org-time-stamp-inactive (&optional arg)
16102 "Insert an inactive time stamp.
16103 An inactive time stamp is enclosed in square brackets instead of angle
16104 brackets. It is inactive in the sense that it does not trigger agenda entries,
16105 does not link to the calendar and cannot be changed with the S-cursor keys.
16106 So these are more for recording a certain time/date."
16107 (interactive "P")
16108 (org-time-stamp arg 'inactive))
16110 (defvar org-date-ovl (make-overlay 1 1))
16111 (overlay-put org-date-ovl 'face 'org-date-selected)
16112 (org-detach-overlay org-date-ovl)
16114 (defvar org-ans1) ; dynamically scoped parameter
16115 (defvar org-ans2) ; dynamically scoped parameter
16117 (defvar org-plain-time-of-day-regexp) ; defined below
16119 (defvar org-overriding-default-time nil) ; dynamically scoped
16120 (defvar org-read-date-overlay nil)
16121 (defvar org-dcst nil) ; dynamically scoped
16122 (defvar org-read-date-history nil)
16123 (defvar org-read-date-final-answer nil)
16124 (defvar org-read-date-analyze-futurep nil)
16125 (defvar org-read-date-analyze-forced-year nil)
16126 (defvar org-read-date-inactive)
16128 (defvar org-read-date-minibuffer-local-map
16129 (let ((map (make-sparse-keymap)))
16130 (set-keymap-parent map minibuffer-local-map)
16131 (org-defkey map (kbd ".")
16132 (lambda () (interactive)
16133 ;; Are we at the beginning of the prompt?
16134 (if (looking-back "^[^:]+: ")
16135 (org-eval-in-calendar '(calendar-goto-today))
16136 (insert "."))))
16137 (org-defkey map (kbd "C-.")
16138 (lambda () (interactive)
16139 (org-eval-in-calendar '(calendar-goto-today))))
16140 (org-defkey map [(meta shift left)]
16141 (lambda () (interactive)
16142 (org-eval-in-calendar '(calendar-backward-month 1))))
16143 (org-defkey map [(meta shift right)]
16144 (lambda () (interactive)
16145 (org-eval-in-calendar '(calendar-forward-month 1))))
16146 (org-defkey map [(meta shift up)]
16147 (lambda () (interactive)
16148 (org-eval-in-calendar '(calendar-backward-year 1))))
16149 (org-defkey map [(meta shift down)]
16150 (lambda () (interactive)
16151 (org-eval-in-calendar '(calendar-forward-year 1))))
16152 (org-defkey map [?\e (shift left)]
16153 (lambda () (interactive)
16154 (org-eval-in-calendar '(calendar-backward-month 1))))
16155 (org-defkey map [?\e (shift right)]
16156 (lambda () (interactive)
16157 (org-eval-in-calendar '(calendar-forward-month 1))))
16158 (org-defkey map [?\e (shift up)]
16159 (lambda () (interactive)
16160 (org-eval-in-calendar '(calendar-backward-year 1))))
16161 (org-defkey map [?\e (shift down)]
16162 (lambda () (interactive)
16163 (org-eval-in-calendar '(calendar-forward-year 1))))
16164 (org-defkey map [(shift up)]
16165 (lambda () (interactive)
16166 (org-eval-in-calendar '(calendar-backward-week 1))))
16167 (org-defkey map [(shift down)]
16168 (lambda () (interactive)
16169 (org-eval-in-calendar '(calendar-forward-week 1))))
16170 (org-defkey map [(shift left)]
16171 (lambda () (interactive)
16172 (org-eval-in-calendar '(calendar-backward-day 1))))
16173 (org-defkey map [(shift right)]
16174 (lambda () (interactive)
16175 (org-eval-in-calendar '(calendar-forward-day 1))))
16176 (org-defkey map "!"
16177 (lambda () (interactive)
16178 (org-eval-in-calendar '(diary-view-entries))
16179 (message "")))
16180 (org-defkey map ">"
16181 (lambda () (interactive)
16182 (org-eval-in-calendar '(scroll-calendar-left 1))))
16183 (org-defkey map "<"
16184 (lambda () (interactive)
16185 (org-eval-in-calendar '(scroll-calendar-right 1))))
16186 (org-defkey map "\C-v"
16187 (lambda () (interactive)
16188 (org-eval-in-calendar
16189 '(calendar-scroll-left-three-months 1))))
16190 (org-defkey map "\M-v"
16191 (lambda () (interactive)
16192 (org-eval-in-calendar
16193 '(calendar-scroll-right-three-months 1))))
16194 map)
16195 "Keymap for minibuffer commands when using `org-read-date'.")
16197 (defun org-read-date (&optional org-with-time to-time from-string prompt
16198 default-time default-input inactive)
16199 "Read a date, possibly a time, and make things smooth for the user.
16200 The prompt will suggest to enter an ISO date, but you can also enter anything
16201 which will at least partially be understood by `parse-time-string'.
16202 Unrecognized parts of the date will default to the current day, month, year,
16203 hour and minute. If this command is called to replace a timestamp at point,
16204 or to enter the second timestamp of a range, the default time is taken
16205 from the existing stamp. Furthermore, the command prefers the future,
16206 so if you are giving a date where the year is not given, and the day-month
16207 combination is already past in the current year, it will assume you
16208 mean next year. For details, see the manual. A few examples:
16210 3-2-5 --> 2003-02-05
16211 feb 15 --> currentyear-02-15
16212 2/15 --> currentyear-02-15
16213 sep 12 9 --> 2009-09-12
16214 12:45 --> today 12:45
16215 22 sept 0:34 --> currentyear-09-22 0:34
16216 12 --> currentyear-currentmonth-12
16217 Fri --> nearest Friday after today
16218 -Tue --> last Tuesday
16219 etc.
16221 Furthermore you can specify a relative date by giving, as the *first* thing
16222 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16223 change in days weeks, months, years.
16224 With a single plus or minus, the date is relative to today. With a double
16225 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16226 +4d --> four days from today
16227 +4 --> same as above
16228 +2w --> two weeks from today
16229 ++5 --> five days from default date
16231 The function understands only English month and weekday abbreviations.
16233 While prompting, a calendar is popped up - you can also select the
16234 date with the mouse (button 1). The calendar shows a period of three
16235 months. To scroll it to other months, use the keys `>' and `<'.
16236 If you don't like the calendar, turn it off with
16237 \(setq org-read-date-popup-calendar nil)
16239 With optional argument TO-TIME, the date will immediately be converted
16240 to an internal time.
16241 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16242 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16243 still enter a time, and this function will inform the calling routine
16244 about this change. The calling routine may then choose to change the
16245 format used to insert the time stamp into the buffer to include the time.
16246 With optional argument FROM-STRING, read from this string instead from
16247 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16248 the time/date that is used for everything that is not specified by the
16249 user."
16250 (require 'parse-time)
16251 (let* ((org-time-stamp-rounding-minutes
16252 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16253 (org-dcst org-display-custom-times)
16254 (ct (org-current-time))
16255 (org-def (or org-overriding-default-time default-time ct))
16256 (org-defdecode (decode-time org-def))
16257 (dummy (progn
16258 (when (< (nth 2 org-defdecode) org-extend-today-until)
16259 (setcar (nthcdr 2 org-defdecode) -1)
16260 (setcar (nthcdr 1 org-defdecode) 59)
16261 (setq org-def (apply 'encode-time org-defdecode)
16262 org-defdecode (decode-time org-def)))))
16263 (mouse-autoselect-window nil) ; Don't let the mouse jump
16264 (calendar-frame-setup nil)
16265 (calendar-setup nil)
16266 (calendar-move-hook nil)
16267 (calendar-view-diary-initially-flag nil)
16268 (calendar-view-holidays-initially-flag nil)
16269 (timestr (format-time-string
16270 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16271 (prompt (concat (if prompt (concat prompt " ") "")
16272 (format "Date+time [%s]: " timestr)))
16273 ans (org-ans0 "") org-ans1 org-ans2 final)
16275 (cond
16276 (from-string (setq ans from-string))
16277 (org-read-date-popup-calendar
16278 (save-excursion
16279 (save-window-excursion
16280 (calendar)
16281 (org-eval-in-calendar '(setq cursor-type nil) t)
16282 (unwind-protect
16283 (progn
16284 (calendar-forward-day (- (time-to-days org-def)
16285 (calendar-absolute-from-gregorian
16286 (calendar-current-date))))
16287 (org-eval-in-calendar nil t)
16288 (let* ((old-map (current-local-map))
16289 (org-replace-disputed-keys nil)
16290 (map (copy-keymap calendar-mode-map))
16291 (minibuffer-local-map
16292 (copy-keymap org-read-date-minibuffer-local-map)))
16293 (org-defkey map (kbd "RET") 'org-calendar-select)
16294 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16295 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16296 (unwind-protect
16297 (progn
16298 (use-local-map map)
16299 (setq org-read-date-inactive inactive)
16300 (add-hook 'post-command-hook 'org-read-date-display)
16301 (setq org-ans0 (read-string prompt default-input
16302 'org-read-date-history nil))
16303 ;; org-ans0: from prompt
16304 ;; org-ans1: from mouse click
16305 ;; org-ans2: from calendar motion
16306 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16307 (remove-hook 'post-command-hook 'org-read-date-display)
16308 (use-local-map old-map)
16309 (when org-read-date-overlay
16310 (delete-overlay org-read-date-overlay)
16311 (setq org-read-date-overlay nil)))))
16312 (bury-buffer "*Calendar*")))))
16314 (t ; Naked prompt only
16315 (unwind-protect
16316 (setq ans (read-string prompt default-input
16317 'org-read-date-history timestr))
16318 (when org-read-date-overlay
16319 (delete-overlay org-read-date-overlay)
16320 (setq org-read-date-overlay nil)))))
16322 (setq final (org-read-date-analyze ans org-def org-defdecode))
16324 (when org-read-date-analyze-forced-year
16325 (message "Year was forced into %s"
16326 (if org-read-date-force-compatible-dates
16327 "compatible range (1970-2037)"
16328 "range representable on this machine"))
16329 (ding))
16331 ;; One round trip to get rid of 34th of August and stuff like that....
16332 (setq final (decode-time (apply 'encode-time final)))
16334 (setq org-read-date-final-answer ans)
16336 (if to-time
16337 (apply 'encode-time final)
16338 (if (and (boundp 'org-time-was-given) org-time-was-given)
16339 (format "%04d-%02d-%02d %02d:%02d"
16340 (nth 5 final) (nth 4 final) (nth 3 final)
16341 (nth 2 final) (nth 1 final))
16342 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16344 (defvar org-def)
16345 (defvar org-defdecode)
16346 (defvar org-with-time)
16347 (defun org-read-date-display ()
16348 "Display the current date prompt interpretation in the minibuffer."
16349 (when org-read-date-display-live
16350 (when org-read-date-overlay
16351 (delete-overlay org-read-date-overlay))
16352 (when (minibufferp (current-buffer))
16353 (save-excursion
16354 (end-of-line 1)
16355 (while (not (equal (buffer-substring
16356 (max (point-min) (- (point) 4)) (point))
16357 " "))
16358 (insert " ")))
16359 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16360 " " (or org-ans1 org-ans2)))
16361 (org-end-time-was-given nil)
16362 (f (org-read-date-analyze ans org-def org-defdecode))
16363 (fmts (if org-dcst
16364 org-time-stamp-custom-formats
16365 org-time-stamp-formats))
16366 (fmt (if (or org-with-time
16367 (and (boundp 'org-time-was-given) org-time-was-given))
16368 (cdr fmts)
16369 (car fmts)))
16370 (txt (format-time-string fmt (apply 'encode-time f)))
16371 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16372 (txt (concat "=> " txt)))
16373 (when (and org-end-time-was-given
16374 (string-match org-plain-time-of-day-regexp txt))
16375 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16376 org-end-time-was-given
16377 (substring txt (match-end 0)))))
16378 (when org-read-date-analyze-futurep
16379 (setq txt (concat txt " (=>F)")))
16380 (setq org-read-date-overlay
16381 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16382 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16384 (defun org-read-date-analyze (ans org-def org-defdecode)
16385 "Analyze the combined answer of the date prompt."
16386 ;; FIXME: cleanup and comment
16387 (let ((nowdecode (decode-time (current-time)))
16388 delta deltan deltaw deltadef year month day
16389 hour minute second wday pm h2 m2 tl wday1
16390 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16391 (setq org-read-date-analyze-futurep nil
16392 org-read-date-analyze-forced-year nil)
16393 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16394 (setq ans "+0"))
16396 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16397 (setq ans (replace-match "" t t ans)
16398 deltan (car delta)
16399 deltaw (nth 1 delta)
16400 deltadef (nth 2 delta)))
16402 ;; Check if there is an iso week date in there. If yes, store the
16403 ;; info and postpone interpreting it until the rest of the parsing
16404 ;; is done.
16405 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16406 (setq iso-year (if (match-end 1)
16407 (org-small-year-to-year
16408 (string-to-number (match-string 1 ans))))
16409 iso-weekday (if (match-end 3)
16410 (string-to-number (match-string 3 ans)))
16411 iso-week (string-to-number (match-string 2 ans)))
16412 (setq ans (replace-match "" t t ans)))
16414 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16415 (when (string-match
16416 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16417 (setq year (if (match-end 2)
16418 (string-to-number (match-string 2 ans))
16419 (progn (setq kill-year t)
16420 (string-to-number (format-time-string "%Y"))))
16421 month (string-to-number (match-string 3 ans))
16422 day (string-to-number (match-string 4 ans)))
16423 (if (< year 100) (setq year (+ 2000 year)))
16424 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16425 t nil ans)))
16427 ;; Help matching dotted european dates
16428 (when (string-match
16429 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16430 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16431 (setq kill-year t)
16432 (string-to-number (format-time-string "%Y")))
16433 day (string-to-number (match-string 1 ans))
16434 month (string-to-number (match-string 2 ans))
16435 ans (replace-match (format "%04d-%02d-%02d" year month day)
16436 t nil ans)))
16438 ;; Help matching american dates, like 5/30 or 5/30/7
16439 (when (string-match
16440 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16441 (setq year (if (match-end 4)
16442 (string-to-number (match-string 4 ans))
16443 (progn (setq kill-year t)
16444 (string-to-number (format-time-string "%Y"))))
16445 month (string-to-number (match-string 1 ans))
16446 day (string-to-number (match-string 2 ans)))
16447 (if (< year 100) (setq year (+ 2000 year)))
16448 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16449 t nil ans)))
16450 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16451 ;; If there is a time with am/pm, and *no* time without it, we convert
16452 ;; so that matching will be successful.
16453 (loop for i from 1 to 2 do ; twice, for end time as well
16454 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16455 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16456 (setq hour (string-to-number (match-string 1 ans))
16457 minute (if (match-end 3)
16458 (string-to-number (match-string 3 ans))
16460 pm (equal ?p
16461 (string-to-char (downcase (match-string 4 ans)))))
16462 (if (and (= hour 12) (not pm))
16463 (setq hour 0)
16464 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16465 (setq ans (replace-match (format "%02d:%02d" hour minute)
16466 t t ans))))
16468 ;; Check if a time range is given as a duration
16469 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16470 (setq hour (string-to-number (match-string 1 ans))
16471 h2 (+ hour (string-to-number (match-string 3 ans)))
16472 minute (string-to-number (match-string 2 ans))
16473 m2 (+ minute (if (match-end 5) (string-to-number
16474 (match-string 5 ans))0)))
16475 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16476 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16477 t t ans)))
16479 ;; Check if there is a time range
16480 (when (boundp 'org-end-time-was-given)
16481 (setq org-time-was-given nil)
16482 (when (and (string-match org-plain-time-of-day-regexp ans)
16483 (match-end 8))
16484 (setq org-end-time-was-given (match-string 8 ans))
16485 (setq ans (concat (substring ans 0 (match-beginning 7))
16486 (substring ans (match-end 7))))))
16488 (setq tl (parse-time-string ans)
16489 day (or (nth 3 tl) (nth 3 org-defdecode))
16490 month (or (nth 4 tl)
16491 (if (and org-read-date-prefer-future
16492 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16493 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16494 (nth 4 org-defdecode)))
16495 year (or (and (not kill-year) (nth 5 tl))
16496 (if (and org-read-date-prefer-future
16497 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16498 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16499 (nth 5 org-defdecode)))
16500 hour (or (nth 2 tl) (nth 2 org-defdecode))
16501 minute (or (nth 1 tl) (nth 1 org-defdecode))
16502 second (or (nth 0 tl) 0)
16503 wday (nth 6 tl))
16505 (when (and (eq org-read-date-prefer-future 'time)
16506 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16507 (equal day (nth 3 nowdecode))
16508 (equal month (nth 4 nowdecode))
16509 (equal year (nth 5 nowdecode))
16510 (nth 2 tl)
16511 (or (< (nth 2 tl) (nth 2 nowdecode))
16512 (and (= (nth 2 tl) (nth 2 nowdecode))
16513 (nth 1 tl)
16514 (< (nth 1 tl) (nth 1 nowdecode)))))
16515 (setq day (1+ day)
16516 futurep t))
16518 ;; Special date definitions below
16519 (cond
16520 (iso-week
16521 ;; There was an iso week
16522 (require 'cal-iso)
16523 (setq futurep nil)
16524 (setq year (or iso-year year)
16525 day (or iso-weekday wday 1)
16526 wday nil ; to make sure that the trigger below does not match
16527 iso-date (calendar-gregorian-from-absolute
16528 (calendar-absolute-from-iso
16529 (list iso-week day year))))
16530 ; FIXME: Should we also push ISO weeks into the future?
16531 ; (when (and org-read-date-prefer-future
16532 ; (not iso-year)
16533 ; (< (calendar-absolute-from-gregorian iso-date)
16534 ; (time-to-days (current-time))))
16535 ; (setq year (1+ year)
16536 ; iso-date (calendar-gregorian-from-absolute
16537 ; (calendar-absolute-from-iso
16538 ; (list iso-week day year)))))
16539 (setq month (car iso-date)
16540 year (nth 2 iso-date)
16541 day (nth 1 iso-date)))
16542 (deltan
16543 (setq futurep nil)
16544 (unless deltadef
16545 (let ((now (decode-time (current-time))))
16546 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16547 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16548 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16549 ((equal deltaw "m") (setq month (+ month deltan)))
16550 ((equal deltaw "y") (setq year (+ year deltan)))))
16551 ((and wday (not (nth 3 tl)))
16552 ;; Weekday was given, but no day, so pick that day in the week
16553 ;; on or after the derived date.
16554 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16555 (unless (equal wday wday1)
16556 (setq day (+ day (% (- wday wday1 -7) 7))))))
16557 (if (and (boundp 'org-time-was-given)
16558 (nth 2 tl))
16559 (setq org-time-was-given t))
16560 (if (< year 100) (setq year (+ 2000 year)))
16561 ;; Check of the date is representable
16562 (if org-read-date-force-compatible-dates
16563 (progn
16564 (if (< year 1970)
16565 (setq year 1970 org-read-date-analyze-forced-year t))
16566 (if (> year 2037)
16567 (setq year 2037 org-read-date-analyze-forced-year t)))
16568 (condition-case nil
16569 (ignore (encode-time second minute hour day month year))
16570 (error
16571 (setq year (nth 5 org-defdecode))
16572 (setq org-read-date-analyze-forced-year t))))
16573 (setq org-read-date-analyze-futurep futurep)
16574 (list second minute hour day month year)))
16576 (defvar parse-time-weekdays)
16577 (defun org-read-date-get-relative (s today default)
16578 "Check string S for special relative date string.
16579 TODAY and DEFAULT are internal times, for today and for a default.
16580 Return shift list (N what def-flag)
16581 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16582 N is the number of WHATs to shift.
16583 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16584 the DEFAULT date rather than TODAY."
16585 (require 'parse-time)
16586 (when (and
16587 (string-match
16588 (concat
16589 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16590 "\\([0-9]+\\)?"
16591 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16592 "\\([ \t]\\|$\\)") s)
16593 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16594 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16595 (string-to-char (substring (match-string 1 s) -1))
16596 ?+))
16597 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16598 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16599 (what (if (match-end 3) (match-string 3 s) "d"))
16600 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16601 (date (if rel default today))
16602 (wday (nth 6 (decode-time date)))
16603 delta)
16604 (if wday1
16605 (progn
16606 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16607 (if (= delta 0) (setq delta 7))
16608 (if (= dir ?-)
16609 (progn
16610 (setq delta (- delta 7))
16611 (if (= delta 0) (setq delta -7))))
16612 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16613 (list delta "d" rel))
16614 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16616 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16617 "Turn a user-specified date into the internal representation.
16618 The internal representation needed by the calendar is (month day year).
16619 This is a wrapper to handle the brain-dead convention in calendar that
16620 user function argument order change dependent on argument order."
16621 (if (boundp 'calendar-date-style)
16622 (cond
16623 ((eq calendar-date-style 'american)
16624 (list arg1 arg2 arg3))
16625 ((eq calendar-date-style 'european)
16626 (list arg2 arg1 arg3))
16627 ((eq calendar-date-style 'iso)
16628 (list arg2 arg3 arg1)))
16629 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16630 (if (org-bound-and-true-p european-calendar-style)
16631 (list arg2 arg1 arg3)
16632 (list arg1 arg2 arg3)))))
16634 (defun org-eval-in-calendar (form &optional keepdate)
16635 "Eval FORM in the calendar window and return to current window.
16636 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16637 otherwise stick to the current value of `org-ans2'."
16638 (let ((sf (selected-frame))
16639 (sw (selected-window)))
16640 (select-window (get-buffer-window "*Calendar*" t))
16641 (eval form)
16642 (when (and (not keepdate) (calendar-cursor-to-date))
16643 (let* ((date (calendar-cursor-to-date))
16644 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16645 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16646 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16647 (select-window sw)
16648 (org-select-frame-set-input-focus sf)))
16650 (defun org-calendar-select ()
16651 "Return to `org-read-date' with the date currently selected.
16652 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16653 (interactive)
16654 (when (calendar-cursor-to-date)
16655 (let* ((date (calendar-cursor-to-date))
16656 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16657 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16658 (if (active-minibuffer-window) (exit-minibuffer))))
16660 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16661 "Insert a date stamp for the date given by the internal TIME.
16662 WITH-HM means use the stamp format that includes the time of the day.
16663 INACTIVE means use square brackets instead of angular ones, so that the
16664 stamp will not contribute to the agenda.
16665 PRE and POST are optional strings to be inserted before and after the
16666 stamp.
16667 The command returns the inserted time stamp."
16668 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16669 stamp)
16670 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16671 (insert-before-markers (or pre ""))
16672 (when (listp extra)
16673 (setq extra (car extra))
16674 (if (and (stringp extra)
16675 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16676 (setq extra (format "-%02d:%02d"
16677 (string-to-number (match-string 1 extra))
16678 (string-to-number (match-string 2 extra))))
16679 (setq extra nil)))
16680 (when extra
16681 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16682 (insert-before-markers (setq stamp (format-time-string fmt time)))
16683 (insert-before-markers (or post ""))
16684 (setq org-last-inserted-timestamp stamp)))
16686 (defun org-toggle-time-stamp-overlays ()
16687 "Toggle the use of custom time stamp formats."
16688 (interactive)
16689 (setq org-display-custom-times (not org-display-custom-times))
16690 (unless org-display-custom-times
16691 (let ((p (point-min)) (bmp (buffer-modified-p)))
16692 (while (setq p (next-single-property-change p 'display))
16693 (if (and (get-text-property p 'display)
16694 (eq (get-text-property p 'face) 'org-date))
16695 (remove-text-properties
16696 p (setq p (next-single-property-change p 'display))
16697 '(display t))))
16698 (set-buffer-modified-p bmp)))
16699 (if (featurep 'xemacs)
16700 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16701 (org-restart-font-lock)
16702 (setq org-table-may-need-update t)
16703 (if org-display-custom-times
16704 (message "Time stamps are overlaid with custom format")
16705 (message "Time stamp overlays removed")))
16707 (defun org-display-custom-time (beg end)
16708 "Overlay modified time stamp format over timestamp between BEG and END."
16709 (let* ((ts (buffer-substring beg end))
16710 t1 w1 with-hm tf time str w2 (off 0))
16711 (save-match-data
16712 (setq t1 (org-parse-time-string ts t))
16713 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16714 (setq off (- (match-end 0) (match-beginning 0)))))
16715 (setq end (- end off))
16716 (setq w1 (- end beg)
16717 with-hm (and (nth 1 t1) (nth 2 t1))
16718 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16719 time (org-fix-decoded-time t1)
16720 str (org-add-props
16721 (format-time-string
16722 (substring tf 1 -1) (apply 'encode-time time))
16723 nil 'mouse-face 'highlight)
16724 w2 (length str))
16725 (if (not (= w2 w1))
16726 (add-text-properties (1+ beg) (+ 2 beg)
16727 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16728 (if (featurep 'xemacs)
16729 (progn
16730 (put-text-property beg end 'invisible t)
16731 (put-text-property beg end 'end-glyph (make-glyph str)))
16732 (put-text-property beg end 'display str))))
16734 (defun org-translate-time (string)
16735 "Translate all timestamps in STRING to custom format.
16736 But do this only if the variable `org-display-custom-times' is set."
16737 (when org-display-custom-times
16738 (save-match-data
16739 (let* ((start 0)
16740 (re org-ts-regexp-both)
16741 t1 with-hm inactive tf time str beg end)
16742 (while (setq start (string-match re string start))
16743 (setq beg (match-beginning 0)
16744 end (match-end 0)
16745 t1 (save-match-data
16746 (org-parse-time-string (substring string beg end) t))
16747 with-hm (and (nth 1 t1) (nth 2 t1))
16748 inactive (equal (substring string beg (1+ beg)) "[")
16749 tf (funcall (if with-hm 'cdr 'car)
16750 org-time-stamp-custom-formats)
16751 time (org-fix-decoded-time t1)
16752 str (format-time-string
16753 (concat
16754 (if inactive "[" "<") (substring tf 1 -1)
16755 (if inactive "]" ">"))
16756 (apply 'encode-time time))
16757 string (replace-match str t t string)
16758 start (+ start (length str)))))))
16759 string)
16761 (defun org-fix-decoded-time (time)
16762 "Set 0 instead of nil for the first 6 elements of time.
16763 Don't touch the rest."
16764 (let ((n 0))
16765 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16767 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16769 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16770 "Difference between TIMESTAMP-STRING and now in days.
16771 If SECONDS is non-nil, return the difference in seconds."
16772 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16773 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16774 (funcall fdiff (current-time)))))
16776 (defun org-deadline-close (timestamp-string &optional ndays)
16777 "Is the time in TIMESTAMP-STRING close to the current date?"
16778 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16779 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16780 (not (org-entry-is-done-p))))
16782 (defun org-get-wdays (ts &optional delay zero-delay)
16783 "Get the deadline lead time appropriate for timestring TS.
16784 When DELAY is non-nil, get the delay time for scheduled items
16785 instead of the deadline lead time. When ZERO-DELAY is non-nil
16786 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16787 don't try to find the delay cookie in the scheduled timestamp."
16788 (let ((tv (if delay org-scheduled-delay-days
16789 org-deadline-warning-days)))
16790 (cond
16791 ((or (and delay (< tv 0))
16792 (and delay zero-delay (<= tv 0))
16793 (and (not delay) (<= tv 0)))
16794 ;; Enforce this value no matter what
16795 (- tv))
16796 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16797 ;; lead time is specified.
16798 (floor (* (string-to-number (match-string 1 ts))
16799 (cdr (assoc (match-string 2 ts)
16800 '(("d" . 1) ("w" . 7)
16801 ("m" . 30.4) ("y" . 365.25)
16802 ("h" . 0.041667)))))))
16803 ;; go for the default.
16804 (t tv))))
16806 (defun org-calendar-select-mouse (ev)
16807 "Return to `org-read-date' with the date currently selected.
16808 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16809 (interactive "e")
16810 (mouse-set-point ev)
16811 (when (calendar-cursor-to-date)
16812 (let* ((date (calendar-cursor-to-date))
16813 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16814 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16815 (if (active-minibuffer-window) (exit-minibuffer))))
16817 (defun org-check-deadlines (ndays)
16818 "Check if there are any deadlines due or past due.
16819 A deadline is considered due if it happens within `org-deadline-warning-days'
16820 days from today's date. If the deadline appears in an entry marked DONE,
16821 it is not shown. The prefix arg NDAYS can be used to test that many
16822 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16823 (interactive "P")
16824 (let* ((org-warn-days
16825 (cond
16826 ((equal ndays '(4)) 100000)
16827 (ndays (prefix-numeric-value ndays))
16828 (t (abs org-deadline-warning-days))))
16829 (case-fold-search nil)
16830 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16831 (callback
16832 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16834 (message "%d deadlines past-due or due within %d days"
16835 (org-occur regexp nil callback)
16836 org-warn-days)))
16838 (defsubst org-re-timestamp (type)
16839 "Return a regexp for timestamp TYPE.
16840 Allowed values for TYPE are:
16842 all: all timestamps
16843 active: only active timestamps (<...>)
16844 inactive: only inactive timestamps ([...])
16845 scheduled: only scheduled timestamps
16846 deadline: only deadline timestamps
16847 closed: only closed time-stamps
16849 When TYPE is nil, fall back on returning a regexp that matches
16850 both scheduled and deadline timestamps."
16851 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16852 ((eq type 'active) org-ts-regexp)
16853 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16854 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16855 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16856 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
16857 ((eq type 'scheduled-or-deadline)
16858 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16860 (defun org-check-before-date (date)
16861 "Check if there are deadlines or scheduled entries before DATE."
16862 (interactive (list (org-read-date)))
16863 (let ((case-fold-search nil)
16864 (regexp (org-re-timestamp org-ts-type))
16865 (callback
16866 (lambda () (time-less-p
16867 (org-time-string-to-time (match-string 1))
16868 (org-time-string-to-time date)))))
16869 (message "%d entries before %s"
16870 (org-occur regexp nil callback) date)))
16872 (defun org-check-after-date (date)
16873 "Check if there are deadlines or scheduled entries after DATE."
16874 (interactive (list (org-read-date)))
16875 (let ((case-fold-search nil)
16876 (regexp (org-re-timestamp org-ts-type))
16877 (callback
16878 (lambda () (not
16879 (time-less-p
16880 (org-time-string-to-time (match-string 1))
16881 (org-time-string-to-time date))))))
16882 (message "%d entries after %s"
16883 (org-occur regexp nil callback) date)))
16885 (defun org-check-dates-range (start-date end-date)
16886 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16887 (interactive (list (org-read-date nil nil nil "Range starts")
16888 (org-read-date nil nil nil "Range end")))
16889 (let ((case-fold-search nil)
16890 (regexp (org-re-timestamp org-ts-type))
16891 (callback
16892 (lambda ()
16893 (let ((match (match-string 1)))
16894 (and
16895 (not (time-less-p
16896 (org-time-string-to-time match)
16897 (org-time-string-to-time start-date)))
16898 (time-less-p
16899 (org-time-string-to-time match)
16900 (org-time-string-to-time end-date)))))))
16901 (message "%d entries between %s and %s"
16902 (org-occur regexp nil callback) start-date end-date)))
16904 (defun org-evaluate-time-range (&optional to-buffer)
16905 "Evaluate a time range by computing the difference between start and end.
16906 Normally the result is just printed in the echo area, but with prefix arg
16907 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16908 If the time range is actually in a table, the result is inserted into the
16909 next column.
16910 For time difference computation, a year is assumed to be exactly 365
16911 days in order to avoid rounding problems."
16912 (interactive "P")
16914 (org-clock-update-time-maybe)
16915 (save-excursion
16916 (unless (org-at-date-range-p t)
16917 (goto-char (point-at-bol))
16918 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16919 (if (not (org-at-date-range-p t))
16920 (user-error "Not at a time-stamp range, and none found in current line")))
16921 (let* ((ts1 (match-string 1))
16922 (ts2 (match-string 2))
16923 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16924 (match-end (match-end 0))
16925 (time1 (org-time-string-to-time ts1))
16926 (time2 (org-time-string-to-time ts2))
16927 (t1 (org-float-time time1))
16928 (t2 (org-float-time time2))
16929 (diff (abs (- t2 t1)))
16930 (negative (< (- t2 t1) 0))
16931 ;; (ys (floor (* 365 24 60 60)))
16932 (ds (* 24 60 60))
16933 (hs (* 60 60))
16934 (fy "%dy %dd %02d:%02d")
16935 (fy1 "%dy %dd")
16936 (fd "%dd %02d:%02d")
16937 (fd1 "%dd")
16938 (fh "%02d:%02d")
16939 y d h m align)
16940 (if havetime
16941 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16943 d (floor (/ diff ds)) diff (mod diff ds)
16944 h (floor (/ diff hs)) diff (mod diff hs)
16945 m (floor (/ diff 60)))
16946 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16948 d (floor (+ (/ diff ds) 0.5))
16949 h 0 m 0))
16950 (if (not to-buffer)
16951 (message "%s" (org-make-tdiff-string y d h m))
16952 (if (org-at-table-p)
16953 (progn
16954 (goto-char match-end)
16955 (setq align t)
16956 (and (looking-at " *|") (goto-char (match-end 0))))
16957 (goto-char match-end))
16958 (if (looking-at
16959 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16960 (replace-match ""))
16961 (if negative (insert " -"))
16962 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16963 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16964 (insert " " (format fh h m))))
16965 (if align (org-table-align))
16966 (message "Time difference inserted")))))
16968 (defun org-make-tdiff-string (y d h m)
16969 (let ((fmt "")
16970 (l nil))
16971 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16972 l (push y l)))
16973 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16974 l (push d l)))
16975 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16976 l (push h l)))
16977 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16978 l (push m l)))
16979 (apply 'format fmt (nreverse l))))
16981 (defun org-time-string-to-time (s &optional buffer pos)
16982 "Convert a timestamp string into internal time."
16983 (condition-case errdata
16984 (apply 'encode-time (org-parse-time-string s))
16985 (error (error "Bad timestamp `%s'%s\nError was: %s"
16986 s (if (not (and buffer pos))
16988 (format " at %d in buffer `%s'" pos buffer))
16989 (cdr errdata)))))
16991 (defun org-time-string-to-seconds (s)
16992 "Convert a timestamp string to a number of seconds."
16993 (org-float-time (org-time-string-to-time s)))
16995 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16996 "Convert a time stamp to an absolute day number.
16997 If there is a specifier for a cyclic time stamp, get the closest
16998 date to DAYNR.
16999 PREFER and SHOW-ALL are passed through to `org-closest-date'.
17000 The variable `date' is bound by the calendar when this is called."
17001 (cond
17002 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17003 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17004 daynr
17005 (+ daynr 1000)))
17006 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
17007 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17008 (time-to-days (current-time))) (match-string 0 s)
17009 prefer show-all))
17010 (t (time-to-days
17011 (condition-case errdata
17012 (apply 'encode-time (org-parse-time-string s))
17013 (error (error "Bad timestamp `%s'%s\nError was: %s"
17014 s (if (not (and buffer pos))
17016 (format " at %d in buffer `%s'" pos buffer))
17017 (cdr errdata))))))))
17019 (defun org-days-to-iso-week (days)
17020 "Return the iso week number."
17021 (require 'cal-iso)
17022 (car (calendar-iso-from-absolute days)))
17024 (defun org-small-year-to-year (year)
17025 "Convert 2-digit years into 4-digit years.
17026 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
17027 The year 2000 cannot be abbreviated. Any year larger than 99
17028 is returned unchanged."
17029 (if (< year 38)
17030 (setq year (+ 2000 year))
17031 (if (< year 100)
17032 (setq year (+ 1900 year))))
17033 year)
17035 (defun org-time-from-absolute (d)
17036 "Return the time corresponding to date D.
17037 D may be an absolute day number, or a calendar-type list (month day year)."
17038 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17039 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17041 (defun org-calendar-holiday ()
17042 "List of holidays, for Diary display in Org-mode."
17043 (require 'holidays)
17044 (let ((hl (funcall
17045 (if (fboundp 'calendar-check-holidays)
17046 'calendar-check-holidays 'check-calendar-holidays) date)))
17047 (if hl (mapconcat 'identity hl "; "))))
17049 (defun org-diary-sexp-entry (sexp entry date)
17050 "Process a SEXP diary ENTRY for DATE."
17051 (require 'diary-lib)
17052 (let ((result (if calendar-debug-sexp
17053 (let ((stack-trace-on-error t))
17054 (eval (car (read-from-string sexp))))
17055 (condition-case nil
17056 (eval (car (read-from-string sexp)))
17057 (error
17058 (beep)
17059 (message "Bad sexp at line %d in %s: %s"
17060 (org-current-line)
17061 (buffer-file-name) sexp)
17062 (sleep-for 2))))))
17063 (cond ((stringp result) (split-string result "; "))
17064 ((and (consp result)
17065 (not (consp (cdr result)))
17066 (stringp (cdr result))) (cdr result))
17067 ((and (consp result)
17068 (stringp (car result))) result)
17069 (result entry))))
17071 (defun org-diary-to-ical-string (frombuf)
17072 "Get iCalendar entries from diary entries in buffer FROMBUF.
17073 This uses the icalendar.el library."
17074 (let* ((tmpdir (if (featurep 'xemacs)
17075 (temp-directory)
17076 temporary-file-directory))
17077 (tmpfile (make-temp-name
17078 (expand-file-name "orgics" tmpdir)))
17079 buf rtn b e)
17080 (with-current-buffer frombuf
17081 (icalendar-export-region (point-min) (point-max) tmpfile)
17082 (setq buf (find-buffer-visiting tmpfile))
17083 (set-buffer buf)
17084 (goto-char (point-min))
17085 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17086 (setq b (match-beginning 0)))
17087 (goto-char (point-max))
17088 (if (re-search-backward "^END:VEVENT" nil t)
17089 (setq e (match-end 0)))
17090 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17091 (kill-buffer buf)
17092 (delete-file tmpfile)
17093 rtn))
17095 (defun org-closest-date (start current change prefer show-all)
17096 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17097 When PREFER is `past', return a date that is either CURRENT or past.
17098 When PREFER is `future', return a date that is either CURRENT or future.
17099 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17100 ;; Make the proper lists from the dates
17101 (catch 'exit
17102 (let ((a1 '(("h" . hour)
17103 ("d" . day)
17104 ("w" . week)
17105 ("m" . month)
17106 ("y" . year)))
17107 (shour (nth 2 (org-parse-time-string start)))
17108 dn dw sday cday n1 n2 n0
17109 d m y y1 y2 date1 date2 nmonths nm ny m2)
17111 (setq start (org-date-to-gregorian start)
17112 current (org-date-to-gregorian
17113 (if show-all
17114 current
17115 (time-to-days (current-time))))
17116 sday (calendar-absolute-from-gregorian start)
17117 cday (calendar-absolute-from-gregorian current))
17119 (if (<= cday sday) (throw 'exit sday))
17121 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17122 (setq dn (string-to-number (match-string 1 change))
17123 dw (cdr (assoc (match-string 2 change) a1)))
17124 (user-error "Invalid change specifier: %s" change))
17125 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17126 (cond
17127 ((eq dw 'hour)
17128 (let ((missing-hours
17129 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17130 dn)))
17131 (setq n1 (if (zerop missing-hours) cday
17132 (- cday (1+ (floor (/ missing-hours 24)))))
17133 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17134 ((eq dw 'day)
17135 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17136 n2 (+ n1 dn)))
17137 ((eq dw 'year)
17138 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17139 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17140 (setq date1 (list m d y1)
17141 n1 (calendar-absolute-from-gregorian date1)
17142 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17143 n2 (calendar-absolute-from-gregorian date2)))
17144 ((eq dw 'month)
17145 ;; approx number of month between the two dates
17146 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17147 ;; How often does dn fit in there?
17148 (setq d (nth 1 start) m (car start) y (nth 2 start)
17149 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17150 m (+ m nm)
17151 ny (floor (/ m 12))
17152 y (+ y ny)
17153 m (- m (* ny 12)))
17154 (while (> m 12) (setq m (- m 12) y (1+ y)))
17155 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17156 (setq m2 (+ m dn) y2 y)
17157 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17158 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17159 (while (<= n2 cday)
17160 (setq n1 n2 m m2 y y2)
17161 (setq m2 (+ m dn) y2 y)
17162 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17163 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17164 ;; Make sure n1 is the earlier date
17165 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17166 (if show-all
17167 (cond
17168 ((eq prefer 'past) (if (= cday n2) n2 n1))
17169 ((eq prefer 'future) (if (= cday n1) n1 n2))
17170 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17171 (cond
17172 ((eq prefer 'past) (if (= cday n2) n2 n1))
17173 ((eq prefer 'future) (if (= cday n1) n1 n2))
17174 (t (if (= cday n1) n1 n2)))))))
17176 (defun org-date-to-gregorian (date)
17177 "Turn any specification of DATE into a Gregorian date for the calendar."
17178 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17179 ((and (listp date) (= (length date) 3)) date)
17180 ((stringp date)
17181 (setq date (org-parse-time-string date))
17182 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17183 ((listp date)
17184 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17186 (defun org-parse-time-string (s &optional nodefault)
17187 "Parse the standard Org-mode time string.
17188 This should be a lot faster than the normal `parse-time-string'.
17189 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17190 hour and minute fields will be nil if not given."
17191 (cond ((string-match org-ts-regexp0 s)
17192 (list 0
17193 (if (or (match-beginning 8) (not nodefault))
17194 (string-to-number (or (match-string 8 s) "0")))
17195 (if (or (match-beginning 7) (not nodefault))
17196 (string-to-number (or (match-string 7 s) "0")))
17197 (string-to-number (match-string 4 s))
17198 (string-to-number (match-string 3 s))
17199 (string-to-number (match-string 2 s))
17200 nil nil nil))
17201 ((string-match "^<[^>]+>$" s)
17202 (decode-time (seconds-to-time (org-matcher-time s))))
17203 (t (error "Not a standard Org-mode time string: %s" s))))
17205 (defun org-timestamp-up (&optional arg)
17206 "Increase the date item at the cursor by one.
17207 If the cursor is on the year, change the year. If it is on the month,
17208 the day or the time, change that.
17209 With prefix ARG, change by that many units."
17210 (interactive "p")
17211 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17213 (defun org-timestamp-down (&optional arg)
17214 "Decrease the date item at the cursor by one.
17215 If the cursor is on the year, change the year. If it is on the month,
17216 the day or the time, change that.
17217 With prefix ARG, change by that many units."
17218 (interactive "p")
17219 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17221 (defun org-timestamp-up-day (&optional arg)
17222 "Increase the date in the time stamp by one day.
17223 With prefix ARG, change that many days."
17224 (interactive "p")
17225 (if (and (not (org-at-timestamp-p t))
17226 (org-at-heading-p))
17227 (org-todo 'up)
17228 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17230 (defun org-timestamp-down-day (&optional arg)
17231 "Decrease the date in the time stamp by one day.
17232 With prefix ARG, change that many days."
17233 (interactive "p")
17234 (if (and (not (org-at-timestamp-p t))
17235 (org-at-heading-p))
17236 (org-todo 'down)
17237 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17239 (defun org-at-timestamp-p (&optional inactive-ok)
17240 "Determine if the cursor is in or at a timestamp."
17241 (interactive)
17242 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17243 (pos (point))
17244 (ans (or (looking-at tsr)
17245 (save-excursion
17246 (skip-chars-backward "^[<\n\r\t")
17247 (if (> (point) (point-min)) (backward-char 1))
17248 (and (looking-at tsr)
17249 (> (- (match-end 0) pos) -1))))))
17250 (and ans
17251 (boundp 'org-ts-what)
17252 (setq org-ts-what
17253 (cond
17254 ((= pos (match-beginning 0)) 'bracket)
17255 ;; Point is considered to be "on the bracket" whether
17256 ;; it's really on it or right after it.
17257 ((= pos (1- (match-end 0))) 'bracket)
17258 ((= pos (match-end 0)) 'after)
17259 ((org-pos-in-match-range pos 2) 'year)
17260 ((org-pos-in-match-range pos 3) 'month)
17261 ((org-pos-in-match-range pos 7) 'hour)
17262 ((org-pos-in-match-range pos 8) 'minute)
17263 ((or (org-pos-in-match-range pos 4)
17264 (org-pos-in-match-range pos 5)) 'day)
17265 ((and (> pos (or (match-end 8) (match-end 5)))
17266 (< pos (match-end 0)))
17267 (- pos (or (match-end 8) (match-end 5))))
17268 (t 'day))))
17269 ans))
17271 (defun org-toggle-timestamp-type ()
17272 "Toggle the type (<active> or [inactive]) of a time stamp."
17273 (interactive)
17274 (when (org-at-timestamp-p t)
17275 (let ((beg (match-beginning 0)) (end (match-end 0))
17276 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17277 (save-excursion
17278 (goto-char beg)
17279 (while (re-search-forward "[][<>]" end t)
17280 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17281 t t)))
17282 (message "Timestamp is now %sactive"
17283 (if (equal (char-after beg) ?<) "" "in")))))
17285 (defun org-at-clock-log-p nil
17286 "Is the cursor on the clock log line?"
17287 (save-excursion
17288 (move-beginning-of-line 1)
17289 (looking-at "^[ \t]*CLOCK:")))
17291 (defvar org-clock-history) ; defined in org-clock.el
17292 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17293 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17294 "Change the date in the time stamp at point.
17295 The date will be changed by N times WHAT. WHAT can be `day', `month',
17296 `year', `minute', `second'. If WHAT is not given, the cursor position
17297 in the timestamp determines what will be changed.
17298 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17299 (let ((origin (point)) origin-cat
17300 with-hm inactive
17301 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17302 org-ts-what
17303 extra rem
17304 ts time time0 fixnext clrgx)
17305 (if (not (org-at-timestamp-p t))
17306 (user-error "Not at a timestamp"))
17307 (if (and (not what) (eq org-ts-what 'bracket))
17308 (org-toggle-timestamp-type)
17309 ;; Point isn't on brackets. Remember the part of the time-stamp
17310 ;; the point was in. Indeed, size of time-stamps may change,
17311 ;; but point must be kept in the same category nonetheless.
17312 (setq origin-cat org-ts-what)
17313 (if (and (not what) (not (eq org-ts-what 'day))
17314 org-display-custom-times
17315 (get-text-property (point) 'display)
17316 (not (get-text-property (1- (point)) 'display)))
17317 (setq org-ts-what 'day))
17318 (setq org-ts-what (or what org-ts-what)
17319 inactive (= (char-after (match-beginning 0)) ?\[)
17320 ts (match-string 0))
17321 (replace-match "")
17322 (when (string-match
17323 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17325 (setq extra (match-string 1 ts))
17326 (if suppress-tmp-delay
17327 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17328 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17329 (setq with-hm t))
17330 (setq time0 (org-parse-time-string ts))
17331 (when (and updown
17332 (eq org-ts-what 'minute)
17333 (not current-prefix-arg))
17334 ;; This looks like s-up and s-down. Change by one rounding step.
17335 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17336 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17337 (setcar (cdr time0) (+ (nth 1 time0)
17338 (if (> n 0) (- rem) (- dm rem))))))
17339 (setq time
17340 (encode-time (or (car time0) 0)
17341 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17342 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17343 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17344 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17345 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17346 (nthcdr 6 time0)))
17347 (when (and (member org-ts-what '(hour minute))
17348 extra
17349 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17350 (setq extra (org-modify-ts-extra
17351 extra
17352 (if (eq org-ts-what 'hour) 2 5)
17353 n dm)))
17354 (when (integerp org-ts-what)
17355 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17356 (if (eq what 'calendar)
17357 (let ((cal-date (org-get-date-from-calendar)))
17358 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17359 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17360 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17361 (setcar time0 (or (car time0) 0))
17362 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17363 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17364 (setq time (apply 'encode-time time0))))
17365 ;; Insert the new time-stamp, and ensure point stays in the same
17366 ;; category as before (i.e. not after the last position in that
17367 ;; category).
17368 (let ((pos (point)))
17369 ;; Stay before inserted string. `save-excursion' is of no use.
17370 (setq org-last-changed-timestamp
17371 (org-insert-time-stamp time with-hm inactive nil nil extra))
17372 (goto-char pos))
17373 (save-match-data
17374 (looking-at org-ts-regexp3)
17375 (goto-char (cond
17376 ;; `day' category ends before `hour' if any, or at
17377 ;; the end of the day name.
17378 ((eq origin-cat 'day)
17379 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17380 ((eq origin-cat 'hour) (min (match-end 7) origin))
17381 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17382 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17383 ;; `year' and `month' have both fixed size: point
17384 ;; couldn't have moved into another part.
17385 (t origin))))
17386 ;; Update clock if on a CLOCK line.
17387 (org-clock-update-time-maybe)
17388 ;; Maybe adjust the closest clock in `org-clock-history'
17389 (when org-clock-adjust-closest
17390 (if (not (and (org-at-clock-log-p)
17391 (< 1 (length (delq nil (mapcar 'marker-position
17392 org-clock-history))))))
17393 (message "No clock to adjust")
17394 (cond ((save-excursion ; fix previous clock?
17395 (re-search-backward org-ts-regexp0 nil t)
17396 (org-looking-back (concat org-clock-string " \\[")))
17397 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17398 ((save-excursion ; fix next clock?
17399 (re-search-backward org-ts-regexp0 nil t)
17400 (looking-at (concat org-ts-regexp0 "\\] =>")))
17401 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17402 (save-window-excursion
17403 ;; Find closest clock to point, adjust the previous/next one in history
17404 (let* ((p (save-excursion (org-back-to-heading t)))
17405 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17406 (clfixnth
17407 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17408 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17409 (if (not clfixpos)
17410 (message "No clock to adjust")
17411 (save-excursion
17412 (org-goto-marker-or-bmk clfixpos)
17413 (org-show-subtree)
17414 (when (re-search-forward clrgx nil t)
17415 (goto-char (match-beginning 1))
17416 (let (org-clock-adjust-closest)
17417 (org-timestamp-change n org-ts-what updown))
17418 (message "Clock adjusted in %s for heading: %s"
17419 (file-name-nondirectory (buffer-file-name))
17420 (org-get-heading t t)))))))))
17421 ;; Try to recenter the calendar window, if any.
17422 (if (and org-calendar-follow-timestamp-change
17423 (get-buffer-window "*Calendar*" t)
17424 (memq org-ts-what '(day month year)))
17425 (org-recenter-calendar (time-to-days time))))))
17427 (defun org-modify-ts-extra (s pos n dm)
17428 "Change the different parts of the lead-time and repeat fields in timestamp."
17429 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17430 ng h m new rem)
17431 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17432 (cond
17433 ((or (org-pos-in-match-range pos 2)
17434 (org-pos-in-match-range pos 3))
17435 (setq m (string-to-number (match-string 3 s))
17436 h (string-to-number (match-string 2 s)))
17437 (if (org-pos-in-match-range pos 2)
17438 (setq h (+ h n))
17439 (setq n (* dm (org-no-warnings (signum n))))
17440 (when (not (= 0 (setq rem (% m dm))))
17441 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17442 (setq m (+ m n)))
17443 (if (< m 0) (setq m (+ m 60) h (1- h)))
17444 (if (> m 59) (setq m (- m 60) h (1+ h)))
17445 (setq h (min 24 (max 0 h)))
17446 (setq ng 1 new (format "-%02d:%02d" h m)))
17447 ((org-pos-in-match-range pos 6)
17448 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17449 ((org-pos-in-match-range pos 5)
17450 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17452 ((org-pos-in-match-range pos 9)
17453 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17454 ((org-pos-in-match-range pos 8)
17455 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17457 (when ng
17458 (setq s (concat
17459 (substring s 0 (match-beginning ng))
17461 (substring s (match-end ng))))))
17464 (defun org-recenter-calendar (date)
17465 "If the calendar is visible, recenter it to DATE."
17466 (let ((cwin (get-buffer-window "*Calendar*" t)))
17467 (when cwin
17468 (let ((calendar-move-hook nil))
17469 (with-selected-window cwin
17470 (calendar-goto-date (if (listp date) date
17471 (calendar-gregorian-from-absolute date))))))))
17473 (defun org-goto-calendar (&optional arg)
17474 "Go to the Emacs calendar at the current date.
17475 If there is a time stamp in the current line, go to that date.
17476 A prefix ARG can be used to force the current date."
17477 (interactive "P")
17478 (let ((tsr org-ts-regexp) diff
17479 (calendar-move-hook nil)
17480 (calendar-view-holidays-initially-flag nil)
17481 (calendar-view-diary-initially-flag nil))
17482 (if (or (org-at-timestamp-p)
17483 (save-excursion
17484 (beginning-of-line 1)
17485 (looking-at (concat ".*" tsr))))
17486 (let ((d1 (time-to-days (current-time)))
17487 (d2 (time-to-days
17488 (org-time-string-to-time (match-string 1)))))
17489 (setq diff (- d2 d1))))
17490 (calendar)
17491 (calendar-goto-today)
17492 (if (and diff (not arg)) (calendar-forward-day diff))))
17494 (defun org-get-date-from-calendar ()
17495 "Return a list (month day year) of date at point in calendar."
17496 (with-current-buffer "*Calendar*"
17497 (save-match-data
17498 (calendar-cursor-to-date))))
17500 (defun org-date-from-calendar ()
17501 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17502 If there is already a time stamp at the cursor position, update it."
17503 (interactive)
17504 (if (org-at-timestamp-p t)
17505 (org-timestamp-change 0 'calendar)
17506 (let ((cal-date (org-get-date-from-calendar)))
17507 (org-insert-time-stamp
17508 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17510 (defcustom org-effort-durations
17511 `(("h" . 60)
17512 ("d" . ,(* 60 8))
17513 ("w" . ,(* 60 8 5))
17514 ("m" . ,(* 60 8 5 4))
17515 ("y" . ,(* 60 8 5 40)))
17516 "Conversion factor to minutes for an effort modifier.
17518 Each entry has the form (MODIFIER . MINUTES).
17520 In an effort string, a number followed by MODIFIER is multiplied
17521 by the specified number of MINUTES to obtain an effort in
17522 minutes.
17524 For example, if the value of this variable is ((\"hours\" . 60)), then an
17525 effort string \"2hours\" is equivalent to 120 minutes."
17526 :group 'org-agenda
17527 :version "24.1"
17528 :type '(alist :key-type (string :tag "Modifier")
17529 :value-type (number :tag "Minutes")))
17531 (defun org-minutes-to-clocksum-string (m)
17532 "Format number of minutes as a clocksum string.
17533 The format is determined by `org-time-clocksum-format',
17534 `org-time-clocksum-use-fractional' and
17535 `org-time-clocksum-fractional-format' and
17536 `org-time-clocksum-use-effort-durations'."
17537 (let ((clocksum "")
17538 (m (round m)) ; Don't allow fractions of minutes
17539 h d w mo y fmt n)
17540 (setq h (if org-time-clocksum-use-effort-durations
17541 (cdr (assoc "h" org-effort-durations)) 60)
17542 d (if org-time-clocksum-use-effort-durations
17543 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17544 w (if org-time-clocksum-use-effort-durations
17545 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17546 mo (if org-time-clocksum-use-effort-durations
17547 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17548 y (if org-time-clocksum-use-effort-durations
17549 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17550 ;; fractional format
17551 (if org-time-clocksum-use-fractional
17552 (cond
17553 ;; single format string
17554 ((stringp org-time-clocksum-fractional-format)
17555 (format org-time-clocksum-fractional-format (/ m (float h))))
17556 ;; choice of fractional formats for different time units
17557 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17558 (> (/ (truncate m) (* y d h)) 0))
17559 (format fmt (/ m (* y d (float h)))))
17560 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17561 (> (/ (truncate m) (* mo d h)) 0))
17562 (format fmt (/ m (* mo d (float h)))))
17563 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17564 (> (/ (truncate m) (* w d h)) 0))
17565 (format fmt (/ m (* w d (float h)))))
17566 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17567 (> (/ (truncate m) (* d h)) 0))
17568 (format fmt (/ m (* d (float h)))))
17569 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17570 (> (/ (truncate m) h) 0))
17571 (format fmt (/ m (float h))))
17572 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17573 (format fmt m))
17574 ;; fall back to smallest time unit with a format
17575 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17576 (format fmt (/ m (float h))))
17577 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17578 (format fmt (/ m (* d (float h)))))
17579 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17580 (format fmt (/ m (* w d (float h)))))
17581 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17582 (format fmt (/ m (* mo d (float h)))))
17583 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17584 (format fmt (/ m (* y d (float h))))))
17585 ;; standard (non-fractional) format, with single format string
17586 (if (stringp org-time-clocksum-format)
17587 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17588 ;; separate formats components
17589 (and (setq fmt (plist-get org-time-clocksum-format :years))
17590 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17591 (plist-get org-time-clocksum-format :require-years))
17592 (setq clocksum (concat clocksum (format fmt n))
17593 m (- m (* n y d h))))
17594 (and (setq fmt (plist-get org-time-clocksum-format :months))
17595 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17596 (plist-get org-time-clocksum-format :require-months))
17597 (setq clocksum (concat clocksum (format fmt n))
17598 m (- m (* n mo d h))))
17599 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17600 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17601 (plist-get org-time-clocksum-format :require-weeks))
17602 (setq clocksum (concat clocksum (format fmt n))
17603 m (- m (* n w d h))))
17604 (and (setq fmt (plist-get org-time-clocksum-format :days))
17605 (or (> (setq n (/ (truncate m) (* d h))) 0)
17606 (plist-get org-time-clocksum-format :require-days))
17607 (setq clocksum (concat clocksum (format fmt n))
17608 m (- m (* n d h))))
17609 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17610 (or (> (setq n (/ (truncate m) h)) 0)
17611 (plist-get org-time-clocksum-format :require-hours))
17612 (setq clocksum (concat clocksum (format fmt n))
17613 m (- m (* n h))))
17614 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17615 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17616 (setq clocksum (concat clocksum (format fmt m))))
17617 ;; return formatted time duration
17618 clocksum))))
17620 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17621 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17622 "Org mode version 8.0")
17624 (defun org-hours-to-clocksum-string (n)
17625 (org-minutes-to-clocksum-string (* n 60)))
17627 (defun org-hh:mm-string-to-minutes (s)
17628 "Convert a string H:MM to a number of minutes.
17629 If the string is just a number, interpret it as minutes.
17630 In fact, the first hh:mm or number in the string will be taken,
17631 there can be extra stuff in the string.
17632 If no number is found, the return value is 0."
17633 (cond
17634 ((integerp s) s)
17635 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17636 (+ (* (string-to-number (match-string 1 s)) 60)
17637 (string-to-number (match-string 2 s))))
17638 ((string-match "\\([0-9]+\\)" s)
17639 (string-to-number (match-string 1 s)))
17640 (t 0)))
17642 (defcustom org-image-actual-width t
17643 "Should we use the actual width of images when inlining them?
17645 When set to `t', always use the image width.
17647 When set to a number, use imagemagick (when available) to set
17648 the image's width to this value.
17650 When set to a number in a list, try to get the width from any
17651 #+ATTR.* keyword if it matches a width specification like
17653 #+ATTR_HTML: :width 300px
17655 and fall back on that number if none is found.
17657 When set to nil, try to get the width from an #+ATTR.* keyword
17658 and fall back on the original width if none is found.
17660 This requires Emacs >= 24.1, build with imagemagick support."
17661 :group 'org-appearance
17662 :version "24.4"
17663 :package-version '(Org . "8.0")
17664 :type '(choice
17665 (const :tag "Use the image width" t)
17666 (integer :tag "Use a number of pixels")
17667 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17668 (const :tag "Use #+ATTR* or don't resize" nil)))
17670 (defcustom org-agenda-inhibit-startup nil
17671 "Inhibit startup when preparing agenda buffers.
17672 When this variable is `t' (the default), the initialization of
17673 the Org agenda buffers is inhibited: e.g. the visibility state
17674 is not set, the tables are not re-aligned, etc."
17675 :type 'boolean
17676 :version "24.3"
17677 :group 'org-agenda)
17679 (defcustom org-agenda-ignore-drawer-properties nil
17680 "Avoid updating text properties when building the agenda.
17681 Properties are used to prepare buffers for effort estimates, appointments,
17682 and subtree-local categories.
17683 If you don't use these in the agenda, you can add them to this list and
17684 agenda building will be a bit faster.
17685 The value is a list, with zero or more of the symbols `effort', `appt',
17686 or `category'."
17687 :type '(set :greedy t
17688 (const effort)
17689 (const appt)
17690 (const category))
17691 :version "24.3"
17692 :group 'org-agenda)
17694 (defun org-duration-string-to-minutes (s &optional output-to-string)
17695 "Convert a duration string S to minutes.
17697 A bare number is interpreted as minutes, modifiers can be set by
17698 customizing `org-effort-durations' (which see).
17700 Entries containing a colon are interpreted as H:MM by
17701 `org-hh:mm-string-to-minutes'."
17702 (let ((result 0)
17703 (re (concat "\\([0-9.]+\\) *\\("
17704 (regexp-opt (mapcar 'car org-effort-durations))
17705 "\\)")))
17706 (while (string-match re s)
17707 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17708 (string-to-number (match-string 1 s))))
17709 (setq s (replace-match "" nil t s)))
17710 (setq result (floor result))
17711 (incf result (org-hh:mm-string-to-minutes s))
17712 (if output-to-string (number-to-string result) result)))
17714 ;;;; Files
17716 (defun org-save-all-org-buffers ()
17717 "Save all Org-mode buffers without user confirmation."
17718 (interactive)
17719 (message "Saving all Org-mode buffers...")
17720 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17721 (when (featurep 'org-id) (org-id-locations-save))
17722 (message "Saving all Org-mode buffers... done"))
17724 (defun org-revert-all-org-buffers ()
17725 "Revert all Org-mode buffers.
17726 Prompt for confirmation when there are unsaved changes.
17727 Be sure you know what you are doing before letting this function
17728 overwrite your changes.
17730 This function is useful in a setup where one tracks org files
17731 with a version control system, to revert on one machine after pulling
17732 changes from another. I believe the procedure must be like this:
17734 1. M-x org-save-all-org-buffers
17735 2. Pull changes from the other machine, resolve conflicts
17736 3. M-x org-revert-all-org-buffers"
17737 (interactive)
17738 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17739 (user-error "Abort"))
17740 (save-excursion
17741 (save-window-excursion
17742 (mapc
17743 (lambda (b)
17744 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17745 (with-current-buffer b buffer-file-name))
17746 (org-pop-to-buffer-same-window b)
17747 (revert-buffer t 'no-confirm)))
17748 (buffer-list))
17749 (when (and (featurep 'org-id) org-id-track-globally)
17750 (org-id-locations-load)))))
17752 ;;;; Agenda files
17754 ;;;###autoload
17755 (defun org-switchb (&optional arg)
17756 "Switch between Org buffers.
17757 With one prefix argument, restrict available buffers to files.
17758 With two prefix arguments, restrict available buffers to agenda files.
17760 Defaults to `iswitchb' for buffer name completion.
17761 Set `org-completion-use-ido' to make it use ido instead."
17762 (interactive "P")
17763 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17764 ((equal arg '(16)) (org-buffer-list 'agenda))
17765 (t (org-buffer-list))))
17766 (org-completion-use-iswitchb org-completion-use-iswitchb)
17767 (org-completion-use-ido org-completion-use-ido))
17768 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17769 (setq org-completion-use-iswitchb t))
17770 (org-pop-to-buffer-same-window
17771 (org-icompleting-read "Org buffer: "
17772 (mapcar 'list (mapcar 'buffer-name blist))
17773 nil t))))
17775 ;;; Define some older names previously used for this functionality
17776 ;;;###autoload
17777 (defalias 'org-ido-switchb 'org-switchb)
17778 ;;;###autoload
17779 (defalias 'org-iswitchb 'org-switchb)
17781 (defun org-buffer-list (&optional predicate exclude-tmp)
17782 "Return a list of Org buffers.
17783 PREDICATE can be `export', `files' or `agenda'.
17785 export restrict the list to Export buffers.
17786 files restrict the list to buffers visiting Org files.
17787 agenda restrict the list to buffers visiting agenda files.
17789 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17790 (let* ((bfn nil)
17791 (agenda-files (and (eq predicate 'agenda)
17792 (mapcar 'file-truename (org-agenda-files t))))
17793 (filter
17794 (cond
17795 ((eq predicate 'files)
17796 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17797 ((eq predicate 'export)
17798 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17799 ((eq predicate 'agenda)
17800 (lambda (b)
17801 (with-current-buffer b
17802 (and (derived-mode-p 'org-mode)
17803 (setq bfn (buffer-file-name b))
17804 (member (file-truename bfn) agenda-files)))))
17805 (t (lambda (b) (with-current-buffer b
17806 (or (derived-mode-p 'org-mode)
17807 (string-match "\*Org .*Export"
17808 (buffer-name b)))))))))
17809 (delq nil
17810 (mapcar
17811 (lambda(b)
17812 (if (and (funcall filter b)
17813 (or (not exclude-tmp)
17814 (not (string-match "tmp" (buffer-name b)))))
17816 nil))
17817 (buffer-list)))))
17819 (defun org-agenda-files (&optional unrestricted archives)
17820 "Get the list of agenda files.
17821 Optional UNRESTRICTED means return the full list even if a restriction
17822 is currently in place.
17823 When ARCHIVES is t, include all archive files that are really being
17824 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17825 `org-agenda-archives-mode' is t."
17826 (let ((files
17827 (cond
17828 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17829 ((stringp org-agenda-files) (org-read-agenda-file-list))
17830 ((listp org-agenda-files) org-agenda-files)
17831 (t (error "Invalid value of `org-agenda-files'")))))
17832 (setq files (apply 'append
17833 (mapcar (lambda (f)
17834 (if (file-directory-p f)
17835 (directory-files
17836 f t org-agenda-file-regexp)
17837 (list f)))
17838 files)))
17839 (when org-agenda-skip-unavailable-files
17840 (setq files (delq nil
17841 (mapcar (function
17842 (lambda (file)
17843 (and (file-readable-p file) file)))
17844 files))))
17845 (when (or (eq archives t)
17846 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17847 (setq files (org-add-archive-files files)))
17848 files))
17850 (defun org-agenda-file-p (&optional file)
17851 "Return non-nil, if FILE is an agenda file.
17852 If FILE is omitted, use the file associated with the current
17853 buffer."
17854 (member (or file (buffer-file-name))
17855 (org-agenda-files t)))
17857 (defun org-edit-agenda-file-list ()
17858 "Edit the list of agenda files.
17859 Depending on setup, this either uses customize to edit the variable
17860 `org-agenda-files', or it visits the file that is holding the list. In the
17861 latter case, the buffer is set up in a way that saving it automatically kills
17862 the buffer and restores the previous window configuration."
17863 (interactive)
17864 (if (stringp org-agenda-files)
17865 (let ((cw (current-window-configuration)))
17866 (find-file org-agenda-files)
17867 (org-set-local 'org-window-configuration cw)
17868 (org-add-hook 'after-save-hook
17869 (lambda ()
17870 (set-window-configuration
17871 (prog1 org-window-configuration
17872 (kill-buffer (current-buffer))))
17873 (org-install-agenda-files-menu)
17874 (message "New agenda file list installed"))
17875 nil 'local)
17876 (message "%s" (substitute-command-keys
17877 "Edit list and finish with \\[save-buffer]")))
17878 (customize-variable 'org-agenda-files)))
17880 (defun org-store-new-agenda-file-list (list)
17881 "Set new value for the agenda file list and save it correctly."
17882 (if (stringp org-agenda-files)
17883 (let ((fe (org-read-agenda-file-list t)) b u)
17884 (while (setq b (find-buffer-visiting org-agenda-files))
17885 (kill-buffer b))
17886 (with-temp-file org-agenda-files
17887 (insert
17888 (mapconcat
17889 (lambda (f) ;; Keep un-expanded entries.
17890 (if (setq u (assoc f fe))
17891 (cdr u)
17893 list "\n")
17894 "\n")))
17895 (let ((org-mode-hook nil) (org-inhibit-startup t)
17896 (org-insert-mode-line-in-empty-file nil))
17897 (setq org-agenda-files list)
17898 (customize-save-variable 'org-agenda-files org-agenda-files))))
17900 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17901 "Read the list of agenda files from a file.
17902 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17903 filenames, used by `org-store-new-agenda-file-list' to write back
17904 un-expanded file names."
17905 (when (file-directory-p org-agenda-files)
17906 (error "`org-agenda-files' cannot be a single directory"))
17907 (when (stringp org-agenda-files)
17908 (with-temp-buffer
17909 (insert-file-contents org-agenda-files)
17910 (mapcar
17911 (lambda (f)
17912 (let ((e (expand-file-name (substitute-in-file-name f)
17913 org-directory)))
17914 (if pair-with-expansion
17915 (cons e f)
17916 e)))
17917 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17919 ;;;###autoload
17920 (defun org-cycle-agenda-files ()
17921 "Cycle through the files in `org-agenda-files'.
17922 If the current buffer visits an agenda file, find the next one in the list.
17923 If the current buffer does not, find the first agenda file."
17924 (interactive)
17925 (let* ((fs (org-agenda-files t))
17926 (files (append fs (list (car fs))))
17927 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17928 file)
17929 (unless files (user-error "No agenda files"))
17930 (catch 'exit
17931 (while (setq file (pop files))
17932 (if (equal (file-truename file) tcf)
17933 (when (car files)
17934 (find-file (car files))
17935 (throw 'exit t))))
17936 (find-file (car fs)))
17937 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17939 (defun org-agenda-file-to-front (&optional to-end)
17940 "Move/add the current file to the top of the agenda file list.
17941 If the file is not present in the list, it is added to the front. If it is
17942 present, it is moved there. With optional argument TO-END, add/move to the
17943 end of the list."
17944 (interactive "P")
17945 (let ((org-agenda-skip-unavailable-files nil)
17946 (file-alist (mapcar (lambda (x)
17947 (cons (file-truename x) x))
17948 (org-agenda-files t)))
17949 (ctf (file-truename
17950 (or buffer-file-name
17951 (user-error "Please save the current buffer to a file"))))
17952 x had)
17953 (setq x (assoc ctf file-alist) had x)
17955 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17956 (if to-end
17957 (setq file-alist (append (delq x file-alist) (list x)))
17958 (setq file-alist (cons x (delq x file-alist))))
17959 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17960 (org-install-agenda-files-menu)
17961 (message "File %s to %s of agenda file list"
17962 (if had "moved" "added") (if to-end "end" "front"))))
17964 (defun org-remove-file (&optional file)
17965 "Remove current file from the list of files in variable `org-agenda-files'.
17966 These are the files which are being checked for agenda entries.
17967 Optional argument FILE means use this file instead of the current."
17968 (interactive)
17969 (let* ((org-agenda-skip-unavailable-files nil)
17970 (file (or file buffer-file-name
17971 (user-error "Current buffer does not visit a file")))
17972 (true-file (file-truename file))
17973 (afile (abbreviate-file-name file))
17974 (files (delq nil (mapcar
17975 (lambda (x)
17976 (if (equal true-file
17977 (file-truename x))
17978 nil x))
17979 (org-agenda-files t)))))
17980 (if (not (= (length files) (length (org-agenda-files t))))
17981 (progn
17982 (org-store-new-agenda-file-list files)
17983 (org-install-agenda-files-menu)
17984 (message "Removed file: %s" afile))
17985 (message "File was not in list: %s (not removed)" afile))))
17987 (defun org-file-menu-entry (file)
17988 (vector file (list 'find-file file) t))
17990 (defun org-check-agenda-file (file)
17991 "Make sure FILE exists. If not, ask user what to do."
17992 (when (not (file-exists-p file))
17993 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17994 (abbreviate-file-name file))
17995 (let ((r (downcase (read-char-exclusive))))
17996 (cond
17997 ((equal r ?r)
17998 (org-remove-file file)
17999 (throw 'nextfile t))
18000 (t (error "Abort"))))))
18002 (defun org-get-agenda-file-buffer (file)
18003 "Get a buffer visiting FILE. If the buffer needs to be created, add
18004 it to the list of buffers which might be released later."
18005 (let ((buf (org-find-base-buffer-visiting file)))
18006 (if buf
18007 buf ; just return it
18008 ;; Make a new buffer and remember it
18009 (setq buf (find-file-noselect file))
18010 (if buf (push buf org-agenda-new-buffers))
18011 buf)))
18013 (defun org-release-buffers (blist)
18014 "Release all buffers in list, asking the user for confirmation when needed.
18015 When a buffer is unmodified, it is just killed. When modified, it is saved
18016 \(if the user agrees) and then killed."
18017 (let (buf file)
18018 (while (setq buf (pop blist))
18019 (setq file (buffer-file-name buf))
18020 (when (and (buffer-modified-p buf)
18021 file
18022 (y-or-n-p (format "Save file %s? " file)))
18023 (with-current-buffer buf (save-buffer)))
18024 (kill-buffer buf))))
18026 (defun org-agenda-prepare-buffers (files)
18027 "Create buffers for all agenda files, protect archived trees and comments."
18028 (interactive)
18029 (let ((pa '(:org-archived t))
18030 (pc '(:org-comment t))
18031 (pall '(:org-archived t :org-comment t))
18032 (inhibit-read-only t)
18033 (org-inhibit-startup org-agenda-inhibit-startup)
18034 (rea (concat ":" org-archive-tag ":"))
18035 file re)
18036 (setq org-tag-alist-for-agenda nil
18037 org-tag-groups-alist-for-agenda nil)
18038 (save-excursion
18039 (save-restriction
18040 (while (setq file (pop files))
18041 (catch 'nextfile
18042 (if (bufferp file)
18043 (set-buffer file)
18044 (org-check-agenda-file file)
18045 (set-buffer (org-get-agenda-file-buffer file)))
18046 (widen)
18047 (org-set-regexps-and-options-for-tags)
18048 (goto-char (point-min))
18049 (let ((case-fold-search t))
18050 (when (search-forward "#+setupfile" nil t)
18051 ;; Don't set all regexps and options systematically as
18052 ;; this is only run for setting agenda tags from setup
18053 ;; file
18054 (org-set-regexps-and-options)))
18055 (or (memq 'category org-agenda-ignore-drawer-properties)
18056 (org-refresh-category-properties))
18057 (or (memq 'effort org-agenda-ignore-drawer-properties)
18058 (org-refresh-properties org-effort-property 'org-effort))
18059 (or (memq 'appt org-agenda-ignore-drawer-properties)
18060 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18061 (setq org-todo-keywords-for-agenda
18062 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18063 (setq org-done-keywords-for-agenda
18064 (append org-done-keywords-for-agenda org-done-keywords))
18065 (setq org-todo-keyword-alist-for-agenda
18066 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18067 (setq org-drawers-for-agenda
18068 (append org-drawers-for-agenda org-drawers))
18069 (setq org-tag-alist-for-agenda
18070 (org-uniquify
18071 (append org-tag-alist-for-agenda
18072 org-tag-alist
18073 org-tag-persistent-alist)))
18074 (if org-group-tags
18075 (setq org-tag-groups-alist-for-agenda
18076 (org-uniquify-alist
18077 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18078 (org-with-silent-modifications
18079 (save-excursion
18080 (remove-text-properties (point-min) (point-max) pall)
18081 (when org-agenda-skip-archived-trees
18082 (goto-char (point-min))
18083 (while (re-search-forward rea nil t)
18084 (if (org-at-heading-p t)
18085 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18086 (goto-char (point-min))
18087 (setq re (format org-heading-keyword-regexp-format
18088 org-comment-string))
18089 (while (re-search-forward re nil t)
18090 (add-text-properties
18091 (match-beginning 0) (org-end-of-subtree t) pc))))))))
18092 (setq org-todo-keywords-for-agenda
18093 (org-uniquify org-todo-keywords-for-agenda))
18094 (setq org-todo-keyword-alist-for-agenda
18095 (org-uniquify org-todo-keyword-alist-for-agenda))))
18098 ;;;; CDLaTeX minor mode
18100 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18101 "Keymap for the minor `org-cdlatex-mode'.")
18103 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18104 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18105 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18106 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18107 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
18109 (defvar org-cdlatex-texmathp-advice-is-done nil
18110 "Flag remembering if we have applied the advice to texmathp already.")
18112 (define-minor-mode org-cdlatex-mode
18113 "Toggle the minor `org-cdlatex-mode'.
18114 This mode supports entering LaTeX environment and math in LaTeX fragments
18115 in Org-mode.
18116 \\{org-cdlatex-mode-map}"
18117 nil " OCDL" nil
18118 (when org-cdlatex-mode
18119 (require 'cdlatex)
18120 (run-hooks 'cdlatex-mode-hook)
18121 (cdlatex-compute-tables))
18122 (unless org-cdlatex-texmathp-advice-is-done
18123 (setq org-cdlatex-texmathp-advice-is-done t)
18124 (defadvice texmathp (around org-math-always-on activate)
18125 "Always return t in org-mode buffers.
18126 This is because we want to insert math symbols without dollars even outside
18127 the LaTeX math segments. If Orgmode thinks that point is actually inside
18128 an embedded LaTeX fragment, let texmathp do its job.
18129 \\[org-cdlatex-mode-map]"
18130 (interactive)
18131 (let (p)
18132 (cond
18133 ((not (derived-mode-p 'org-mode)) ad-do-it)
18134 ((eq this-command 'cdlatex-math-symbol)
18135 (setq ad-return-value t
18136 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18138 (let ((p (org-inside-LaTeX-fragment-p)))
18139 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18140 (setq ad-return-value t
18141 texmathp-why '("Org-mode embedded math" . 0))
18142 (if p ad-do-it)))))))))
18144 (defun turn-on-org-cdlatex ()
18145 "Unconditionally turn on `org-cdlatex-mode'."
18146 (org-cdlatex-mode 1))
18148 (defun org-try-cdlatex-tab ()
18149 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18150 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18151 - inside a LaTeX fragment, or
18152 - after the first word in a line, where an abbreviation expansion could
18153 insert a LaTeX environment."
18154 (when org-cdlatex-mode
18155 (cond
18156 ;; Before any word on the line: No expansion possible.
18157 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18158 ;; Just after first word on the line: Expand it. Make sure it
18159 ;; cannot happen on headlines, though.
18160 ((save-excursion
18161 (skip-chars-backward "a-zA-Z0-9*")
18162 (skip-chars-backward " \t")
18163 (and (bolp) (not (org-at-heading-p))))
18164 (cdlatex-tab) t)
18165 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18167 (defun org-cdlatex-underscore-caret (&optional arg)
18168 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18169 Revert to the normal definition outside of these fragments."
18170 (interactive "P")
18171 (if (org-inside-LaTeX-fragment-p)
18172 (call-interactively 'cdlatex-sub-superscript)
18173 (let (org-cdlatex-mode)
18174 (call-interactively (key-binding (vector last-input-event))))))
18176 (defun org-cdlatex-math-modify (&optional arg)
18177 "Execute `cdlatex-math-modify' in LaTeX fragments.
18178 Revert to the normal definition outside of these fragments."
18179 (interactive "P")
18180 (if (org-inside-LaTeX-fragment-p)
18181 (call-interactively 'cdlatex-math-modify)
18182 (let (org-cdlatex-mode)
18183 (call-interactively (key-binding (vector last-input-event))))))
18187 ;;;; LaTeX fragments
18189 (defvar org-latex-regexps
18190 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
18191 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
18192 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
18193 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18194 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18195 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
18196 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
18197 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
18198 "Regular expressions for matching embedded LaTeX.")
18200 (defun org-inside-LaTeX-fragment-p ()
18201 "Test if point is inside a LaTeX fragment.
18202 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18203 sequence appearing also before point.
18204 Even though the matchers for math are configurable, this function assumes
18205 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18206 delimiters are skipped when they have been removed by customization.
18207 The return value is nil, or a cons cell with the delimiter and the
18208 position of this delimiter.
18210 This function does a reasonably good job, but can locally be fooled by
18211 for example currency specifications. For example it will assume being in
18212 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18213 fragments that are properly closed, but during editing, we have to live
18214 with the uncertainty caused by missing closing delimiters. This function
18215 looks only before point, not after."
18216 (catch 'exit
18217 (let ((pos (point))
18218 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18219 (lim (progn
18220 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18221 (point)))
18222 dd-on str (start 0) m re)
18223 (goto-char pos)
18224 (when dodollar
18225 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18226 re (nth 1 (assoc "$" org-latex-regexps)))
18227 (while (string-match re str start)
18228 (cond
18229 ((= (match-end 0) (length str))
18230 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18231 ((= (match-end 0) (- (length str) 5))
18232 (throw 'exit nil))
18233 (t (setq start (match-end 0))))))
18234 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18235 (goto-char pos)
18236 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18237 (and (match-beginning 2) (throw 'exit nil))
18238 ;; count $$
18239 (while (re-search-backward "\\$\\$" lim t)
18240 (setq dd-on (not dd-on)))
18241 (goto-char pos)
18242 (if dd-on (cons "$$" m))))))
18244 (defun org-inside-latex-macro-p ()
18245 "Is point inside a LaTeX macro or its arguments?"
18246 (save-match-data
18247 (org-in-regexp
18248 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18250 (defvar org-latex-fragment-image-overlays nil
18251 "List of overlays carrying the images of latex fragments.")
18252 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18254 (defun org-remove-latex-fragment-image-overlays ()
18255 "Remove all overlays with LaTeX fragment images in current buffer."
18256 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18257 (setq org-latex-fragment-image-overlays nil))
18259 (defun org-preview-latex-fragment (&optional subtree)
18260 "Preview the LaTeX fragment at point, or all locally or globally.
18261 If the cursor is in a LaTeX fragment, create the image and overlay
18262 it over the source code. If there is no fragment at point, display
18263 all fragments in the current text, from one headline to the next. With
18264 prefix SUBTREE, display all fragments in the current subtree. With a
18265 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18266 the cursor is before the first headline,
18267 display all fragments in the buffer.
18268 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18269 (interactive "P")
18270 (unless buffer-file-name
18271 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18272 (when (display-graphic-p)
18273 (org-remove-latex-fragment-image-overlays)
18274 (save-excursion
18275 (save-restriction
18276 (let (beg end at msg)
18277 (cond
18278 ((or (equal subtree '(16))
18279 (not (save-excursion
18280 (re-search-backward org-outline-regexp-bol nil t))))
18281 (setq beg (point-min) end (point-max)
18282 msg "Creating images for buffer...%s"))
18283 ((equal subtree '(4))
18284 (org-back-to-heading)
18285 (setq beg (point) end (org-end-of-subtree t)
18286 msg "Creating images for subtree...%s"))
18288 (if (setq at (org-inside-LaTeX-fragment-p))
18289 (goto-char (max (point-min) (- (cdr at) 2)))
18290 (org-back-to-heading))
18291 (setq beg (point) end (progn (outline-next-heading) (point))
18292 msg (if at "Creating image...%s"
18293 "Creating images for entry...%s"))))
18294 (message msg "")
18295 (narrow-to-region beg end)
18296 (goto-char beg)
18297 (org-format-latex
18298 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18299 (file-name-nondirectory
18300 buffer-file-name)))
18301 default-directory 'overlays msg at 'forbuffer
18302 org-latex-create-formula-image-program)
18303 (message msg "done. Use `C-c C-c' to remove images."))))))
18305 (defun org-format-latex (prefix &optional dir overlays msg at
18306 forbuffer processing-type)
18307 "Replace LaTeX fragments with links to an image, and produce images.
18308 Some of the options can be changed using the variable
18309 `org-format-latex-options'."
18310 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18311 (let* ((prefixnodir (file-name-nondirectory prefix))
18312 (absprefix (expand-file-name prefix dir))
18313 (todir (file-name-directory absprefix))
18314 (opt org-format-latex-options)
18315 (optnew org-format-latex-options)
18316 (matchers (plist-get opt :matchers))
18317 (re-list org-latex-regexps)
18318 (cnt 0) txt hash link beg end re e checkdir
18319 string
18320 m n block-type block linkfile movefile ov)
18321 ;; Check the different regular expressions
18322 (while (setq e (pop re-list))
18323 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18324 block (if block-type "\n\n" ""))
18325 (when (member m matchers)
18326 (goto-char (point-min))
18327 (while (re-search-forward re nil t)
18328 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18329 (or (not overlays)
18330 (not (eq (get-char-property (match-beginning n)
18331 'org-overlay-type)
18332 'org-latex-overlay))))
18333 (cond
18334 ((eq processing-type 'verbatim))
18335 ((eq processing-type 'mathjax)
18336 ;; Prepare for MathJax processing.
18337 (setq string (match-string n))
18338 (when (member m '("$" "$1"))
18339 (save-excursion
18340 (delete-region (match-beginning n) (match-end n))
18341 (goto-char (match-beginning n))
18342 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18343 ((or (eq processing-type 'dvipng)
18344 (eq processing-type 'imagemagick))
18345 ;; Process to an image.
18346 (setq txt (match-string n)
18347 beg (match-beginning n) end (match-end n)
18348 cnt (1+ cnt))
18349 (let ((face (face-at-point))
18350 (fg (plist-get opt :foreground))
18351 (bg (plist-get opt :background))
18352 ;; Ensure full list is printed.
18353 print-length print-level)
18354 (when forbuffer
18355 ;; Get the colors from the face at point.
18356 (goto-char beg)
18357 (when (eq fg 'auto)
18358 (setq fg (face-attribute face :foreground nil 'default)))
18359 (when (eq bg 'auto)
18360 (setq bg (face-attribute face :background nil 'default)))
18361 (setq optnew (copy-sequence opt))
18362 (plist-put optnew :foreground fg)
18363 (plist-put optnew :background bg))
18364 (setq hash (sha1 (prin1-to-string
18365 (list org-format-latex-header
18366 org-latex-default-packages-alist
18367 org-latex-packages-alist
18368 org-format-latex-options
18369 forbuffer txt fg bg)))
18370 linkfile (format "%s_%s.png" prefix hash)
18371 movefile (format "%s_%s.png" absprefix hash)))
18372 (setq link (concat block "[[file:" linkfile "]]" block))
18373 (if msg (message msg cnt))
18374 (goto-char beg)
18375 (unless checkdir ; Ensure the directory exists.
18376 (setq checkdir t)
18377 (or (file-directory-p todir) (make-directory todir t)))
18378 (unless (file-exists-p movefile)
18379 (org-create-formula-image
18380 txt movefile optnew forbuffer processing-type))
18381 (if overlays
18382 (progn
18383 (mapc (lambda (o)
18384 (if (eq (overlay-get o 'org-overlay-type)
18385 'org-latex-overlay)
18386 (delete-overlay o)))
18387 (overlays-in beg end))
18388 (setq ov (make-overlay beg end))
18389 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18390 (if (featurep 'xemacs)
18391 (progn
18392 (overlay-put ov 'invisible t)
18393 (overlay-put
18394 ov 'end-glyph
18395 (make-glyph (vector 'png :file movefile))))
18396 (overlay-put
18397 ov 'display
18398 (list 'image :type 'png :file movefile :ascent 'center)))
18399 (push ov org-latex-fragment-image-overlays)
18400 (goto-char end))
18401 (delete-region beg end)
18402 (insert (org-add-props link
18403 (list 'org-latex-src
18404 (replace-regexp-in-string
18405 "\"" "" txt)
18406 'org-latex-src-embed-type
18407 (if block-type 'paragraph 'character))))))
18408 ((eq processing-type 'mathml)
18409 ;; Process to MathML
18410 (unless (save-match-data (org-format-latex-mathml-available-p))
18411 (user-error "LaTeX to MathML converter not configured"))
18412 (setq txt (match-string n)
18413 beg (match-beginning n) end (match-end n)
18414 cnt (1+ cnt))
18415 (if msg (message msg cnt))
18416 (goto-char beg)
18417 (delete-region beg end)
18418 (insert (org-format-latex-as-mathml
18419 txt block-type prefix dir)))
18421 (error "Unknown conversion type %s for LaTeX fragments"
18422 processing-type)))))))))
18424 (defun org-create-math-formula (latex-frag &optional mathml-file)
18425 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18426 Use `org-latex-to-mathml-convert-command'. If the conversion is
18427 sucessful, return the portion between \"<math...> </math>\"
18428 elements otherwise return nil. When MATHML-FILE is specified,
18429 write the results in to that file. When invoked as an
18430 interactive command, prompt for LATEX-FRAG, with initial value
18431 set to the current active region and echo the results for user
18432 inspection."
18433 (interactive (list (let ((frag (when (org-region-active-p)
18434 (buffer-substring-no-properties
18435 (region-beginning) (region-end)))))
18436 (read-string "LaTeX Fragment: " frag nil frag))))
18437 (unless latex-frag (error "Invalid LaTeX fragment"))
18438 (let* ((tmp-in-file (file-relative-name
18439 (make-temp-name (expand-file-name "ltxmathml-in"))))
18440 (ignore (write-region latex-frag nil tmp-in-file))
18441 (tmp-out-file (file-relative-name
18442 (make-temp-name (expand-file-name "ltxmathml-out"))))
18443 (cmd (format-spec
18444 org-latex-to-mathml-convert-command
18445 `((?j . ,(shell-quote-argument
18446 (expand-file-name org-latex-to-mathml-jar-file)))
18447 (?I . ,(shell-quote-argument tmp-in-file))
18448 (?o . ,(shell-quote-argument tmp-out-file)))))
18449 mathml shell-command-output)
18450 (when (org-called-interactively-p 'any)
18451 (unless (org-format-latex-mathml-available-p)
18452 (user-error "LaTeX to MathML converter not configured")))
18453 (message "Running %s" cmd)
18454 (setq shell-command-output (shell-command-to-string cmd))
18455 (setq mathml
18456 (when (file-readable-p tmp-out-file)
18457 (with-current-buffer (find-file-noselect tmp-out-file t)
18458 (goto-char (point-min))
18459 (when (re-search-forward
18460 (concat
18461 (regexp-quote
18462 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18463 "\\(.\\|\n\\)*"
18464 (regexp-quote "</math>")) nil t)
18465 (prog1 (match-string 0) (kill-buffer))))))
18466 (cond
18467 (mathml
18468 (setq mathml
18469 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18470 (when mathml-file
18471 (write-region mathml nil mathml-file))
18472 (when (org-called-interactively-p 'any)
18473 (message mathml)))
18474 ((message "LaTeX to MathML conversion failed")
18475 (message shell-command-output)))
18476 (delete-file tmp-in-file)
18477 (when (file-exists-p tmp-out-file)
18478 (delete-file tmp-out-file))
18479 mathml))
18481 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18482 prefix &optional dir)
18483 "Use `org-create-math-formula' but check local cache first."
18484 (let* ((absprefix (expand-file-name prefix dir))
18485 (print-length nil) (print-level nil)
18486 (formula-id (concat
18487 "formula-"
18488 (sha1
18489 (prin1-to-string
18490 (list latex-frag
18491 org-latex-to-mathml-convert-command)))))
18492 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18493 (formula-cache-dir (file-name-directory formula-cache)))
18495 (unless (file-directory-p formula-cache-dir)
18496 (make-directory formula-cache-dir t))
18498 (unless (file-exists-p formula-cache)
18499 (org-create-math-formula latex-frag formula-cache))
18501 (if (file-exists-p formula-cache)
18502 ;; Successful conversion. Return the link to MathML file.
18503 (org-add-props
18504 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18505 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18506 'org-latex-src-embed-type (if latex-frag-type
18507 'paragraph 'character)))
18508 ;; Failed conversion. Return the LaTeX fragment verbatim
18509 latex-frag)))
18511 (defun org-create-formula-image (string tofile options buffer &optional type)
18512 "Create an image from LaTeX source using dvipng or convert.
18513 This function calls either `org-create-formula-image-with-dvipng'
18514 or `org-create-formula-image-with-imagemagick' depending on the
18515 value of `org-latex-create-formula-image-program' or on the value
18516 of the optional TYPE variable.
18518 Note: ultimately these two function should be combined as they
18519 share a good deal of logic."
18520 (org-check-external-command
18521 "latex" "needed to convert LaTeX fragments to images")
18522 (funcall
18523 (case (or type org-latex-create-formula-image-program)
18524 ('dvipng
18525 (org-check-external-command
18526 "dvipng" "needed to convert LaTeX fragments to images")
18527 #'org-create-formula-image-with-dvipng)
18528 ('imagemagick
18529 (org-check-external-command
18530 "convert" "you need to install imagemagick")
18531 #'org-create-formula-image-with-imagemagick)
18532 (t (error
18533 "Invalid value of `org-latex-create-formula-image-program'")))
18534 string tofile options buffer))
18536 (declare-function org-export-get-backend "ox" (name))
18537 (declare-function org-export--get-global-options "ox" (&optional backend))
18538 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18539 (declare-function org-latex-guess-inputenc "ox-latex" (header))
18540 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
18541 (defun org-create-formula--latex-header ()
18542 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18543 (let ((info (org-combine-plists (org-export--get-global-options
18544 (org-export-get-backend 'latex))
18545 (org-export--get-inbuffer-options
18546 (org-export-get-backend 'latex)))))
18547 (org-latex-guess-babel-language
18548 (org-latex-guess-inputenc
18549 (org-splice-latex-header
18550 org-format-latex-header
18551 org-latex-default-packages-alist
18552 org-latex-packages-alist t
18553 (plist-get info :latex-header)))
18554 info)))
18556 ;; This function borrows from Ganesh Swami's latex2png.el
18557 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18558 "This calls dvipng."
18559 (require 'ox-latex)
18560 (let* ((tmpdir (if (featurep 'xemacs)
18561 (temp-directory)
18562 temporary-file-directory))
18563 (texfilebase (make-temp-name
18564 (expand-file-name "orgtex" tmpdir)))
18565 (texfile (concat texfilebase ".tex"))
18566 (dvifile (concat texfilebase ".dvi"))
18567 (pngfile (concat texfilebase ".png"))
18568 (fnh (if (featurep 'xemacs)
18569 (font-height (face-font 'default))
18570 (face-attribute 'default :height nil)))
18571 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18572 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18573 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18574 "Black"))
18575 (bg (or (plist-get options (if buffer :background :html-background))
18576 "Transparent")))
18577 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18578 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18579 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18580 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18581 (let ((latex-header (org-create-formula--latex-header)))
18582 (with-temp-file texfile
18583 (insert latex-header)
18584 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18585 (let ((dir default-directory))
18586 (condition-case nil
18587 (progn
18588 (cd tmpdir)
18589 (call-process "latex" nil nil nil texfile))
18590 (error nil))
18591 (cd dir))
18592 (if (not (file-exists-p dvifile))
18593 (progn (message "Failed to create dvi file from %s" texfile) nil)
18594 (condition-case nil
18595 (if (featurep 'xemacs)
18596 (call-process "dvipng" nil nil nil
18597 "-fg" fg "-bg" bg
18598 "-T" "tight"
18599 "-o" pngfile
18600 dvifile)
18601 (call-process "dvipng" nil nil nil
18602 "-fg" fg "-bg" bg
18603 "-D" dpi
18604 ;;"-x" scale "-y" scale
18605 "-T" "tight"
18606 "-o" pngfile
18607 dvifile))
18608 (error nil))
18609 (if (not (file-exists-p pngfile))
18610 (if org-format-latex-signal-error
18611 (error "Failed to create png file from %s" texfile)
18612 (message "Failed to create png file from %s" texfile)
18613 nil)
18614 ;; Use the requested file name and clean up
18615 (copy-file pngfile tofile 'replace)
18616 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18617 (if (file-exists-p (concat texfilebase e))
18618 (delete-file (concat texfilebase e))))
18619 pngfile))))
18621 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18622 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18623 "This calls convert, which is included into imagemagick."
18624 (require 'ox-latex)
18625 (let* ((tmpdir (if (featurep 'xemacs)
18626 (temp-directory)
18627 temporary-file-directory))
18628 (texfilebase (make-temp-name
18629 (expand-file-name "orgtex" tmpdir)))
18630 (texfile (concat texfilebase ".tex"))
18631 (pdffile (concat texfilebase ".pdf"))
18632 (pngfile (concat texfilebase ".png"))
18633 (fnh (if (featurep 'xemacs)
18634 (font-height (face-font 'default))
18635 (face-attribute 'default :height nil)))
18636 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18637 (dpi (number-to-string (* scale (floor (if buffer fnh 120.)))))
18638 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18639 "black"))
18640 (bg (or (plist-get options (if buffer :background :html-background))
18641 "white")))
18642 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18643 (setq fg (org-latex-color-format fg)))
18644 (if (eq bg 'default) (setq bg (org-latex-color :background))
18645 (setq bg (org-latex-color-format
18646 (if (string= bg "Transparent") "white" bg))))
18647 (let ((latex-header (org-create-formula--latex-header)))
18648 (with-temp-file texfile
18649 (insert latex-header)
18650 (insert "\n\\begin{document}\n"
18651 "\\definecolor{fg}{rgb}{" fg "}\n"
18652 "\\definecolor{bg}{rgb}{" bg "}\n"
18653 "\n\\pagecolor{bg}\n"
18654 "\n{\\color{fg}\n"
18655 string
18656 "\n}\n"
18657 "\n\\end{document}\n")))
18658 (org-latex-compile texfile t)
18659 (if (not (file-exists-p pdffile))
18660 (progn (message "Failed to create pdf file from %s" texfile) nil)
18661 (condition-case nil
18662 (if (featurep 'xemacs)
18663 (call-process "convert" nil nil nil
18664 "-density" "96"
18665 "-trim"
18666 "-antialias"
18667 pdffile
18668 "-quality" "100"
18669 ;; "-sharpen" "0x1.0"
18670 pngfile)
18671 (call-process "convert" nil nil nil
18672 "-density" dpi
18673 "-trim"
18674 "-antialias"
18675 pdffile
18676 "-quality" "100"
18677 ;; "-sharpen" "0x1.0"
18678 pngfile))
18679 (error nil))
18680 (if (not (file-exists-p pngfile))
18681 (if org-format-latex-signal-error
18682 (error "Failed to create png file from %s" texfile)
18683 (message "Failed to create png file from %s" texfile)
18684 nil)
18685 ;; Use the requested file name and clean up
18686 (copy-file pngfile tofile 'replace)
18687 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18688 (if (file-exists-p (concat texfilebase e))
18689 (delete-file (concat texfilebase e))))
18690 pngfile))))
18692 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18693 "Fill a LaTeX header template TPL.
18694 In the template, the following place holders will be recognized:
18696 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18697 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18698 [PACKAGES] \\usepackage statements for PKG
18699 [NO-PACKAGES] do not include PKG
18700 [EXTRA] the string EXTRA
18701 [NO-EXTRA] do not include EXTRA
18703 For backward compatibility, if both the positive and the negative place
18704 holder is missing, the positive one (without the \"NO-\") will be
18705 assumed to be present at the end of the template.
18706 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18707 EXTRA is a string.
18708 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18709 (let (rpl (end ""))
18710 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18711 (setq rpl (if (or (match-end 1) (not def-pkg))
18712 "" (org-latex-packages-to-string def-pkg snippets-p t))
18713 tpl (replace-match rpl t t tpl))
18714 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18716 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18717 (setq rpl (if (or (match-end 1) (not pkg))
18718 "" (org-latex-packages-to-string pkg snippets-p t))
18719 tpl (replace-match rpl t t tpl))
18720 (if pkg (setq end
18721 (concat end "\n"
18722 (org-latex-packages-to-string pkg snippets-p)))))
18724 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18725 (setq rpl (if (or (match-end 1) (not extra))
18726 "" (concat extra "\n"))
18727 tpl (replace-match rpl t t tpl))
18728 (if (and extra (string-match "\\S-" extra))
18729 (setq end (concat end "\n" extra))))
18731 (if (string-match "\\S-" end)
18732 (concat tpl "\n" end)
18733 tpl)))
18735 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18736 "Turn an alist of packages into a string with the \\usepackage macros."
18737 (setq pkg (mapconcat (lambda(p)
18738 (cond
18739 ((stringp p) p)
18740 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18741 (format "%% Package %s omitted" (cadr p)))
18742 ((equal "" (car p))
18743 (format "\\usepackage{%s}" (cadr p)))
18745 (format "\\usepackage[%s]{%s}"
18746 (car p) (cadr p)))))
18748 "\n"))
18749 (if newline (concat pkg "\n") pkg))
18751 (defun org-dvipng-color (attr)
18752 "Return a RGB color specification for dvipng."
18753 (apply 'format "rgb %s %s %s"
18754 (mapcar 'org-normalize-color
18755 (if (featurep 'xemacs)
18756 (color-rgb-components
18757 (face-property 'default
18758 (cond ((eq attr :foreground) 'foreground)
18759 ((eq attr :background) 'background))))
18760 (color-values (face-attribute 'default attr nil))))))
18762 (defun org-dvipng-color-format (color-name)
18763 "Convert COLOR-NAME to a RGB color value for dvipng."
18764 (apply 'format "rgb %s %s %s"
18765 (mapcar 'org-normalize-color
18766 (color-values color-name))))
18768 (defun org-latex-color (attr)
18769 "Return a RGB color for the LaTeX color package."
18770 (apply 'format "%s,%s,%s"
18771 (mapcar 'org-normalize-color
18772 (if (featurep 'xemacs)
18773 (color-rgb-components
18774 (face-property 'default
18775 (cond ((eq attr :foreground) 'foreground)
18776 ((eq attr :background) 'background))))
18777 (color-values (face-attribute 'default attr nil))))))
18779 (defun org-latex-color-format (color-name)
18780 "Convert COLOR-NAME to a RGB color value."
18781 (apply 'format "%s,%s,%s"
18782 (mapcar 'org-normalize-color
18783 (color-values color-name))))
18785 (defun org-normalize-color (value)
18786 "Return string to be used as color value for an RGB component."
18787 (format "%g" (/ value 65535.0)))
18791 ;; Image display
18793 (defvar org-inline-image-overlays nil)
18794 (make-variable-buffer-local 'org-inline-image-overlays)
18796 (defun org-toggle-inline-images (&optional include-linked)
18797 "Toggle the display of inline images.
18798 INCLUDE-LINKED is passed to `org-display-inline-images'."
18799 (interactive "P")
18800 (if org-inline-image-overlays
18801 (progn
18802 (org-remove-inline-images)
18803 (message "Inline image display turned off"))
18804 (org-display-inline-images include-linked)
18805 (if (and (org-called-interactively-p)
18806 org-inline-image-overlays)
18807 (message "%d images displayed inline"
18808 (length org-inline-image-overlays))
18809 (message "No images to display inline"))))
18811 (defun org-redisplay-inline-images ()
18812 "Refresh the display of inline images."
18813 (interactive)
18814 (if (not org-inline-image-overlays)
18815 (org-toggle-inline-images)
18816 (org-toggle-inline-images)
18817 (org-toggle-inline-images)))
18819 (defun org-display-inline-images (&optional include-linked refresh beg end)
18820 "Display inline images.
18821 Normally only links without a description part are inlined, because this
18822 is how it will work for export. When INCLUDE-LINKED is set, also links
18823 with a description part will be inlined. This can be nice for a quick
18824 look at those images, but it does not reflect what exported files will look
18825 like.
18826 When REFRESH is set, refresh existing images between BEG and END.
18827 This will create new image displays only if necessary.
18828 BEG and END default to the buffer boundaries."
18829 (interactive "P")
18830 (when (display-graphic-p)
18831 (unless refresh
18832 (org-remove-inline-images)
18833 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18834 (save-excursion
18835 (save-restriction
18836 (widen)
18837 (setq beg (or beg (point-min)) end (or end (point-max)))
18838 (goto-char beg)
18839 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18840 (substring (org-image-file-name-regexp) 0 -2)
18841 "\\)\\]" (if include-linked "" "\\]")))
18842 (case-fold-search t)
18843 old file ov img type attrwidth width)
18844 (while (re-search-forward re end t)
18845 (setq old (get-char-property-and-overlay (match-beginning 1)
18846 'org-image-overlay)
18847 file (expand-file-name
18848 (concat (or (match-string 3) "") (match-string 4))))
18849 (when (image-type-available-p 'imagemagick)
18850 (setq attrwidth (if (or (listp org-image-actual-width)
18851 (null org-image-actual-width))
18852 (save-excursion
18853 (save-match-data
18854 (when (re-search-backward
18855 "#\\+attr.*:width[ \t]+\\([^ ]+\\)"
18856 (save-excursion
18857 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18858 (string-to-number (match-string 1))))))
18859 width (cond ((eq org-image-actual-width t) nil)
18860 ((null org-image-actual-width) attrwidth)
18861 ((numberp org-image-actual-width)
18862 org-image-actual-width)
18863 ((listp org-image-actual-width)
18864 (or attrwidth (car org-image-actual-width))))
18865 type (if width 'imagemagick)))
18866 (when (file-exists-p file)
18867 (if (and (car-safe old) refresh)
18868 (image-refresh (overlay-get (cdr old) 'display))
18869 (setq img (save-match-data (create-image file type nil :width width)))
18870 (when img
18871 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18872 (overlay-put ov 'display img)
18873 (overlay-put ov 'face 'default)
18874 (overlay-put ov 'org-image-overlay t)
18875 (overlay-put ov 'modification-hooks
18876 (list 'org-display-inline-remove-overlay))
18877 (push ov org-inline-image-overlays))))))))))
18879 (define-obsolete-function-alias
18880 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18882 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18883 "Remove inline-display overlay if a corresponding region is modified."
18884 (let ((inhibit-modification-hooks t))
18885 (when (and ov after)
18886 (delete ov org-inline-image-overlays)
18887 (delete-overlay ov))))
18889 (defun org-remove-inline-images ()
18890 "Remove inline display of images."
18891 (interactive)
18892 (mapc 'delete-overlay org-inline-image-overlays)
18893 (setq org-inline-image-overlays nil))
18895 ;;;; Key bindings
18897 ;; Outline functions from `outline-mode-prefix-map'
18898 ;; that can be remapped in Org:
18899 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18900 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18901 (define-key org-mode-map [remap outline-forward-same-level]
18902 'org-forward-heading-same-level)
18903 (define-key org-mode-map [remap outline-backward-same-level]
18904 'org-backward-heading-same-level)
18905 (define-key org-mode-map [remap show-branches]
18906 'org-kill-note-or-show-branches)
18907 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18908 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18909 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18911 ;; Outline functions from `outline-mode-prefix-map' that can not
18912 ;; be remapped in Org:
18914 ;; - the column "key binding" shows whether the Outline function is still
18915 ;; available in Org mode on the same key that it has been bound to in
18916 ;; Outline mode:
18917 ;; - "overridden": key used for a different functionality in Org mode
18918 ;; - else: key still bound to the same Outline function in Org mode
18920 ;; | Outline function | key binding | Org replacement |
18921 ;; |------------------------------------+-------------+-----------------------|
18922 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18923 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18924 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18925 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18926 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18927 ;; | `show-entry' | overridden | no replacement |
18928 ;; | `show-children' | `C-c C-i' | visibility cycling |
18929 ;; | `show-branches' | `C-c C-k' | still same function |
18930 ;; | `show-subtree' | overridden | visibility cycling |
18931 ;; | `show-all' | overridden | no replacement |
18932 ;; | `hide-subtree' | overridden | visibility cycling |
18933 ;; | `hide-body' | overridden | no replacement |
18934 ;; | `hide-entry' | overridden | visibility cycling |
18935 ;; | `hide-leaves' | overridden | no replacement |
18936 ;; | `hide-sublevels' | overridden | no replacement |
18937 ;; | `hide-other' | overridden | no replacement |
18939 ;; Make `C-c C-x' a prefix key
18940 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18942 ;; TAB key with modifiers
18943 (org-defkey org-mode-map "\C-i" 'org-cycle)
18944 (org-defkey org-mode-map [(tab)] 'org-cycle)
18945 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18946 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18947 ;; The following line is necessary under Suse GNU/Linux
18948 (unless (featurep 'xemacs)
18949 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18950 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18951 (define-key org-mode-map [backtab] 'org-shifttab)
18953 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18954 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18955 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18957 ;; Cursor keys with modifiers
18958 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18959 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18960 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18961 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18963 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18964 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18965 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18966 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18968 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18969 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18970 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18971 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18973 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18974 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18975 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18976 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18978 ;; Babel keys
18979 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18980 (mapc (lambda (pair)
18981 (define-key org-babel-map (car pair) (cdr pair)))
18982 org-babel-key-bindings)
18984 ;;; Extra keys for tty access.
18985 ;; We only set them when really needed because otherwise the
18986 ;; menus don't show the simple keys
18988 (when (or org-use-extra-keys
18989 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18990 (not window-system))
18991 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18992 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18993 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18994 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18995 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18996 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18997 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18998 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18999 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19000 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19001 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19002 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19003 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19004 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19005 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19006 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19007 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19008 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19009 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19010 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19011 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19012 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19013 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
19014 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19015 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19016 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19017 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19018 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19020 ;; All the other keys
19022 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
19023 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19024 (if (boundp 'narrow-map)
19025 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19026 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19027 (if (boundp 'narrow-map)
19028 (org-defkey narrow-map "b" 'org-narrow-to-block)
19029 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19030 (if (boundp 'narrow-map)
19031 (org-defkey narrow-map "e" 'org-narrow-to-element)
19032 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19033 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19034 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19035 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19036 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19037 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19038 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19039 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19040 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19041 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19042 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19043 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
19044 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19045 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19046 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19047 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19048 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19049 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19050 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19051 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19052 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19053 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19054 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19055 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19056 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19057 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19058 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19059 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19060 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19061 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19062 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19063 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19064 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19065 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19066 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19067 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19068 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19069 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19070 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19071 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19072 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19073 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19074 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19075 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19076 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19077 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19078 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19079 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19080 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19081 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19082 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19083 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19084 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19085 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19086 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19087 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19088 (org-defkey org-mode-map "\C-c^" 'org-sort)
19089 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19090 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19091 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19092 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19093 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-element)
19094 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-element)
19095 (org-defkey org-mode-map "\C-m" 'org-return)
19096 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19097 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19098 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19099 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19100 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19101 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19102 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19103 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19104 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19105 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19106 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19107 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19108 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19109 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19110 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
19111 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19112 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19113 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19114 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19115 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19116 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19117 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19118 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19120 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19121 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19122 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19124 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19125 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19126 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19127 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19128 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19129 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19130 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19131 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19132 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19133 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19134 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
19135 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19136 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19137 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19138 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19139 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19140 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19141 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19142 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19143 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19144 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19145 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19146 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19148 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19149 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19150 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19151 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19152 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19154 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19156 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19158 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19159 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19161 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19164 (when (featurep 'xemacs)
19165 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19168 (defconst org-speed-commands-default
19170 ("Outline Navigation")
19171 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19172 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19173 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19174 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19175 ("F" . org-next-block)
19176 ("B" . org-previous-block)
19177 ("u" . (org-speed-move-safe 'outline-up-heading))
19178 ("j" . org-goto)
19179 ("g" . (org-refile t))
19180 ("Outline Visibility")
19181 ("c" . org-cycle)
19182 ("C" . org-shifttab)
19183 (" " . org-display-outline-path)
19184 ("s" . org-narrow-to-subtree)
19185 ("=" . org-columns)
19186 ("Outline Structure Editing")
19187 ("U" . org-shiftmetaup)
19188 ("D" . org-shiftmetadown)
19189 ("r" . org-metaright)
19190 ("l" . org-metaleft)
19191 ("R" . org-shiftmetaright)
19192 ("L" . org-shiftmetaleft)
19193 ("i" . (progn (forward-char 1) (call-interactively
19194 'org-insert-heading-respect-content)))
19195 ("^" . org-sort)
19196 ("w" . org-refile)
19197 ("a" . org-archive-subtree-default-with-confirmation)
19198 ("@" . org-mark-subtree)
19199 ("#" . org-toggle-comment)
19200 ("Clock Commands")
19201 ("I" . org-clock-in)
19202 ("O" . org-clock-out)
19203 ("Meta Data Editing")
19204 ("t" . org-todo)
19205 ("," . (org-priority))
19206 ("0" . (org-priority ?\ ))
19207 ("1" . (org-priority ?A))
19208 ("2" . (org-priority ?B))
19209 ("3" . (org-priority ?C))
19210 (":" . org-set-tags-command)
19211 ("e" . org-set-effort)
19212 ("E" . org-inc-effort)
19213 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19214 (org-entry-put (point) "APPT_WARNTIME" m)))
19215 ("Agenda Views etc")
19216 ("v" . org-agenda)
19217 ("/" . org-sparse-tree)
19218 ("Misc")
19219 ("o" . org-open-at-point)
19220 ("?" . org-speed-command-help)
19221 ("<" . (org-agenda-set-restriction-lock 'subtree))
19222 (">" . (org-agenda-remove-restriction-lock))
19224 "The default speed commands.")
19226 (defun org-print-speed-command (e)
19227 (if (> (length (car e)) 1)
19228 (progn
19229 (princ "\n")
19230 (princ (car e))
19231 (princ "\n")
19232 (princ (make-string (length (car e)) ?-))
19233 (princ "\n"))
19234 (princ (car e))
19235 (princ " ")
19236 (if (symbolp (cdr e))
19237 (princ (symbol-name (cdr e)))
19238 (prin1 (cdr e)))
19239 (princ "\n")))
19241 (defun org-speed-command-help ()
19242 "Show the available speed commands."
19243 (interactive)
19244 (if (not org-use-speed-commands)
19245 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19246 (with-output-to-temp-buffer "*Help*"
19247 (princ "User-defined Speed commands\n===========================\n")
19248 (mapc 'org-print-speed-command org-speed-commands-user)
19249 (princ "\n")
19250 (princ "Built-in Speed commands\n=======================\n")
19251 (mapc 'org-print-speed-command org-speed-commands-default))
19252 (with-current-buffer "*Help*"
19253 (setq truncate-lines t))))
19255 (defun org-speed-move-safe (cmd)
19256 "Execute CMD, but make sure that the cursor always ends up in a headline.
19257 If not, return to the original position and throw an error."
19258 (interactive)
19259 (let ((pos (point)))
19260 (call-interactively cmd)
19261 (unless (and (bolp) (org-at-heading-p))
19262 (goto-char pos)
19263 (error "Boundary reached while executing %s" cmd))))
19265 (defvar org-self-insert-command-undo-counter 0)
19267 (defvar org-table-auto-blank-field) ; defined in org-table.el
19268 (defvar org-speed-command nil)
19270 (define-obsolete-function-alias
19271 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19273 (defun org-speed-command-activate (keys)
19274 "Hook for activating single-letter speed commands.
19275 `org-speed-commands-default' specifies a minimal command set.
19276 Use `org-speed-commands-user' for further customization."
19277 (when (or (and (bolp) (looking-at org-outline-regexp))
19278 (and (functionp org-use-speed-commands)
19279 (funcall org-use-speed-commands)))
19280 (cdr (assoc keys (append org-speed-commands-user
19281 org-speed-commands-default)))))
19283 (define-obsolete-function-alias
19284 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19286 (defun org-babel-speed-command-activate (keys)
19287 "Hook for activating single-letter code block commands."
19288 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19289 (cdr (assoc keys org-babel-key-bindings))))
19291 (defcustom org-speed-command-hook
19292 '(org-speed-command-default-hook org-babel-speed-command-hook)
19293 "Hook for activating speed commands at strategic locations.
19294 Hook functions are called in sequence until a valid handler is
19295 found.
19297 Each hook takes a single argument, a user-pressed command key
19298 which is also a `self-insert-command' from the global map.
19300 Within the hook, examine the cursor position and the command key
19301 and return nil or a valid handler as appropriate. Handler could
19302 be one of an interactive command, a function, or a form.
19304 Set `org-use-speed-commands' to non-nil value to enable this
19305 hook. The default setting is `org-speed-command-activate'."
19306 :group 'org-structure
19307 :version "24.1"
19308 :type 'hook)
19310 (defun org-self-insert-command (N)
19311 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19312 If the cursor is in a table looking at whitespace, the whitespace is
19313 overwritten, and the table is not marked as requiring realignment."
19314 (interactive "p")
19315 (org-check-before-invisible-edit 'insert)
19316 (cond
19317 ((and org-use-speed-commands
19318 (setq org-speed-command
19319 (run-hook-with-args-until-success
19320 'org-speed-command-hook (this-command-keys))))
19321 (cond
19322 ((commandp org-speed-command)
19323 (setq this-command org-speed-command)
19324 (call-interactively org-speed-command))
19325 ((functionp org-speed-command)
19326 (funcall org-speed-command))
19327 ((and org-speed-command (listp org-speed-command))
19328 (eval org-speed-command))
19329 (t (let (org-use-speed-commands)
19330 (call-interactively 'org-self-insert-command)))))
19331 ((and
19332 (org-table-p)
19333 (progn
19334 ;; check if we blank the field, and if that triggers align
19335 (and (featurep 'org-table) org-table-auto-blank-field
19336 (member last-command
19337 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19338 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19339 ;; got extra space, this field does not determine column width
19340 (let (org-table-may-need-update) (org-table-blank-field))
19341 ;; no extra space, this field may determine column width
19342 (org-table-blank-field)))
19344 (eq N 1)
19345 (looking-at "[^|\n]* |"))
19346 (let (org-table-may-need-update)
19347 (goto-char (1- (match-end 0)))
19348 (backward-delete-char 1)
19349 (goto-char (match-beginning 0))
19350 (self-insert-command N)))
19352 (setq org-table-may-need-update t)
19353 (self-insert-command N)
19354 (org-fix-tags-on-the-fly)
19355 (if org-self-insert-cluster-for-undo
19356 (if (not (eq last-command 'org-self-insert-command))
19357 (setq org-self-insert-command-undo-counter 1)
19358 (if (>= org-self-insert-command-undo-counter 20)
19359 (setq org-self-insert-command-undo-counter 1)
19360 (and (> org-self-insert-command-undo-counter 0)
19361 buffer-undo-list (listp buffer-undo-list)
19362 (not (cadr buffer-undo-list)) ; remove nil entry
19363 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19364 (setq org-self-insert-command-undo-counter
19365 (1+ org-self-insert-command-undo-counter))))))))
19367 (defun org-check-before-invisible-edit (kind)
19368 "Check is editing if kind KIND would be dangerous with invisible text around.
19369 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19370 ;; First, try to get out of here as quickly as possible, to reduce overhead
19371 (if (and org-catch-invisible-edits
19372 (or (not (boundp 'visible-mode)) (not visible-mode))
19373 (or (get-char-property (point) 'invisible)
19374 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19375 ;; OK, we need to take a closer look
19376 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19377 (invisible-before-point (if (bobp) nil (get-char-property
19378 (1- (point)) 'invisible)))
19379 (border-and-ok-direction
19381 ;; Check if we are acting predictably before invisible text
19382 (and invisible-at-point (not invisible-before-point)
19383 (memq kind '(insert delete-backward)))
19384 ;; Check if we are acting predictably after invisible text
19385 ;; This works not well, and I have turned it off. It seems
19386 ;; better to always show and stop after invisible text.
19387 ;; (and (not invisible-at-point) invisible-before-point
19388 ;; (memq kind '(insert delete)))
19390 (when (or (memq invisible-at-point '(outline org-hide-block t))
19391 (memq invisible-before-point '(outline org-hide-block t)))
19392 (if (eq org-catch-invisible-edits 'error)
19393 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19394 (if (and org-custom-properties-overlays
19395 (y-or-n-p "Display invisible properties in this buffer? "))
19396 (org-toggle-custom-properties-visibility)
19397 ;; Make the area visible
19398 (save-excursion
19399 (if invisible-before-point
19400 (goto-char (previous-single-char-property-change
19401 (point) 'invisible)))
19402 (org-cycle))
19403 (cond
19404 ((eq org-catch-invisible-edits 'show)
19405 ;; That's it, we do the edit after showing
19406 (message
19407 "Unfolding invisible region around point before editing")
19408 (sit-for 1))
19409 ((and (eq org-catch-invisible-edits 'smart)
19410 border-and-ok-direction)
19411 (message "Unfolding invisible region around point before editing"))
19413 ;; Don't do the edit, make the user repeat it in full visibility
19414 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19416 (defun org-fix-tags-on-the-fly ()
19417 (when (and (equal (char-after (point-at-bol)) ?*)
19418 (org-at-heading-p))
19419 (org-align-tags-here org-tags-column)))
19421 (defun org-delete-backward-char (N)
19422 "Like `delete-backward-char', insert whitespace at field end in tables.
19423 When deleting backwards, in tables this function will insert whitespace in
19424 front of the next \"|\" separator, to keep the table aligned. The table will
19425 still be marked for re-alignment if the field did fill the entire column,
19426 because, in this case the deletion might narrow the column."
19427 (interactive "p")
19428 (save-match-data
19429 (org-check-before-invisible-edit 'delete-backward)
19430 (if (and (org-table-p)
19431 (eq N 1)
19432 (string-match "|" (buffer-substring (point-at-bol) (point)))
19433 (looking-at ".*?|"))
19434 (let ((pos (point))
19435 (noalign (looking-at "[^|\n\r]* |"))
19436 (c org-table-may-need-update))
19437 (backward-delete-char N)
19438 (if (not overwrite-mode)
19439 (progn
19440 (skip-chars-forward "^|")
19441 (insert " ")
19442 (goto-char (1- pos))))
19443 ;; noalign: if there were two spaces at the end, this field
19444 ;; does not determine the width of the column.
19445 (if noalign (setq org-table-may-need-update c)))
19446 (backward-delete-char N)
19447 (org-fix-tags-on-the-fly))))
19449 (defun org-delete-char (N)
19450 "Like `delete-char', but insert whitespace at field end in tables.
19451 When deleting characters, in tables this function will insert whitespace in
19452 front of the next \"|\" separator, to keep the table aligned. The table will
19453 still be marked for re-alignment if the field did fill the entire column,
19454 because, in this case the deletion might narrow the column."
19455 (interactive "p")
19456 (save-match-data
19457 (org-check-before-invisible-edit 'delete)
19458 (if (and (org-table-p)
19459 (not (bolp))
19460 (not (= (char-after) ?|))
19461 (eq N 1))
19462 (if (looking-at ".*?|")
19463 (let ((pos (point))
19464 (noalign (looking-at "[^|\n\r]* |"))
19465 (c org-table-may-need-update))
19466 (replace-match
19467 (concat (substring (match-string 0) 1 -1) " |") nil t)
19468 (goto-char pos)
19469 ;; noalign: if there were two spaces at the end, this field
19470 ;; does not determine the width of the column.
19471 (if noalign (setq org-table-may-need-update c)))
19472 (delete-char N))
19473 (delete-char N)
19474 (org-fix-tags-on-the-fly))))
19476 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19477 (put 'org-self-insert-command 'delete-selection t)
19478 (put 'orgtbl-self-insert-command 'delete-selection t)
19479 (put 'org-delete-char 'delete-selection 'supersede)
19480 (put 'org-delete-backward-char 'delete-selection 'supersede)
19481 (put 'org-yank 'delete-selection 'yank)
19483 ;; Make `flyspell-mode' delay after some commands
19484 (put 'org-self-insert-command 'flyspell-delayed t)
19485 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19486 (put 'org-delete-char 'flyspell-delayed t)
19487 (put 'org-delete-backward-char 'flyspell-delayed t)
19489 ;; Make pabbrev-mode expand after org-mode commands
19490 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19491 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19493 ;; How to do this: Measure non-white length of current string
19494 ;; If equal to column width, we should realign.
19496 (defun org-remap (map &rest commands)
19497 "In MAP, remap the functions given in COMMANDS.
19498 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19499 (let (new old)
19500 (while commands
19501 (setq old (pop commands) new (pop commands))
19502 (if (fboundp 'command-remapping)
19503 (org-defkey map (vector 'remap old) new)
19504 (substitute-key-definition old new map global-map)))))
19506 (defun org-transpose-words ()
19507 "Transpose words for Org.
19508 This uses the `org-mode-transpose-word-syntax-table' syntax
19509 table, which interprets characters in `org-emphasis-alist' as
19510 word constituants."
19511 (interactive)
19512 (with-syntax-table org-mode-transpose-word-syntax-table
19513 (call-interactively 'transpose-words)))
19514 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19516 (when (eq org-enable-table-editor 'optimized)
19517 ;; If the user wants maximum table support, we need to hijack
19518 ;; some standard editing functions
19519 (org-remap org-mode-map
19520 'self-insert-command 'org-self-insert-command
19521 'delete-char 'org-delete-char
19522 'delete-backward-char 'org-delete-backward-char)
19523 (org-defkey org-mode-map "|" 'org-force-self-insert))
19525 (defvar org-ctrl-c-ctrl-c-hook nil
19526 "Hook for functions attaching themselves to `C-c C-c'.
19528 This can be used to add additional functionality to the C-c C-c
19529 key which executes context-dependent commands. This hook is run
19530 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19531 run after the last test.
19533 Each function will be called with no arguments. The function
19534 must check if the context is appropriate for it to act. If yes,
19535 it should do its thing and then return a non-nil value. If the
19536 context is wrong, just do nothing and return nil.")
19538 (defvar org-ctrl-c-ctrl-c-final-hook nil
19539 "Hook for functions attaching themselves to `C-c C-c'.
19541 This can be used to add additional functionality to the C-c C-c
19542 key which executes context-dependent commands. This hook is run
19543 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19544 before the first test.
19546 Each function will be called with no arguments. The function
19547 must check if the context is appropriate for it to act. If yes,
19548 it should do its thing and then return a non-nil value. If the
19549 context is wrong, just do nothing and return nil.")
19551 (defvar org-tab-first-hook nil
19552 "Hook for functions to attach themselves to TAB.
19553 See `org-ctrl-c-ctrl-c-hook' for more information.
19554 This hook runs as the first action when TAB is pressed, even before
19555 `org-cycle' messes around with the `outline-regexp' to cater for
19556 inline tasks and plain list item folding.
19557 If any function in this hook returns t, any other actions that
19558 would have been caused by TAB (such as table field motion or visibility
19559 cycling) will not occur.")
19561 (defvar org-tab-after-check-for-table-hook nil
19562 "Hook for functions to attach themselves to TAB.
19563 See `org-ctrl-c-ctrl-c-hook' for more information.
19564 This hook runs after it has been established that the cursor is not in a
19565 table, but before checking if the cursor is in a headline or if global cycling
19566 should be done.
19567 If any function in this hook returns t, not other actions like visibility
19568 cycling will be done.")
19570 (defvar org-tab-after-check-for-cycling-hook nil
19571 "Hook for functions to attach themselves to TAB.
19572 See `org-ctrl-c-ctrl-c-hook' for more information.
19573 This hook runs after it has been established that not table field motion and
19574 not visibility should be done because of current context. This is probably
19575 the place where a package like yasnippets can hook in.")
19577 (defvar org-tab-before-tab-emulation-hook nil
19578 "Hook for functions to attach themselves to TAB.
19579 See `org-ctrl-c-ctrl-c-hook' for more information.
19580 This hook runs after every other options for TAB have been exhausted, but
19581 before indentation and \t insertion takes place.")
19583 (defvar org-metaleft-hook nil
19584 "Hook for functions attaching themselves to `M-left'.
19585 See `org-ctrl-c-ctrl-c-hook' for more information.")
19586 (defvar org-metaright-hook nil
19587 "Hook for functions attaching themselves to `M-right'.
19588 See `org-ctrl-c-ctrl-c-hook' for more information.")
19589 (defvar org-metaup-hook nil
19590 "Hook for functions attaching themselves to `M-up'.
19591 See `org-ctrl-c-ctrl-c-hook' for more information.")
19592 (defvar org-metadown-hook nil
19593 "Hook for functions attaching themselves to `M-down'.
19594 See `org-ctrl-c-ctrl-c-hook' for more information.")
19595 (defvar org-shiftmetaleft-hook nil
19596 "Hook for functions attaching themselves to `M-S-left'.
19597 See `org-ctrl-c-ctrl-c-hook' for more information.")
19598 (defvar org-shiftmetaright-hook nil
19599 "Hook for functions attaching themselves to `M-S-right'.
19600 See `org-ctrl-c-ctrl-c-hook' for more information.")
19601 (defvar org-shiftmetaup-hook nil
19602 "Hook for functions attaching themselves to `M-S-up'.
19603 See `org-ctrl-c-ctrl-c-hook' for more information.")
19604 (defvar org-shiftmetadown-hook nil
19605 "Hook for functions attaching themselves to `M-S-down'.
19606 See `org-ctrl-c-ctrl-c-hook' for more information.")
19607 (defvar org-metareturn-hook nil
19608 "Hook for functions attaching themselves to `M-RET'.
19609 See `org-ctrl-c-ctrl-c-hook' for more information.")
19610 (defvar org-shiftup-hook nil
19611 "Hook for functions attaching themselves to `S-up'.
19612 See `org-ctrl-c-ctrl-c-hook' for more information.")
19613 (defvar org-shiftup-final-hook nil
19614 "Hook for functions attaching themselves to `S-up'.
19615 This one runs after all other options except shift-select have been excluded.
19616 See `org-ctrl-c-ctrl-c-hook' for more information.")
19617 (defvar org-shiftdown-hook nil
19618 "Hook for functions attaching themselves to `S-down'.
19619 See `org-ctrl-c-ctrl-c-hook' for more information.")
19620 (defvar org-shiftdown-final-hook nil
19621 "Hook for functions attaching themselves to `S-down'.
19622 This one runs after all other options except shift-select have been excluded.
19623 See `org-ctrl-c-ctrl-c-hook' for more information.")
19624 (defvar org-shiftleft-hook nil
19625 "Hook for functions attaching themselves to `S-left'.
19626 See `org-ctrl-c-ctrl-c-hook' for more information.")
19627 (defvar org-shiftleft-final-hook nil
19628 "Hook for functions attaching themselves to `S-left'.
19629 This one runs after all other options except shift-select have been excluded.
19630 See `org-ctrl-c-ctrl-c-hook' for more information.")
19631 (defvar org-shiftright-hook nil
19632 "Hook for functions attaching themselves to `S-right'.
19633 See `org-ctrl-c-ctrl-c-hook' for more information.")
19634 (defvar org-shiftright-final-hook nil
19635 "Hook for functions attaching themselves to `S-right'.
19636 This one runs after all other options except shift-select have been excluded.
19637 See `org-ctrl-c-ctrl-c-hook' for more information.")
19639 (defun org-modifier-cursor-error ()
19640 "Throw an error, a modified cursor command was applied in wrong context."
19641 (user-error "This command is active in special context like tables, headlines or items"))
19643 (defun org-shiftselect-error ()
19644 "Throw an error because Shift-Cursor command was applied in wrong context."
19645 (if (and (boundp 'shift-select-mode) shift-select-mode)
19646 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19647 (user-error "This command works only in special context like headlines or timestamps")))
19649 (defun org-call-for-shift-select (cmd)
19650 (let ((this-command-keys-shift-translated t))
19651 (call-interactively cmd)))
19653 (defun org-shifttab (&optional arg)
19654 "Global visibility cycling or move to previous table field.
19655 Call `org-table-previous-field' within a table.
19656 When ARG is nil, cycle globally through visibility states.
19657 When ARG is a numeric prefix, show contents of this level."
19658 (interactive "P")
19659 (cond
19660 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19661 ((integerp arg)
19662 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19663 (message "Content view to level: %d" arg)
19664 (org-content (prefix-numeric-value arg2))
19665 (org-cycle-show-empty-lines t)
19666 (setq org-cycle-global-status 'overview)))
19667 (t (call-interactively 'org-global-cycle))))
19669 (defun org-shiftmetaleft ()
19670 "Promote subtree or delete table column.
19671 Calls `org-promote-subtree', `org-outdent-item-tree', or
19672 `org-table-delete-column', depending on context. See the
19673 individual commands for more information."
19674 (interactive)
19675 (cond
19676 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19677 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19678 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19679 ((if (not (org-region-active-p)) (org-at-item-p)
19680 (save-excursion (goto-char (region-beginning))
19681 (org-at-item-p)))
19682 (call-interactively 'org-outdent-item-tree))
19683 (t (org-modifier-cursor-error))))
19685 (defun org-shiftmetaright ()
19686 "Demote subtree or insert table column.
19687 Calls `org-demote-subtree', `org-indent-item-tree', or
19688 `org-table-insert-column', depending on context. See the
19689 individual commands for more information."
19690 (interactive)
19691 (cond
19692 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19693 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19694 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19695 ((if (not (org-region-active-p)) (org-at-item-p)
19696 (save-excursion (goto-char (region-beginning))
19697 (org-at-item-p)))
19698 (call-interactively 'org-indent-item-tree))
19699 (t (org-modifier-cursor-error))))
19701 (defun org-shiftmetaup (&optional arg)
19702 "Move subtree up or kill table row.
19703 Calls `org-move-subtree-up' or `org-table-kill-row' or
19704 `org-move-item-up' or `org-timestamp-up', depending on context.
19705 See the individual commands for more information."
19706 (interactive "P")
19707 (cond
19708 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19709 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19710 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19711 ((org-at-item-p) (call-interactively 'org-move-item-up))
19712 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19713 (call-interactively 'org-timestamp-up)))
19714 (t (call-interactively 'org-drag-line-backward))))
19716 (defun org-shiftmetadown (&optional arg)
19717 "Move subtree down or insert table row.
19718 Calls `org-move-subtree-down' or `org-table-insert-row' or
19719 `org-move-item-down' or `org-timestamp-up', depending on context.
19720 See the individual commands for more information."
19721 (interactive "P")
19722 (cond
19723 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19724 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19725 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19726 ((org-at-item-p) (call-interactively 'org-move-item-down))
19727 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19728 (call-interactively 'org-timestamp-down)))
19729 (t (call-interactively 'org-drag-line-forward))))
19731 (defsubst org-hidden-tree-error ()
19732 (user-error
19733 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19735 (defun org-metaleft (&optional arg)
19736 "Promote heading or move table column to left.
19737 Calls `org-do-promote' or `org-table-move-column', depending on context.
19738 With no specific context, calls the Emacs default `backward-word'.
19739 See the individual commands for more information."
19740 (interactive "P")
19741 (cond
19742 ((run-hook-with-args-until-success 'org-metaleft-hook))
19743 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19744 ((org-with-limited-levels
19745 (or (org-at-heading-p)
19746 (and (org-region-active-p)
19747 (save-excursion
19748 (goto-char (region-beginning))
19749 (org-at-heading-p)))))
19750 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19751 (call-interactively 'org-do-promote))
19752 ;; At an inline task.
19753 ((org-at-heading-p)
19754 (call-interactively 'org-inlinetask-promote))
19755 ((or (org-at-item-p)
19756 (and (org-region-active-p)
19757 (save-excursion
19758 (goto-char (region-beginning))
19759 (org-at-item-p))))
19760 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19761 (call-interactively 'org-outdent-item))
19762 (t (call-interactively 'backward-word))))
19764 (defun org-metaright (&optional arg)
19765 "Demote a subtree, a list item or move table column to right.
19766 In front of a drawer or a block keyword, indent it correctly.
19767 With no specific context, calls the Emacs default `forward-word'.
19768 See the individual commands for more information."
19769 (interactive "P")
19770 (cond
19771 ((run-hook-with-args-until-success 'org-metaright-hook))
19772 ((org-at-table-p) (call-interactively 'org-table-move-column))
19773 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19774 ((org-at-block-p) (call-interactively 'org-indent-block))
19775 ((org-with-limited-levels
19776 (or (org-at-heading-p)
19777 (and (org-region-active-p)
19778 (save-excursion
19779 (goto-char (region-beginning))
19780 (org-at-heading-p)))))
19781 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19782 (call-interactively 'org-do-demote))
19783 ;; At an inline task.
19784 ((org-at-heading-p)
19785 (call-interactively 'org-inlinetask-demote))
19786 ((or (org-at-item-p)
19787 (and (org-region-active-p)
19788 (save-excursion
19789 (goto-char (region-beginning))
19790 (org-at-item-p))))
19791 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19792 (call-interactively 'org-indent-item))
19793 (t (call-interactively 'forward-word))))
19795 (defun org-check-for-hidden (what)
19796 "Check if there are hidden headlines/items in the current visual line.
19797 WHAT can be either `headlines' or `items'. If the current line is
19798 an outline or item heading and it has a folded subtree below it,
19799 this function returns t, nil otherwise."
19800 (let ((re (cond
19801 ((eq what 'headlines) org-outline-regexp-bol)
19802 ((eq what 'items) (org-item-beginning-re))
19803 (t (error "This should not happen"))))
19804 beg end)
19805 (save-excursion
19806 (catch 'exit
19807 (unless (org-region-active-p)
19808 (setq beg (point-at-bol))
19809 (beginning-of-line 2)
19810 (while (and (not (eobp)) ;; this is like `next-line'
19811 (get-char-property (1- (point)) 'invisible))
19812 (beginning-of-line 2))
19813 (setq end (point))
19814 (goto-char beg)
19815 (goto-char (point-at-eol))
19816 (setq end (max end (point)))
19817 (while (re-search-forward re end t)
19818 (if (get-char-property (match-beginning 0) 'invisible)
19819 (throw 'exit t))))
19820 nil))))
19822 (defun org-metaup (&optional arg)
19823 "Move subtree up or move table row up.
19824 Calls `org-move-subtree-up' or `org-table-move-row' or
19825 `org-move-item-up', depending on context. See the individual commands
19826 for more information."
19827 (interactive "P")
19828 (cond
19829 ((run-hook-with-args-until-success 'org-metaup-hook))
19830 ((org-region-active-p)
19831 (let* ((a (min (region-beginning) (region-end)))
19832 (b (1- (max (region-beginning) (region-end))))
19833 (c (save-excursion (goto-char a)
19834 (move-beginning-of-line 0)))
19835 (d (save-excursion (goto-char a)
19836 (move-end-of-line 0) (point))))
19837 (transpose-regions a b c d)
19838 (goto-char c)))
19839 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19840 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19841 ((org-at-item-p) (call-interactively 'org-move-item-up))
19842 (t (org-drag-element-backward))))
19844 (defun org-metadown (&optional arg)
19845 "Move subtree down or move table row down.
19846 Calls `org-move-subtree-down' or `org-table-move-row' or
19847 `org-move-item-down', depending on context. See the individual
19848 commands for more information."
19849 (interactive "P")
19850 (cond
19851 ((run-hook-with-args-until-success 'org-metadown-hook))
19852 ((org-region-active-p)
19853 (let* ((a (min (region-beginning) (region-end)))
19854 (b (max (region-beginning) (region-end)))
19855 (c (save-excursion (goto-char b)
19856 (move-beginning-of-line 1)))
19857 (d (save-excursion (goto-char b)
19858 (move-end-of-line 1) (1+ (point)))))
19859 (transpose-regions a b c d)
19860 (goto-char d)))
19861 ((org-at-table-p) (call-interactively 'org-table-move-row))
19862 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19863 ((org-at-item-p) (call-interactively 'org-move-item-down))
19864 (t (org-drag-element-forward))))
19866 (defun org-shiftup (&optional arg)
19867 "Increase item in timestamp or increase priority of current headline.
19868 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19869 depending on context. See the individual commands for more information."
19870 (interactive "P")
19871 (cond
19872 ((run-hook-with-args-until-success 'org-shiftup-hook))
19873 ((and org-support-shift-select (org-region-active-p))
19874 (org-call-for-shift-select 'previous-line))
19875 ((org-at-timestamp-p t)
19876 (call-interactively (if org-edit-timestamp-down-means-later
19877 'org-timestamp-down 'org-timestamp-up)))
19878 ((and (not (eq org-support-shift-select 'always))
19879 org-enable-priority-commands
19880 (org-at-heading-p))
19881 (call-interactively 'org-priority-up))
19882 ((and (not org-support-shift-select) (org-at-item-p))
19883 (call-interactively 'org-previous-item))
19884 ((org-clocktable-try-shift 'up arg))
19885 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19886 (org-support-shift-select
19887 (org-call-for-shift-select 'previous-line))
19888 (t (org-shiftselect-error))))
19890 (defun org-shiftdown (&optional arg)
19891 "Decrease item in timestamp or decrease priority of current headline.
19892 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19893 depending on context. See the individual commands for more information."
19894 (interactive "P")
19895 (cond
19896 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19897 ((and org-support-shift-select (org-region-active-p))
19898 (org-call-for-shift-select 'next-line))
19899 ((org-at-timestamp-p t)
19900 (call-interactively (if org-edit-timestamp-down-means-later
19901 'org-timestamp-up 'org-timestamp-down)))
19902 ((and (not (eq org-support-shift-select 'always))
19903 org-enable-priority-commands
19904 (org-at-heading-p))
19905 (call-interactively 'org-priority-down))
19906 ((and (not org-support-shift-select) (org-at-item-p))
19907 (call-interactively 'org-next-item))
19908 ((org-clocktable-try-shift 'down arg))
19909 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19910 (org-support-shift-select
19911 (org-call-for-shift-select 'next-line))
19912 (t (org-shiftselect-error))))
19914 (defun org-shiftright (&optional arg)
19915 "Cycle the thing at point or in the current line, depending on context.
19916 Depending on context, this does one of the following:
19918 - switch a timestamp at point one day into the future
19919 - on a headline, switch to the next TODO keyword.
19920 - on an item, switch entire list to the next bullet type
19921 - on a property line, switch to the next allowed value
19922 - on a clocktable definition line, move time block into the future"
19923 (interactive "P")
19924 (cond
19925 ((run-hook-with-args-until-success 'org-shiftright-hook))
19926 ((and org-support-shift-select (org-region-active-p))
19927 (org-call-for-shift-select 'forward-char))
19928 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19929 ((and (not (eq org-support-shift-select 'always))
19930 (org-at-heading-p))
19931 (let ((org-inhibit-logging
19932 (not org-treat-S-cursor-todo-selection-as-state-change))
19933 (org-inhibit-blocking
19934 (not org-treat-S-cursor-todo-selection-as-state-change)))
19935 (org-call-with-arg 'org-todo 'right)))
19936 ((or (and org-support-shift-select
19937 (not (eq org-support-shift-select 'always))
19938 (org-at-item-bullet-p))
19939 (and (not org-support-shift-select) (org-at-item-p)))
19940 (org-call-with-arg 'org-cycle-list-bullet nil))
19941 ((and (not (eq org-support-shift-select 'always))
19942 (org-at-property-p))
19943 (call-interactively 'org-property-next-allowed-value))
19944 ((org-clocktable-try-shift 'right arg))
19945 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19946 (org-support-shift-select
19947 (org-call-for-shift-select 'forward-char))
19948 (t (org-shiftselect-error))))
19950 (defun org-shiftleft (&optional arg)
19951 "Cycle the thing at point or in the current line, depending on context.
19952 Depending on context, this does one of the following:
19954 - switch a timestamp at point one day into the past
19955 - on a headline, switch to the previous TODO keyword.
19956 - on an item, switch entire list to the previous bullet type
19957 - on a property line, switch to the previous allowed value
19958 - on a clocktable definition line, move time block into the past"
19959 (interactive "P")
19960 (cond
19961 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19962 ((and org-support-shift-select (org-region-active-p))
19963 (org-call-for-shift-select 'backward-char))
19964 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19965 ((and (not (eq org-support-shift-select 'always))
19966 (org-at-heading-p))
19967 (let ((org-inhibit-logging
19968 (not org-treat-S-cursor-todo-selection-as-state-change))
19969 (org-inhibit-blocking
19970 (not org-treat-S-cursor-todo-selection-as-state-change)))
19971 (org-call-with-arg 'org-todo 'left)))
19972 ((or (and org-support-shift-select
19973 (not (eq org-support-shift-select 'always))
19974 (org-at-item-bullet-p))
19975 (and (not org-support-shift-select) (org-at-item-p)))
19976 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19977 ((and (not (eq org-support-shift-select 'always))
19978 (org-at-property-p))
19979 (call-interactively 'org-property-previous-allowed-value))
19980 ((org-clocktable-try-shift 'left arg))
19981 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19982 (org-support-shift-select
19983 (org-call-for-shift-select 'backward-char))
19984 (t (org-shiftselect-error))))
19986 (defun org-shiftcontrolright ()
19987 "Switch to next TODO set."
19988 (interactive)
19989 (cond
19990 ((and org-support-shift-select (org-region-active-p))
19991 (org-call-for-shift-select 'forward-word))
19992 ((and (not (eq org-support-shift-select 'always))
19993 (org-at-heading-p))
19994 (org-call-with-arg 'org-todo 'nextset))
19995 (org-support-shift-select
19996 (org-call-for-shift-select 'forward-word))
19997 (t (org-shiftselect-error))))
19999 (defun org-shiftcontrolleft ()
20000 "Switch to previous TODO set."
20001 (interactive)
20002 (cond
20003 ((and org-support-shift-select (org-region-active-p))
20004 (org-call-for-shift-select 'backward-word))
20005 ((and (not (eq org-support-shift-select 'always))
20006 (org-at-heading-p))
20007 (org-call-with-arg 'org-todo 'previousset))
20008 (org-support-shift-select
20009 (org-call-for-shift-select 'backward-word))
20010 (t (org-shiftselect-error))))
20012 (defun org-shiftcontrolup (&optional n)
20013 "Change timestamps synchronously up in CLOCK log lines.
20014 Optional argument N tells to change by that many units."
20015 (interactive "P")
20016 (cond ((and (not org-support-shift-select)
20017 (org-at-clock-log-p)
20018 (org-at-timestamp-p t))
20019 (org-clock-timestamps-up n))
20020 (t (org-shiftselect-error))))
20022 (defun org-shiftcontroldown (&optional n)
20023 "Change timestamps synchronously down in CLOCK log lines.
20024 Optional argument N tells to change by that many units."
20025 (interactive "P")
20026 (cond ((and (not org-support-shift-select)
20027 (org-at-clock-log-p)
20028 (org-at-timestamp-p t))
20029 (org-clock-timestamps-down n))
20030 (t (org-shiftselect-error))))
20032 (defun org-ctrl-c-ret ()
20033 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20034 (interactive)
20035 (cond
20036 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20037 (t (call-interactively 'org-insert-heading))))
20039 (defun org-find-visible ()
20040 (let ((s (point)))
20041 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20042 (get-char-property s 'invisible)))
20044 (defun org-find-invisible ()
20045 (let ((s (point)))
20046 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20047 (not (get-char-property s 'invisible))))
20050 (defun org-copy-visible (beg end)
20051 "Copy the visible parts of the region."
20052 (interactive "r")
20053 (let (snippets s)
20054 (save-excursion
20055 (save-restriction
20056 (narrow-to-region beg end)
20057 (setq s (goto-char (point-min)))
20058 (while (not (= (point) (point-max)))
20059 (goto-char (org-find-invisible))
20060 (push (buffer-substring s (point)) snippets)
20061 (setq s (goto-char (org-find-visible))))))
20062 (kill-new (apply 'concat (nreverse snippets)))))
20064 (defun org-copy-special ()
20065 "Copy region in table or copy current subtree.
20066 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20067 See the individual commands for more information."
20068 (interactive)
20069 (call-interactively
20070 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20072 (defun org-cut-special ()
20073 "Cut region in table or cut current subtree.
20074 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20075 See the individual commands for more information."
20076 (interactive)
20077 (call-interactively
20078 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20080 (defun org-paste-special (arg)
20081 "Paste rectangular region into table, or past subtree relative to level.
20082 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20083 See the individual commands for more information."
20084 (interactive "P")
20085 (if (org-at-table-p)
20086 (org-table-paste-rectangle)
20087 (org-paste-subtree arg)))
20089 (defsubst org-in-fixed-width-region-p ()
20090 "Is point in a fixed-width region?"
20091 (save-match-data
20092 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20094 (defun org-edit-special (&optional arg)
20095 "Call a special editor for the element at point.
20096 When at a table, call the formula editor with `org-table-edit-formulas'.
20097 When in a source code block, call `org-edit-src-code'.
20098 When in a fixed-width region, call `org-edit-fixed-width-region'.
20099 When at an #+INCLUDE keyword, visit the included file.
20100 On a link, call `ffap' to visit the link at point.
20101 Otherwise, return a user error."
20102 (interactive "P")
20103 (let ((element (org-element-at-point)))
20104 (assert (not buffer-read-only) nil
20105 "Buffer is read-only: %s" (buffer-name))
20106 (case (org-element-type element)
20107 (src-block
20108 (if (not arg) (org-edit-src-code)
20109 (let* ((info (org-babel-get-src-block-info))
20110 (lang (nth 0 info))
20111 (params (nth 2 info))
20112 (session (cdr (assq :session params))))
20113 (if (not session) (org-edit-src-code)
20114 ;; At a src-block with a session and function called with
20115 ;; an ARG: switch to the buffer related to the inferior
20116 ;; process.
20117 (switch-to-buffer
20118 (funcall (intern (concat "org-babel-prep-session:" lang))
20119 session params))))))
20120 (keyword
20121 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20122 (find-file
20123 (org-remove-double-quotes
20124 (car (org-split-string (org-element-property :value element)))))
20125 (user-error "No special environment to edit here")))
20126 (table
20127 (if (eq (org-element-property :type element) 'table.el)
20128 (org-edit-src-code)
20129 (call-interactively 'org-table-edit-formulas)))
20130 ;; Only Org tables contain `table-row' type elements.
20131 (table-row (call-interactively 'org-table-edit-formulas))
20132 ((example-block export-block) (org-edit-src-code))
20133 (fixed-width (org-edit-fixed-width-region))
20134 (otherwise
20135 ;; No notable element at point. Though, we may be at a link,
20136 ;; which is an object. Thus, scan deeper.
20137 (if (eq (org-element-type (org-element-context element)) 'link)
20138 (call-interactively 'ffap)
20139 (user-error "No special environment to edit here"))))))
20141 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20142 (defun org-ctrl-c-ctrl-c (&optional arg)
20143 "Set tags in headline, or update according to changed information at point.
20145 This command does many different things, depending on context:
20147 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20148 this is what we do.
20150 - If the cursor is on a statistics cookie, update it.
20152 - If the cursor is in a headline, prompt for tags and insert them
20153 into the current line, aligned to `org-tags-column'. When called
20154 with prefix arg, realign all tags in the current buffer.
20156 - If the cursor is in one of the special #+KEYWORD lines, this
20157 triggers scanning the buffer for these lines and updating the
20158 information.
20160 - If the cursor is inside a table, realign the table. This command
20161 works even if the automatic table editor has been turned off.
20163 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20164 the entire table.
20166 - If the cursor is at a footnote reference or definition, jump to
20167 the corresponding definition or references, respectively.
20169 - If the cursor is a the beginning of a dynamic block, update it.
20171 - If the current buffer is a capture buffer, close note and file it.
20173 - If the cursor is on a <<<target>>>, update radio targets and
20174 corresponding links in this buffer.
20176 - If the cursor is on a numbered item in a plain list, renumber the
20177 ordered list.
20179 - If the cursor is on a checkbox, toggle it.
20181 - If the cursor is on a code block, evaluate it. The variable
20182 `org-confirm-babel-evaluate' can be used to control prompting
20183 before code block evaluation, by default every code block
20184 evaluation requires confirmation. Code block evaluation can be
20185 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20186 (interactive "P")
20187 (cond
20188 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20189 org-occur-highlights
20190 org-latex-fragment-image-overlays)
20191 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20192 (org-remove-occur-highlights)
20193 (org-remove-latex-fragment-image-overlays)
20194 (message "Temporary highlights/overlays removed from current buffer"))
20195 ((and (local-variable-p 'org-finish-function (current-buffer))
20196 (fboundp org-finish-function))
20197 (funcall org-finish-function))
20198 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20200 (let* ((context (org-element-context)) (type (org-element-type context)))
20201 ;; Test if point is within a blank line.
20202 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20203 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20204 (user-error "C-c C-c can do nothing useful at this location"))
20205 ;; For convenience: at the first line of a paragraph on the
20206 ;; same line as an item, apply function on that item instead.
20207 (when (eq type 'paragraph)
20208 (let ((parent (org-element-property :parent context)))
20209 (when (and (eq (org-element-type parent) 'item)
20210 (= (point-at-bol) (org-element-property :begin parent)))
20211 (setq context parent type 'item))))
20212 ;; When heading text is a link, treat the heading, not the link,
20213 ;; as the current element
20214 (when (eq type 'link)
20215 (let ((parent (org-element-property :parent context)))
20216 (when (and (eq (org-element-type parent) 'headline))
20217 (setq context parent type 'headline))))
20218 ;; Act according to type of element or object at point.
20219 (case type
20220 (clock (org-clock-update-time-maybe))
20221 (dynamic-block
20222 (save-excursion
20223 (goto-char (org-element-property :post-affiliated context))
20224 (org-update-dblock)))
20225 (footnote-definition
20226 (goto-char (org-element-property :post-affiliated context))
20227 (call-interactively 'org-footnote-action))
20228 (footnote-reference (call-interactively 'org-footnote-action))
20229 ((headline inlinetask)
20230 (save-excursion (goto-char (org-element-property :begin context))
20231 (call-interactively 'org-set-tags)))
20232 (item
20233 ;; At an item: a double C-u set checkbox to "[-]"
20234 ;; unconditionally, whereas a single one will toggle its
20235 ;; presence. Without an universal argument, if the item
20236 ;; has a checkbox, toggle it. Otherwise repair the list.
20237 (let* ((box (org-element-property :checkbox context))
20238 (struct (org-element-property :structure context))
20239 (old-struct (copy-tree struct))
20240 (parents (org-list-parents-alist struct))
20241 (prevs (org-list-prevs-alist struct))
20242 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20243 (org-list-set-checkbox
20244 (org-element-property :begin context) struct
20245 (cond ((equal arg '(16)) "[-]")
20246 ((and (not box) (equal arg '(4))) "[ ]")
20247 ((or (not box) (equal arg '(4))) nil)
20248 ((eq box 'on) "[ ]")
20249 (t "[X]")))
20250 ;; Mimic `org-list-write-struct' but with grabbing
20251 ;; a return value from `org-list-struct-fix-box'.
20252 (org-list-struct-fix-ind struct parents 2)
20253 (org-list-struct-fix-item-end struct)
20254 (org-list-struct-fix-bul struct prevs)
20255 (org-list-struct-fix-ind struct parents)
20256 (let ((block-item
20257 (org-list-struct-fix-box struct parents prevs orderedp)))
20258 (if (and box (equal struct old-struct))
20259 (if (equal arg '(16))
20260 (message "Checkboxes already reset")
20261 (user-error "Cannot toggle this checkbox: %s"
20262 (if (eq box 'on)
20263 "all subitems checked"
20264 "unchecked subitems")))
20265 (org-list-struct-apply-struct struct old-struct)
20266 (org-update-checkbox-count-maybe))
20267 (when block-item
20268 (message "Checkboxes were removed due to empty box at line %d"
20269 (org-current-line block-item))))))
20270 (keyword
20271 (let ((org-inhibit-startup-visibility-stuff t)
20272 (org-startup-align-all-tables nil))
20273 (when (boundp 'org-table-coordinate-overlays)
20274 (mapc 'delete-overlay org-table-coordinate-overlays)
20275 (setq org-table-coordinate-overlays nil))
20276 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20277 (message "Local setup has been refreshed"))
20278 (plain-list
20279 ;; At a plain list, with a double C-u argument, set
20280 ;; checkboxes of each item to "[-]", whereas a single one
20281 ;; will toggle their presence according to the state of the
20282 ;; first item in the list. Without an argument, repair the
20283 ;; list.
20284 (let* ((begin (org-element-property :contents-begin context))
20285 (beginm (move-marker (make-marker) begin))
20286 (struct (org-element-property :structure context))
20287 (old-struct (copy-tree struct))
20288 (first-box (save-excursion
20289 (goto-char begin)
20290 (looking-at org-list-full-item-re)
20291 (match-string-no-properties 3)))
20292 (new-box (cond ((equal arg '(16)) "[-]")
20293 ((equal arg '(4)) (unless first-box "[ ]"))
20294 ((equal first-box "[X]") "[ ]")
20295 (t "[X]"))))
20296 (cond
20297 (arg
20298 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20299 (org-list-get-all-items
20300 begin struct (org-list-prevs-alist struct))))
20301 ((and first-box (eq (point) begin))
20302 ;; For convenience, when point is at bol on the first
20303 ;; item of the list and no argument is provided, simply
20304 ;; toggle checkbox of that item, if any.
20305 (org-list-set-checkbox begin struct new-box)))
20306 (org-list-write-struct
20307 struct (org-list-parents-alist struct) old-struct)
20308 (org-update-checkbox-count-maybe)
20309 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20310 ((property-drawer node-property)
20311 (call-interactively 'org-property-action))
20312 ((radio-target target)
20313 (call-interactively 'org-update-radio-target-regexp))
20314 (statistics-cookie
20315 (call-interactively 'org-update-statistics-cookies))
20316 ((table table-cell table-row)
20317 ;; At a table, recalculate every field and align it. Also
20318 ;; send the table if necessary. If the table has
20319 ;; a `table.el' type, just give up. At a table row or
20320 ;; cell, maybe recalculate line but always align table.
20321 (if (eq (org-element-property :type context) 'table.el)
20322 (message "Use C-c ' to edit table.el tables")
20323 (let ((org-enable-table-editor t))
20324 (if (or (eq type 'table)
20325 ;; Check if point is at a TBLFM line.
20326 (and (eq type 'table-row)
20327 (= (point) (org-element-property :end context))))
20328 (save-excursion
20329 (if (org-at-TBLFM-p)
20330 (progn (require 'org-table)
20331 (org-table-calc-current-TBLFM))
20332 (goto-char (org-element-property :contents-begin context))
20333 (org-call-with-arg 'org-table-recalculate (or arg t))
20334 (orgtbl-send-table 'maybe)))
20335 (org-table-maybe-eval-formula)
20336 (cond (arg (call-interactively 'org-table-recalculate))
20337 ((org-table-maybe-recalculate-line))
20338 (t (org-table-align)))))))
20339 (timestamp (org-timestamp-change 0 'day))
20340 (otherwise
20341 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20342 (user-error
20343 "C-c C-c can do nothing useful at this location")))))))))
20345 (defun org-mode-restart ()
20346 "Restart Org-mode, to scan again for special lines.
20347 Also updates the keyword regular expressions."
20348 (interactive)
20349 (org-mode)
20350 (message "Org-mode restarted"))
20352 (defun org-kill-note-or-show-branches ()
20353 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20354 (interactive)
20355 (if (not org-finish-function)
20356 (progn
20357 (hide-subtree)
20358 (call-interactively 'show-branches))
20359 (let ((org-note-abort t))
20360 (funcall org-finish-function))))
20362 (defun org-open-line (n)
20363 "Insert a new row in tables, call `open-line' elsewhere."
20364 (interactive "*p")
20365 (if (org-at-table-p)
20366 (org-table-insert-row)
20367 (open-line n)))
20369 (defun org-return (&optional indent)
20370 "Goto next table row or insert a newline.
20371 Calls `org-table-next-row' or `newline', depending on context.
20372 See the individual commands for more information."
20373 (interactive)
20374 (let (org-ts-what)
20375 (cond
20376 ((or (bobp) (org-in-src-block-p))
20377 (if indent (newline-and-indent) (newline)))
20378 ((org-at-table-p)
20379 (org-table-justify-field-maybe)
20380 (call-interactively 'org-table-next-row))
20381 ;; when `newline-and-indent' is called within a list, make sure
20382 ;; text moved stays inside the item.
20383 ((and (org-in-item-p) indent)
20384 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20385 (progn
20386 (save-match-data (newline))
20387 (org-indent-line-to (length (match-string 0))))
20388 (let ((ind (org-get-indentation)))
20389 (newline)
20390 (if (org-looking-back org-list-end-re)
20391 (org-indent-line)
20392 (org-indent-line-to ind)))))
20393 ((and org-return-follows-link
20394 (org-at-timestamp-p t)
20395 (not (eq org-ts-what 'after)))
20396 (org-follow-timestamp-link))
20397 ((and org-return-follows-link
20398 (let ((tprop (get-text-property (point) 'face)))
20399 (or (eq tprop 'org-link)
20400 (and (listp tprop) (memq 'org-link tprop)))))
20401 (call-interactively 'org-open-at-point))
20402 ((and (org-at-heading-p)
20403 (looking-at
20404 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20405 (org-show-entry)
20406 (end-of-line 1)
20407 (newline))
20408 (t (if indent (newline-and-indent) (newline))))))
20410 (defun org-return-indent ()
20411 "Goto next table row or insert a newline and indent.
20412 Calls `org-table-next-row' or `newline-and-indent', depending on
20413 context. See the individual commands for more information."
20414 (interactive)
20415 (org-return t))
20417 (defun org-ctrl-c-star ()
20418 "Compute table, or change heading status of lines.
20419 Calls `org-table-recalculate' or `org-toggle-heading',
20420 depending on context."
20421 (interactive)
20422 (cond
20423 ((org-at-table-p)
20424 (call-interactively 'org-table-recalculate))
20426 ;; Convert all lines in region to list items
20427 (call-interactively 'org-toggle-heading))))
20429 (defun org-ctrl-c-minus ()
20430 "Insert separator line in table or modify bullet status of line.
20431 Also turns a plain line or a region of lines into list items.
20432 Calls `org-table-insert-hline', `org-toggle-item', or
20433 `org-cycle-list-bullet', depending on context."
20434 (interactive)
20435 (cond
20436 ((org-at-table-p)
20437 (call-interactively 'org-table-insert-hline))
20438 ((org-region-active-p)
20439 (call-interactively 'org-toggle-item))
20440 ((org-in-item-p)
20441 (call-interactively 'org-cycle-list-bullet))
20443 (call-interactively 'org-toggle-item))))
20445 (defun org-toggle-item (arg)
20446 "Convert headings or normal lines to items, items to normal lines.
20447 If there is no active region, only the current line is considered.
20449 If the first non blank line in the region is a headline, convert
20450 all headlines to items, shifting text accordingly.
20452 If it is an item, convert all items to normal lines.
20454 If it is normal text, change region into a list of items.
20455 With a prefix argument ARG, change the region in a single item."
20456 (interactive "P")
20457 (let ((shift-text
20458 (function
20459 ;; Shift text in current section to IND, from point to END.
20460 ;; The function leaves point to END line.
20461 (lambda (ind end)
20462 (let ((min-i 1000) (end (copy-marker end)))
20463 ;; First determine the minimum indentation (MIN-I) of
20464 ;; the text.
20465 (save-excursion
20466 (catch 'exit
20467 (while (< (point) end)
20468 (let ((i (org-get-indentation)))
20469 (cond
20470 ;; Skip blank lines and inline tasks.
20471 ((looking-at "^[ \t]*$"))
20472 ((looking-at org-outline-regexp-bol))
20473 ;; We can't find less than 0 indentation.
20474 ((zerop i) (throw 'exit (setq min-i 0)))
20475 ((< i min-i) (setq min-i i))))
20476 (forward-line))))
20477 ;; Then indent each line so that a line indented to
20478 ;; MIN-I becomes indented to IND. Ignore blank lines
20479 ;; and inline tasks in the process.
20480 (let ((delta (- ind min-i)))
20481 (while (< (point) end)
20482 (unless (or (looking-at "^[ \t]*$")
20483 (looking-at org-outline-regexp-bol))
20484 (org-indent-line-to (+ (org-get-indentation) delta)))
20485 (forward-line)))))))
20486 (skip-blanks
20487 (function
20488 ;; Return beginning of first non-blank line, starting from
20489 ;; line at POS.
20490 (lambda (pos)
20491 (save-excursion
20492 (goto-char pos)
20493 (skip-chars-forward " \r\t\n")
20494 (point-at-bol)))))
20495 beg end)
20496 ;; Determine boundaries of changes.
20497 (if (org-region-active-p)
20498 (setq beg (funcall skip-blanks (region-beginning))
20499 end (copy-marker (region-end)))
20500 (setq beg (funcall skip-blanks (point-at-bol))
20501 end (copy-marker (point-at-eol))))
20502 ;; Depending on the starting line, choose an action on the text
20503 ;; between BEG and END.
20504 (org-with-limited-levels
20505 (save-excursion
20506 (goto-char beg)
20507 (cond
20508 ;; Case 1. Start at an item: de-itemize. Note that it only
20509 ;; happens when a region is active: `org-ctrl-c-minus'
20510 ;; would call `org-cycle-list-bullet' otherwise.
20511 ((org-at-item-p)
20512 (while (< (point) end)
20513 (when (org-at-item-p)
20514 (skip-chars-forward " \t")
20515 (delete-region (point) (match-end 0)))
20516 (forward-line)))
20517 ;; Case 2. Start at an heading: convert to items.
20518 ((org-at-heading-p)
20519 (let* ((bul (org-list-bullet-string "-"))
20520 (bul-len (length bul))
20521 ;; Indentation of the first heading. It should be
20522 ;; relative to the indentation of its parent, if any.
20523 (start-ind (save-excursion
20524 (cond
20525 ((not org-adapt-indentation) 0)
20526 ((not (outline-previous-heading)) 0)
20527 (t (length (match-string 0))))))
20528 ;; Level of first heading. Further headings will be
20529 ;; compared to it to determine hierarchy in the list.
20530 (ref-level (org-reduced-level (org-outline-level))))
20531 (while (< (point) end)
20532 (let* ((level (org-reduced-level (org-outline-level)))
20533 (delta (max 0 (- level ref-level))))
20534 ;; If current headline is less indented than the first
20535 ;; one, set it as reference, in order to preserve
20536 ;; subtrees.
20537 (when (< level ref-level) (setq ref-level level))
20538 (replace-match bul t t)
20539 (org-indent-line-to (+ start-ind (* delta bul-len)))
20540 ;; Ensure all text down to END (or SECTION-END) belongs
20541 ;; to the newly created item.
20542 (let ((section-end (save-excursion
20543 (or (outline-next-heading) (point)))))
20544 (forward-line)
20545 (funcall shift-text
20546 (+ start-ind (* (1+ delta) bul-len))
20547 (min end section-end)))))))
20548 ;; Case 3. Normal line with ARG: make the first line of region
20549 ;; an item, and shift indentation of others lines to
20550 ;; set them as item's body.
20551 (arg (let* ((bul (org-list-bullet-string "-"))
20552 (bul-len (length bul))
20553 (ref-ind (org-get-indentation)))
20554 (skip-chars-forward " \t")
20555 (insert bul)
20556 (forward-line)
20557 (while (< (point) end)
20558 ;; Ensure that lines less indented than first one
20559 ;; still get included in item body.
20560 (funcall shift-text
20561 (+ ref-ind bul-len)
20562 (min end (save-excursion (or (outline-next-heading)
20563 (point)))))
20564 (forward-line))))
20565 ;; Case 4. Normal line without ARG: turn each non-item line
20566 ;; into an item.
20568 (while (< (point) end)
20569 (unless (or (org-at-heading-p) (org-at-item-p))
20570 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20571 (replace-match
20572 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20573 (forward-line))))))))
20575 (defun org-toggle-heading (&optional nstars)
20576 "Convert headings to normal text, or items or text to headings.
20577 If there is no active region, only convert the current line.
20579 With a \\[universal-argument] prefix, convert the whole list at
20580 point into heading.
20582 In a region:
20584 - If the first non blank line is a headline, remove the stars
20585 from all headlines in the region.
20587 - If it is a normal line, turn each and every normal line (i.e.,
20588 not an heading or an item) in the region into headings. If you
20589 want to convert only the first line of this region, use one
20590 universal prefix argument.
20592 - If it is a plain list item, turn all plain list items into headings.
20594 When converting a line into a heading, the number of stars is chosen
20595 such that the lines become children of the current entry. However,
20596 when a numeric prefix argument is given, its value determines the
20597 number of stars to add."
20598 (interactive "P")
20599 (let ((skip-blanks
20600 (function
20601 ;; Return beginning of first non-blank line, starting from
20602 ;; line at POS.
20603 (lambda (pos)
20604 (save-excursion
20605 (goto-char pos)
20606 (while (org-at-comment-p) (forward-line))
20607 (skip-chars-forward " \r\t\n")
20608 (point-at-bol)))))
20609 beg end toggled)
20610 ;; Determine boundaries of changes. If a universal prefix has
20611 ;; been given, put the list in a region. If region ends at a bol,
20612 ;; do not consider the last line to be in the region.
20614 (when (and current-prefix-arg (org-at-item-p))
20615 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20616 (org-mark-element))
20618 (if (org-region-active-p)
20619 (setq beg (funcall skip-blanks (region-beginning))
20620 end (copy-marker (save-excursion
20621 (goto-char (region-end))
20622 (if (bolp) (point) (point-at-eol)))))
20623 (setq beg (funcall skip-blanks (point-at-bol))
20624 end (copy-marker (point-at-eol))))
20625 ;; Ensure inline tasks don't count as headings.
20626 (org-with-limited-levels
20627 (save-excursion
20628 (goto-char beg)
20629 (cond
20630 ;; Case 1. Started at an heading: de-star headings.
20631 ((org-at-heading-p)
20632 (while (< (point) end)
20633 (when (org-at-heading-p t)
20634 (looking-at org-outline-regexp) (replace-match "")
20635 (setq toggled t))
20636 (forward-line)))
20637 ;; Case 2. Started at an item: change items into headlines.
20638 ;; One star will be added by `org-list-to-subtree'.
20639 ((org-at-item-p)
20640 (let* ((stars (make-string
20641 ;; subtract the star that will be added again by
20642 ;; `org-list-to-subtree'
20643 (if (numberp nstars) (1- nstars)
20644 (or (org-current-level) 0))
20645 ?*))
20646 (add-stars
20647 (cond (nstars "") ; stars from prefix only
20648 ((equal stars "") "") ; before first heading
20649 (org-odd-levels-only "*") ; inside heading, odd
20650 (t "")))) ; inside heading, oddeven
20651 (while (< (point) end)
20652 (when (org-at-item-p)
20653 ;; Pay attention to cases when region ends before list.
20654 (let* ((struct (org-list-struct))
20655 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20656 (save-restriction
20657 (narrow-to-region (point) list-end)
20658 (insert
20659 (org-list-to-subtree
20660 (org-list-parse-list t)
20661 '(:istart (concat stars add-stars (funcall get-stars depth))
20662 :icount (concat stars add-stars (funcall get-stars depth)))))))
20663 (setq toggled t))
20664 (forward-line))))
20665 ;; Case 3. Started at normal text: make every line an heading,
20666 ;; skipping headlines and items.
20667 (t (let* ((stars
20668 (make-string
20669 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20670 (add-stars
20671 (cond (nstars "") ; stars from prefix only
20672 ((equal stars "") "*") ; before first heading
20673 (org-odd-levels-only "**") ; inside heading, odd
20674 (t "*"))) ; inside heading, oddeven
20675 (rpl (concat stars add-stars " "))
20676 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20677 (while (< (point) (if (equal nstars '(4)) lend end))
20678 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20679 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20680 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20681 (forward-line)))))))
20682 (unless toggled (message "Cannot toggle heading from here"))))
20684 (defun org-meta-return (&optional arg)
20685 "Insert a new heading or wrap a region in a table.
20686 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
20687 See the individual commands for more information."
20688 (interactive "P")
20689 (org-check-before-invisible-edit 'insert)
20690 (cond
20691 ((run-hook-with-args-until-success 'org-metareturn-hook))
20692 ((or (org-at-drawer-p) (org-in-drawer-p) (org-at-property-p))
20693 (newline-and-indent))
20694 ((org-at-table-p)
20695 (call-interactively 'org-table-wrap-region))
20696 (t (call-interactively 'org-insert-heading))))
20698 ;;; Menu entries
20700 (defsubst org-in-subtree-not-table-p ()
20701 "Are we in a subtree and not in a table?"
20702 (and (not (org-before-first-heading-p))
20703 (not (org-at-table-p))))
20705 ;; Define the Org-mode menus
20706 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20707 '("Tbl"
20708 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20709 ["Next Field" org-cycle (org-at-table-p)]
20710 ["Previous Field" org-shifttab (org-at-table-p)]
20711 ["Next Row" org-return (org-at-table-p)]
20712 "--"
20713 ["Blank Field" org-table-blank-field (org-at-table-p)]
20714 ["Edit Field" org-table-edit-field (org-at-table-p)]
20715 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20716 "--"
20717 ("Column"
20718 ["Move Column Left" org-metaleft (org-at-table-p)]
20719 ["Move Column Right" org-metaright (org-at-table-p)]
20720 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20721 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20722 ("Row"
20723 ["Move Row Up" org-metaup (org-at-table-p)]
20724 ["Move Row Down" org-metadown (org-at-table-p)]
20725 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20726 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20727 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20728 "--"
20729 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20730 ("Rectangle"
20731 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20732 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20733 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20734 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20735 "--"
20736 ("Calculate"
20737 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20738 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20739 ["Edit Formulas" org-edit-special (org-at-table-p)]
20740 "--"
20741 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20742 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20743 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20744 "--"
20745 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20746 "--"
20747 ["Sum Column/Rectangle" org-table-sum
20748 (or (org-at-table-p) (org-region-active-p))]
20749 ["Which Column?" org-table-current-column (org-at-table-p)])
20750 ["Debug Formulas"
20751 org-table-toggle-formula-debugger
20752 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20753 ["Show Col/Row Numbers"
20754 org-table-toggle-coordinate-overlays
20755 :style toggle
20756 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20757 "--"
20758 ["Create" org-table-create (and (not (org-at-table-p))
20759 org-enable-table-editor)]
20760 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20761 ["Import from File" org-table-import (not (org-at-table-p))]
20762 ["Export to File" org-table-export (org-at-table-p)]
20763 "--"
20764 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20766 (easy-menu-define org-org-menu org-mode-map "Org menu"
20767 '("Org"
20768 ("Show/Hide"
20769 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20770 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20771 ["Sparse Tree..." org-sparse-tree t]
20772 ["Reveal Context" org-reveal t]
20773 ["Show All" show-all t]
20774 "--"
20775 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20776 "--"
20777 ["New Heading" org-insert-heading t]
20778 ("Navigate Headings"
20779 ["Up" outline-up-heading t]
20780 ["Next" outline-next-visible-heading t]
20781 ["Previous" outline-previous-visible-heading t]
20782 ["Next Same Level" outline-forward-same-level t]
20783 ["Previous Same Level" outline-backward-same-level t]
20784 "--"
20785 ["Jump" org-goto t])
20786 ("Edit Structure"
20787 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20788 "--"
20789 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20790 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20791 "--"
20792 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20793 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20794 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20795 "--"
20796 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20797 "--"
20798 ["Copy visible text" org-copy-visible t]
20799 "--"
20800 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20801 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20802 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20803 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20804 "--"
20805 ["Sort Region/Children" org-sort t]
20806 "--"
20807 ["Convert to odd levels" org-convert-to-odd-levels t]
20808 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20809 ("Editing"
20810 ["Emphasis..." org-emphasize t]
20811 ["Edit Source Example" org-edit-special t]
20812 "--"
20813 ["Footnote new/jump" org-footnote-action t]
20814 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20815 ("Archive"
20816 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20817 "--"
20818 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20819 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20820 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20822 "--"
20823 ("Hyperlinks"
20824 ["Store Link (Global)" org-store-link t]
20825 ["Find existing link to here" org-occur-link-in-agenda-files t]
20826 ["Insert Link" org-insert-link t]
20827 ["Follow Link" org-open-at-point t]
20828 "--"
20829 ["Next link" org-next-link t]
20830 ["Previous link" org-previous-link t]
20831 "--"
20832 ["Descriptive Links"
20833 org-toggle-link-display
20834 :style radio
20835 :selected org-descriptive-links
20837 ["Literal Links"
20838 org-toggle-link-display
20839 :style radio
20840 :selected (not org-descriptive-links)])
20841 "--"
20842 ("TODO Lists"
20843 ["TODO/DONE/-" org-todo t]
20844 ("Select keyword"
20845 ["Next keyword" org-shiftright (org-at-heading-p)]
20846 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20847 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20848 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20849 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20850 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20851 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20852 "--"
20853 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20854 :selected org-enforce-todo-dependencies :style toggle :active t]
20855 "Settings for tree at point"
20856 ["Do Children sequentially" org-toggle-ordered-property :style radio
20857 :selected (org-entry-get nil "ORDERED")
20858 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20859 ["Do Children parallel" org-toggle-ordered-property :style radio
20860 :selected (not (org-entry-get nil "ORDERED"))
20861 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20862 "--"
20863 ["Set Priority" org-priority t]
20864 ["Priority Up" org-shiftup t]
20865 ["Priority Down" org-shiftdown t]
20866 "--"
20867 ["Get news from all feeds" org-feed-update-all t]
20868 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20869 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20870 ("TAGS and Properties"
20871 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20872 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20873 "--"
20874 ["Set property" org-set-property (not (org-before-first-heading-p))]
20875 ["Column view of properties" org-columns t]
20876 ["Insert Column View DBlock" org-insert-columns-dblock t])
20877 ("Dates and Scheduling"
20878 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20879 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20880 ("Change Date"
20881 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20882 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20883 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20884 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20885 ["Compute Time Range" org-evaluate-time-range t]
20886 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20887 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20888 "--"
20889 ["Custom time format" org-toggle-time-stamp-overlays
20890 :style radio :selected org-display-custom-times]
20891 "--"
20892 ["Goto Calendar" org-goto-calendar t]
20893 ["Date from Calendar" org-date-from-calendar t]
20894 "--"
20895 ["Start/Restart Timer" org-timer-start t]
20896 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20897 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20898 ["Insert Timer String" org-timer t]
20899 ["Insert Timer Item" org-timer-item t])
20900 ("Logging work"
20901 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20902 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20903 ["Clock out" org-clock-out t]
20904 ["Clock cancel" org-clock-cancel t]
20905 "--"
20906 ["Mark as default task" org-clock-mark-default-task t]
20907 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20908 ["Goto running clock" org-clock-goto t]
20909 "--"
20910 ["Display times" org-clock-display t]
20911 ["Create clock table" org-clock-report t]
20912 "--"
20913 ["Record DONE time"
20914 (progn (setq org-log-done (not org-log-done))
20915 (message "Switching to %s will %s record a timestamp"
20916 (car org-done-keywords)
20917 (if org-log-done "automatically" "not")))
20918 :style toggle :selected org-log-done])
20919 "--"
20920 ["Agenda Command..." org-agenda t]
20921 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20922 ("File List for Agenda")
20923 ("Special views current file"
20924 ["TODO Tree" org-show-todo-tree t]
20925 ["Check Deadlines" org-check-deadlines t]
20926 ["Timeline" org-timeline t]
20927 ["Tags/Property tree" org-match-sparse-tree t])
20928 "--"
20929 ["Export/Publish..." org-export-dispatch t]
20930 ("LaTeX"
20931 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20932 :selected org-cdlatex-mode]
20933 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20934 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20935 ["Modify math symbol" org-cdlatex-math-modify
20936 (org-inside-LaTeX-fragment-p)]
20937 ["Insert citation" org-reftex-citation t]
20938 "--"
20939 ["Template for BEAMER" (org-beamer-insert-options-template) t])
20940 "--"
20941 ("MobileOrg"
20942 ["Push Files and Views" org-mobile-push t]
20943 ["Get Captured and Flagged" org-mobile-pull t]
20944 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20945 "--"
20946 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20947 "--"
20948 ("Documentation"
20949 ["Show Version" org-version t]
20950 ["Info Documentation" org-info t])
20951 ("Customize"
20952 ["Browse Org Group" org-customize t]
20953 "--"
20954 ["Expand This Menu" org-create-customize-menu
20955 (fboundp 'customize-menu-create)])
20956 ["Send bug report" org-submit-bug-report t]
20957 "--"
20958 ("Refresh/Reload"
20959 ["Refresh setup current buffer" org-mode-restart t]
20960 ["Reload Org (after update)" org-reload t]
20961 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
20964 (defun org-info (&optional node)
20965 "Read documentation for Org-mode in the info system.
20966 With optional NODE, go directly to that node."
20967 (interactive)
20968 (info (format "(org)%s" (or node ""))))
20970 ;;;###autoload
20971 (defun org-submit-bug-report ()
20972 "Submit a bug report on Org-mode via mail.
20974 Don't hesitate to report any problems or inaccurate documentation.
20976 If you don't have setup sending mail from (X)Emacs, please copy the
20977 output buffer into your mail program, as it gives us important
20978 information about your Org-mode version and configuration."
20979 (interactive)
20980 (require 'reporter)
20981 (org-load-modules-maybe)
20982 (org-require-autoloaded-modules)
20983 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20984 (reporter-submit-bug-report
20985 "emacs-orgmode@gnu.org"
20986 (org-version nil 'full)
20987 (let (list)
20988 (save-window-excursion
20989 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20990 (delete-other-windows)
20991 (erase-buffer)
20992 (insert "You are about to submit a bug report to the Org-mode mailing list.
20994 We would like to add your full Org-mode and Outline configuration to the
20995 bug report. This greatly simplifies the work of the maintainer and
20996 other experts on the mailing list.
20998 HOWEVER, some variables you have customized may contain private
20999 information. The names of customers, colleagues, or friends, might
21000 appear in the form of file names, tags, todo states, or search strings.
21001 If you answer yes to the prompt, you might want to check and remove
21002 such private information before sending the email.")
21003 (add-text-properties (point-min) (point-max) '(face org-warning))
21004 (when (yes-or-no-p "Include your Org-mode configuration ")
21005 (mapatoms
21006 (lambda (v)
21007 (and (boundp v)
21008 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21009 (or (and (symbol-value v)
21010 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21011 (and
21012 (get v 'custom-type) (get v 'standard-value)
21013 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21014 (push v list)))))
21015 (kill-buffer (get-buffer "*Warn about privacy*"))
21016 list))
21017 nil nil
21018 "Remember to cover the basics, that is, what you expected to happen and
21019 what in fact did happen. You don't know how to make a good report? See
21021 http://orgmode.org/manual/Feedback.html#Feedback
21023 Your bug report will be posted to the Org-mode mailing list.
21024 ------------------------------------------------------------------------")
21025 (save-excursion
21026 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21027 (replace-match "\\1Bug: \\3 [\\2]")))))
21030 (defun org-install-agenda-files-menu ()
21031 (let ((bl (buffer-list)))
21032 (save-excursion
21033 (while bl
21034 (set-buffer (pop bl))
21035 (if (derived-mode-p 'org-mode) (setq bl nil)))
21036 (when (derived-mode-p 'org-mode)
21037 (easy-menu-change
21038 '("Org") "File List for Agenda"
21039 (append
21040 (list
21041 ["Edit File List" (org-edit-agenda-file-list) t]
21042 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21043 ["Remove Current File from List" org-remove-file t]
21044 ["Cycle through agenda files" org-cycle-agenda-files t]
21045 ["Occur in all agenda files" org-occur-in-agenda-files t]
21046 "--")
21047 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21049 ;;;; Documentation
21051 (defun org-require-autoloaded-modules ()
21052 (interactive)
21053 (mapc 'require
21054 '(org-agenda org-archive org-attach org-clock org-colview org-id
21055 org-remember org-table org-timer)))
21057 ;;;###autoload
21058 (defun org-reload (&optional uncompiled)
21059 "Reload all org lisp files.
21060 With prefix arg UNCOMPILED, load the uncompiled versions."
21061 (interactive "P")
21062 (require 'loadhist)
21063 (let* ((org-dir (org-find-library-dir "org"))
21064 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21065 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21066 (remove-re (mapconcat 'identity
21067 (mapcar (lambda (f) (concat "^" f "$"))
21068 (list (if (featurep 'xemacs)
21069 "org-colview"
21070 "org-colview-xemacs")
21071 "org" "org-loaddefs" "org-version"))
21072 "\\|"))
21073 (feats (delete-dups
21074 (mapcar 'file-name-sans-extension
21075 (mapcar 'file-name-nondirectory
21076 (delq nil
21077 (mapcar 'feature-file
21078 features))))))
21079 (lfeat (append
21080 (sort
21081 (setq feats
21082 (delq nil (mapcar
21083 (lambda (f)
21084 (if (and (string-match feature-re f)
21085 (not (string-match remove-re f)))
21086 f nil))
21087 feats)))
21088 'string-lessp)
21089 (list "org-version" "org")))
21090 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21091 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21092 load-uncore load-misses)
21093 (setq load-misses
21094 (delq 't
21095 (mapcar (lambda (f)
21096 (or (org-load-noerror-mustsuffix (concat org-dir f))
21097 (and (string= org-dir contrib-dir)
21098 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21099 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21100 (add-to-list 'load-uncore f 'append)
21103 lfeat)))
21104 (if load-uncore
21105 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21106 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21107 (if load-misses
21108 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21109 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21110 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21112 ;;;###autoload
21113 (defun org-customize ()
21114 "Call the customize function with org as argument."
21115 (interactive)
21116 (org-load-modules-maybe)
21117 (org-require-autoloaded-modules)
21118 (customize-browse 'org))
21120 (defun org-create-customize-menu ()
21121 "Create a full customization menu for Org-mode, insert it into the menu."
21122 (interactive)
21123 (org-load-modules-maybe)
21124 (org-require-autoloaded-modules)
21125 (if (fboundp 'customize-menu-create)
21126 (progn
21127 (easy-menu-change
21128 '("Org") "Customize"
21129 `(["Browse Org group" org-customize t]
21130 "--"
21131 ,(customize-menu-create 'org)
21132 ["Set" Custom-set t]
21133 ["Save" Custom-save t]
21134 ["Reset to Current" Custom-reset-current t]
21135 ["Reset to Saved" Custom-reset-saved t]
21136 ["Reset to Standard Settings" Custom-reset-standard t]))
21137 (message "\"Org\"-menu now contains full customization menu"))
21138 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21140 ;;;; Miscellaneous stuff
21142 ;;; Generally useful functions
21144 (defun org-get-at-bol (property)
21145 "Get text property PROPERTY at beginning of line."
21146 (get-text-property (point-at-bol) property))
21148 (defun org-find-text-property-in-string (prop s)
21149 "Return the first non-nil value of property PROP in string S."
21150 (or (get-text-property 0 prop s)
21151 (get-text-property (or (next-single-property-change 0 prop s) 0)
21152 prop s)))
21154 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21155 "Display the given MESSAGE as a warning."
21156 (if (fboundp 'display-warning)
21157 (display-warning 'org message
21158 (if (featurep 'xemacs) 'warning :warning))
21159 (let ((buf (get-buffer-create "*Org warnings*")))
21160 (with-current-buffer buf
21161 (goto-char (point-max))
21162 (insert "Warning (Org): " message)
21163 (unless (bolp)
21164 (newline)))
21165 (display-buffer buf)
21166 (sit-for 0))))
21168 (defun org-eval (form)
21169 "Eval FORM and return result."
21170 (condition-case error
21171 (eval form)
21172 (error (format "%%![Error: %s]" error))))
21174 (defun org-in-clocktable-p ()
21175 "Check if the cursor is in a clocktable."
21176 (let ((pos (point)) start)
21177 (save-excursion
21178 (end-of-line 1)
21179 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21180 (setq start (match-beginning 0))
21181 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21182 (>= (match-end 0) pos)
21183 start))))
21185 (defun org-in-commented-line ()
21186 "Is point in a line starting with `#'?"
21187 (equal (char-after (point-at-bol)) ?#))
21189 (defun org-in-indented-comment-line ()
21190 "Is point in a line starting with `#' after some white space?"
21191 (save-excursion
21192 (save-match-data
21193 (goto-char (point-at-bol))
21194 (looking-at "[ \t]*#"))))
21196 (defun org-in-verbatim-emphasis ()
21197 (save-match-data
21198 (and (org-in-regexp org-emph-re 2)
21199 (>= (point) (match-beginning 3))
21200 (<= (point) (match-end 4))
21201 (member (match-string 3) '("=" "~")))))
21203 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21204 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21205 (if (and marker (marker-buffer marker)
21206 (buffer-live-p (marker-buffer marker)))
21207 (progn
21208 (org-pop-to-buffer-same-window (marker-buffer marker))
21209 (if (or (> marker (point-max)) (< marker (point-min)))
21210 (widen))
21211 (goto-char marker)
21212 (org-show-context 'org-goto))
21213 (if bookmark
21214 (bookmark-jump bookmark)
21215 (error "Cannot find location"))))
21217 (defun org-quote-csv-field (s)
21218 "Quote field for inclusion in CSV material."
21219 (if (string-match "[\",]" s)
21220 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21223 (defun org-force-self-insert (N)
21224 "Needed to enforce self-insert under remapping."
21225 (interactive "p")
21226 (self-insert-command N))
21228 (defun org-string-width (s)
21229 "Compute width of string, ignoring invisible characters.
21230 This ignores character with invisibility property `org-link', and also
21231 characters with property `org-cwidth', because these will become invisible
21232 upon the next fontification round."
21233 (let (b l)
21234 (when (or (eq t buffer-invisibility-spec)
21235 (assq 'org-link buffer-invisibility-spec))
21236 (while (setq b (text-property-any 0 (length s)
21237 'invisible 'org-link s))
21238 (setq s (concat (substring s 0 b)
21239 (substring s (or (next-single-property-change
21240 b 'invisible s) (length s)))))))
21241 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21242 (setq s (concat (substring s 0 b)
21243 (substring s (or (next-single-property-change
21244 b 'org-cwidth s) (length s))))))
21245 (setq l (string-width s) b -1)
21246 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21247 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21250 (defun org-shorten-string (s maxlength)
21251 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21252 If the string is shorter or has length MAXLENGTH, just return the
21253 original string. If it is longer, the functions finds a space in the
21254 string, breaks this string off at that locations and adds three dots
21255 as ellipsis. Including the ellipsis, the string will not be longer
21256 than MAXLENGTH. If finding a good breaking point in the string does
21257 not work, the string is just chopped off in the middle of a word
21258 if necessary."
21259 (if (<= (length s) maxlength)
21261 (let* ((n (max (- maxlength 4) 1))
21262 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21263 (if (string-match re s)
21264 (concat (match-string 1 s) "...")
21265 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21267 (defun org-get-indentation (&optional line)
21268 "Get the indentation of the current line, interpreting tabs.
21269 When LINE is given, assume it represents a line and compute its indentation."
21270 (if line
21271 (if (string-match "^ *" (org-remove-tabs line))
21272 (match-end 0))
21273 (save-excursion
21274 (beginning-of-line 1)
21275 (skip-chars-forward " \t")
21276 (current-column))))
21278 (defun org-get-string-indentation (s)
21279 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21280 (let ((n -1) (i 0) (w tab-width) c)
21281 (catch 'exit
21282 (while (< (setq n (1+ n)) (length s))
21283 (setq c (aref s n))
21284 (cond ((= c ?\ ) (setq i (1+ i)))
21285 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21286 (t (throw 'exit t)))))
21289 (defun org-remove-tabs (s &optional width)
21290 "Replace tabulators in S with spaces.
21291 Assumes that s is a single line, starting in column 0."
21292 (setq width (or width tab-width))
21293 (while (string-match "\t" s)
21294 (setq s (replace-match
21295 (make-string
21296 (- (* width (/ (+ (match-beginning 0) width) width))
21297 (match-beginning 0)) ?\ )
21298 t t s)))
21301 (defun org-fix-indentation (line ind)
21302 "Fix indentation in LINE.
21303 IND is a cons cell with target and minimum indentation.
21304 If the current indentation in LINE is smaller than the minimum,
21305 leave it alone. If it is larger than ind, set it to the target."
21306 (let* ((l (org-remove-tabs line))
21307 (i (org-get-indentation l))
21308 (i1 (car ind)) (i2 (cdr ind)))
21309 (if (>= i i2) (setq l (substring line i2)))
21310 (if (> i1 0)
21311 (concat (make-string i1 ?\ ) l)
21312 l)))
21314 (defun org-remove-indentation (code &optional n)
21315 "Remove the maximum common indentation from the lines in CODE.
21316 N may optionally be the number of spaces to remove."
21317 (with-temp-buffer
21318 (insert code)
21319 (org-do-remove-indentation n)
21320 (buffer-string)))
21322 (defun org-do-remove-indentation (&optional n)
21323 "Remove the maximum common indentation from the buffer."
21324 (untabify (point-min) (point-max))
21325 (let ((min 10000) re)
21326 (if n
21327 (setq min n)
21328 (goto-char (point-min))
21329 (while (re-search-forward "^ *[^ \n]" nil t)
21330 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21331 (unless (or (= min 0) (= min 10000))
21332 (setq re (format "^ \\{%d\\}" min))
21333 (goto-char (point-min))
21334 (while (re-search-forward re nil t)
21335 (replace-match "")
21336 (end-of-line 1))
21337 min)))
21339 (defun org-fill-template (template alist)
21340 "Find each %key of ALIST in TEMPLATE and replace it."
21341 (let ((case-fold-search nil)
21342 entry key value)
21343 (setq alist (sort (copy-sequence alist)
21344 (lambda (a b) (< (length (car a)) (length (car b))))))
21345 (while (setq entry (pop alist))
21346 (setq template
21347 (replace-regexp-in-string
21348 (concat "%" (regexp-quote (car entry)))
21349 (or (cdr entry) "") template t t)))
21350 template))
21352 (defun org-base-buffer (buffer)
21353 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21354 (if (not buffer)
21355 buffer
21356 (or (buffer-base-buffer buffer)
21357 buffer)))
21359 (defun org-trim (s)
21360 "Remove whitespace at beginning and end of string."
21361 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
21362 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
21365 (defun org-wrap (string &optional width lines)
21366 "Wrap string to either a number of lines, or a width in characters.
21367 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21368 that costs. If there is a word longer than WIDTH, the text is actually
21369 wrapped to the length of that word.
21370 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21371 many lines, whatever width that takes.
21372 The return value is a list of lines, without newlines at the end."
21373 (let* ((words (org-split-string string "[ \t\n]+"))
21374 (maxword (apply 'max (mapcar 'org-string-width words)))
21375 w ll)
21376 (cond (width
21377 (org-do-wrap words (max maxword width)))
21378 (lines
21379 (setq w maxword)
21380 (setq ll (org-do-wrap words maxword))
21381 (if (<= (length ll) lines)
21383 (setq ll words)
21384 (while (> (length ll) lines)
21385 (setq w (1+ w))
21386 (setq ll (org-do-wrap words w)))
21387 ll))
21388 (t (error "Cannot wrap this")))))
21390 (defun org-do-wrap (words width)
21391 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21392 (let (lines line)
21393 (while words
21394 (setq line (pop words))
21395 (while (and words (< (+ (length line) (length (car words))) width))
21396 (setq line (concat line " " (pop words))))
21397 (setq lines (push line lines)))
21398 (nreverse lines)))
21400 (defun org-split-string (string &optional separators)
21401 "Splits STRING into substrings at SEPARATORS.
21402 No empty strings are returned if there are matches at the beginning
21403 and end of string."
21404 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21405 (start 0)
21406 notfirst
21407 (list nil))
21408 (while (and (string-match rexp string
21409 (if (and notfirst
21410 (= start (match-beginning 0))
21411 (< start (length string)))
21412 (1+ start) start))
21413 (< (match-beginning 0) (length string)))
21414 (setq notfirst t)
21415 (or (eq (match-beginning 0) 0)
21416 (and (eq (match-beginning 0) (match-end 0))
21417 (eq (match-beginning 0) start))
21418 (setq list
21419 (cons (substring string start (match-beginning 0))
21420 list)))
21421 (setq start (match-end 0)))
21422 (or (eq start (length string))
21423 (setq list
21424 (cons (substring string start)
21425 list)))
21426 (nreverse list)))
21428 (defun org-quote-vert (s)
21429 "Replace \"|\" with \"\\vert\"."
21430 (while (string-match "|" s)
21431 (setq s (replace-match "\\vert" t t s)))
21434 (defun org-uuidgen-p (s)
21435 "Is S an ID created by UUIDGEN?"
21436 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21438 (defun org-in-src-block-p (&optional inside)
21439 "Whether point is in a code source block.
21440 When INSIDE is non-nil, don't consider we are within a src block
21441 when point is at #+BEGIN_SRC or #+END_SRC."
21442 (let ((case-fold-search t) ov)
21443 (or (and (setq ov (overlays-at (point)))
21444 (memq 'org-block-background
21445 (overlay-properties (car ov))))
21446 (and (not inside)
21447 (save-match-data
21448 (save-excursion
21449 (beginning-of-line)
21450 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21452 (defun org-context ()
21453 "Return a list of contexts of the current cursor position.
21454 If several contexts apply, all are returned.
21455 Each context entry is a list with a symbol naming the context, and
21456 two positions indicating start and end of the context. Possible
21457 contexts are:
21459 :headline anywhere in a headline
21460 :headline-stars on the leading stars in a headline
21461 :todo-keyword on a TODO keyword (including DONE) in a headline
21462 :tags on the TAGS in a headline
21463 :priority on the priority cookie in a headline
21464 :item on the first line of a plain list item
21465 :item-bullet on the bullet/number of a plain list item
21466 :checkbox on the checkbox in a plain list item
21467 :table in an org-mode table
21468 :table-special on a special filed in a table
21469 :table-table in a table.el table
21470 :clocktable in a clocktable
21471 :src-block in a source block
21472 :link on a hyperlink
21473 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21474 :target on a <<target>>
21475 :radio-target on a <<<radio-target>>>
21476 :latex-fragment on a LaTeX fragment
21477 :latex-preview on a LaTeX fragment with overlaid preview image
21479 This function expects the position to be visible because it uses font-lock
21480 faces as a help to recognize the following contexts: :table-special, :link,
21481 and :keyword."
21482 (let* ((f (get-text-property (point) 'face))
21483 (faces (if (listp f) f (list f)))
21484 (case-fold-search t)
21485 (p (point)) clist o)
21486 ;; First the large context
21487 (cond
21488 ((org-at-heading-p t)
21489 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21490 (when (progn
21491 (beginning-of-line 1)
21492 (looking-at org-todo-line-tags-regexp))
21493 (push (org-point-in-group p 1 :headline-stars) clist)
21494 (push (org-point-in-group p 2 :todo-keyword) clist)
21495 (push (org-point-in-group p 4 :tags) clist))
21496 (goto-char p)
21497 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21498 (if (looking-at "\\[#[A-Z0-9]\\]")
21499 (push (org-point-in-group p 0 :priority) clist)))
21501 ((org-at-item-p)
21502 (push (org-point-in-group p 2 :item-bullet) clist)
21503 (push (list :item (point-at-bol)
21504 (save-excursion (org-end-of-item) (point)))
21505 clist)
21506 (and (org-at-item-checkbox-p)
21507 (push (org-point-in-group p 0 :checkbox) clist)))
21509 ((org-at-table-p)
21510 (push (list :table (org-table-begin) (org-table-end)) clist)
21511 (if (memq 'org-formula faces)
21512 (push (list :table-special
21513 (previous-single-property-change p 'face)
21514 (next-single-property-change p 'face)) clist)))
21515 ((org-at-table-p 'any)
21516 (push (list :table-table) clist)))
21517 (goto-char p)
21519 (let ((case-fold-search t))
21520 ;; New the "medium" contexts: clocktables, source blocks
21521 (cond ((org-in-clocktable-p)
21522 (push (list :clocktable
21523 (and (or (looking-at "#\\+BEGIN: clocktable")
21524 (search-backward "#+BEGIN: clocktable" nil t))
21525 (match-beginning 0))
21526 (and (re-search-forward "#\\+END:?" nil t)
21527 (match-end 0))) clist))
21528 ((org-in-src-block-p)
21529 (push (list :src-block
21530 (and (or (looking-at "#\\+BEGIN_SRC")
21531 (search-backward "#+BEGIN_SRC" nil t))
21532 (match-beginning 0))
21533 (and (search-forward "#+END_SRC" nil t)
21534 (match-beginning 0))) clist))))
21535 (goto-char p)
21537 ;; Now the small context
21538 (cond
21539 ((org-at-timestamp-p)
21540 (push (org-point-in-group p 0 :timestamp) clist))
21541 ((memq 'org-link faces)
21542 (push (list :link
21543 (previous-single-property-change p 'face)
21544 (next-single-property-change p 'face)) clist))
21545 ((memq 'org-special-keyword faces)
21546 (push (list :keyword
21547 (previous-single-property-change p 'face)
21548 (next-single-property-change p 'face)) clist))
21549 ((org-at-target-p)
21550 (push (org-point-in-group p 0 :target) clist)
21551 (goto-char (1- (match-beginning 0)))
21552 (if (looking-at org-radio-target-regexp)
21553 (push (org-point-in-group p 0 :radio-target) clist))
21554 (goto-char p))
21555 ((setq o (car (delq nil
21556 (mapcar
21557 (lambda (x)
21558 (if (memq x org-latex-fragment-image-overlays) x))
21559 (overlays-at (point))))))
21560 (push (list :latex-fragment
21561 (overlay-start o) (overlay-end o)) clist)
21562 (push (list :latex-preview
21563 (overlay-start o) (overlay-end o)) clist))
21564 ((org-inside-LaTeX-fragment-p)
21565 ;; FIXME: positions wrong.
21566 (push (list :latex-fragment (point) (point)) clist)))
21568 (setq clist (nreverse (delq nil clist)))
21569 clist))
21571 ;; FIXME: Compare with at-regexp-p Do we need both?
21572 (defun org-in-regexp (re &optional nlines visually)
21573 "Check if point is inside a match of regexp.
21574 Normally only the current line is checked, but you can include NLINES extra
21575 lines both before and after point into the search.
21576 If VISUALLY is set, require that the cursor is not after the match but
21577 really on, so that the block visually is on the match."
21578 (catch 'exit
21579 (let ((pos (point))
21580 (eol (point-at-eol (+ 1 (or nlines 0))))
21581 (inc (if visually 1 0)))
21582 (save-excursion
21583 (beginning-of-line (- 1 (or nlines 0)))
21584 (while (re-search-forward re eol t)
21585 (if (and (<= (match-beginning 0) pos)
21586 (>= (+ inc (match-end 0)) pos))
21587 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21589 (defun org-at-regexp-p (regexp)
21590 "Is point inside a match of REGEXP in the current line?"
21591 (catch 'exit
21592 (save-excursion
21593 (let ((pos (point)) (end (point-at-eol)))
21594 (beginning-of-line 1)
21595 (while (re-search-forward regexp end t)
21596 (if (and (<= (match-beginning 0) pos)
21597 (>= (match-end 0) pos))
21598 (throw 'exit t)))
21599 nil))))
21601 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21602 "Non-nil when point is between matches of START-RE and END-RE.
21604 Also return a non-nil value when point is on one of the matches.
21606 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21607 buffer positions. Default values are the positions of headlines
21608 surrounding the point.
21610 The functions returns a cons cell whose car (resp. cdr) is the
21611 position before START-RE (resp. after END-RE)."
21612 (save-match-data
21613 (let ((pos (point))
21614 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21615 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21616 beg end)
21617 (save-excursion
21618 ;; Point is on a block when on START-RE or if START-RE can be
21619 ;; found before it...
21620 (and (or (org-at-regexp-p start-re)
21621 (re-search-backward start-re limit-up t))
21622 (setq beg (match-beginning 0))
21623 ;; ... and END-RE after it...
21624 (goto-char (match-end 0))
21625 (re-search-forward end-re limit-down t)
21626 (> (setq end (match-end 0)) pos)
21627 ;; ... without another START-RE in-between.
21628 (goto-char (match-beginning 0))
21629 (not (re-search-backward start-re (1+ beg) t))
21630 ;; Return value.
21631 (cons beg end))))))
21633 (defun org-in-block-p (names)
21634 "Non-nil when point belongs to a block whose name belongs to NAMES.
21636 NAMES is a list of strings containing names of blocks.
21638 Return first block name matched, or nil. Beware that in case of
21639 nested blocks, the returned name may not belong to the closest
21640 block from point."
21641 (save-match-data
21642 (catch 'exit
21643 (let ((case-fold-search t)
21644 (lim-up (save-excursion (outline-previous-heading)))
21645 (lim-down (save-excursion (outline-next-heading))))
21646 (mapc (lambda (name)
21647 (let ((n (regexp-quote name)))
21648 (when (org-between-regexps-p
21649 (concat "^[ \t]*#\\+begin_" n)
21650 (concat "^[ \t]*#\\+end_" n)
21651 lim-up lim-down)
21652 (throw 'exit n))))
21653 names))
21654 nil)))
21656 (defun org-in-drawer-p ()
21657 "Is point within a drawer?"
21658 (save-match-data
21659 (let ((case-fold-search t)
21660 (lim-up (save-excursion (outline-previous-heading)))
21661 (lim-down (save-excursion (outline-next-heading))))
21662 (org-between-regexps-p
21663 (concat "^[ \t]*:" (regexp-opt org-drawers) ":")
21664 "^[ \t]*:end:.*$"
21665 lim-up lim-down))))
21667 (defun org-occur-in-agenda-files (regexp &optional nlines)
21668 "Call `multi-occur' with buffers for all agenda files."
21669 (interactive "sOrg-files matching: \np")
21670 (let* ((files (org-agenda-files))
21671 (tnames (mapcar 'file-truename files))
21672 (extra org-agenda-text-search-extra-files)
21674 (when (eq (car extra) 'agenda-archives)
21675 (setq extra (cdr extra))
21676 (setq files (org-add-archive-files files)))
21677 (while (setq f (pop extra))
21678 (unless (member (file-truename f) tnames)
21679 (add-to-list 'files f 'append)
21680 (add-to-list 'tnames (file-truename f) 'append)))
21681 (multi-occur
21682 (mapcar (lambda (x)
21683 (with-current-buffer
21684 (or (get-file-buffer x) (find-file-noselect x))
21685 (widen)
21686 (current-buffer)))
21687 files)
21688 regexp)))
21690 (if (boundp 'occur-mode-find-occurrence-hook)
21691 ;; Emacs 23
21692 (add-hook 'occur-mode-find-occurrence-hook
21693 (lambda ()
21694 (when (derived-mode-p 'org-mode)
21695 (org-reveal))))
21696 ;; Emacs 22
21697 (defadvice occur-mode-goto-occurrence
21698 (after org-occur-reveal activate)
21699 (and (derived-mode-p 'org-mode) (org-reveal)))
21700 (defadvice occur-mode-goto-occurrence-other-window
21701 (after org-occur-reveal activate)
21702 (and (derived-mode-p 'org-mode) (org-reveal)))
21703 (defadvice occur-mode-display-occurrence
21704 (after org-occur-reveal activate)
21705 (when (derived-mode-p 'org-mode)
21706 (let ((pos (occur-mode-find-occurrence)))
21707 (with-current-buffer (marker-buffer pos)
21708 (save-excursion
21709 (goto-char pos)
21710 (org-reveal)))))))
21712 (defun org-occur-link-in-agenda-files ()
21713 "Create a link and search for it in the agendas.
21714 The link is not stored in `org-stored-links', it is just created
21715 for the search purpose."
21716 (interactive)
21717 (let ((link (condition-case nil
21718 (org-store-link nil)
21719 (error "Unable to create a link to here"))))
21720 (org-occur-in-agenda-files (regexp-quote link))))
21722 (defun org-reverse-string (string)
21723 "Return the reverse of STRING."
21724 (apply 'string (reverse (string-to-list string))))
21726 (defsubst org-uniquify (list)
21727 "Non-destructively remove duplicate elements from LIST."
21728 (let ((res (copy-sequence list))) (delete-dups res)))
21730 (defun org-uniquify-alist (alist)
21731 "Merge elements of ALIST with the same key.
21733 For example, in this alist:
21735 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
21736 => '((a 1 3) (b 2))
21738 merge (a 1) and (a 3) into (a 1 3).
21740 The function returns the new ALIST."
21741 (let (rtn)
21742 (mapc
21743 (lambda (e)
21744 (let (n)
21745 (if (not (assoc (car e) rtn))
21746 (push e rtn)
21747 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
21748 (setq rtn (assq-delete-all (car e) rtn))
21749 (push n rtn))))
21750 alist)
21751 rtn))
21753 (defun org-delete-all (elts list)
21754 "Remove all elements in ELTS from LIST."
21755 (while elts
21756 (setq list (delete (pop elts) list)))
21757 list)
21759 (defun org-count (cl-item cl-seq)
21760 "Count the number of occurrences of ITEM in SEQ.
21761 Taken from `count' in cl-seq.el with all keyword arguments removed."
21762 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21763 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21764 (while (< cl-start cl-end)
21765 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21766 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21767 (setq cl-start (1+ cl-start)))
21768 cl-count))
21770 (defun org-remove-if (predicate seq)
21771 "Remove everything from SEQ that fulfills PREDICATE."
21772 (let (res e)
21773 (while seq
21774 (setq e (pop seq))
21775 (if (not (funcall predicate e)) (push e res)))
21776 (nreverse res)))
21778 (defun org-remove-if-not (predicate seq)
21779 "Remove everything from SEQ that does not fulfill PREDICATE."
21780 (let (res e)
21781 (while seq
21782 (setq e (pop seq))
21783 (if (funcall predicate e) (push e res)))
21784 (nreverse res)))
21786 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21787 "Reduce two-argument FUNCTION across SEQ.
21788 Taken from `reduce' in cl-seq.el with all keyword arguments but
21789 \":initial-value\" removed."
21790 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21791 (cadr (memq :initial-value cl-keys)))
21792 (cl-seq (pop cl-seq))
21793 (t (funcall cl-func)))))
21794 (while cl-seq
21795 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21796 cl-accum))
21798 (defun org-every (pred seq)
21799 "Return true if PREDICATE is true of every element of SEQ.
21800 Adapted from `every' in cl.el."
21801 (catch 'org-every
21802 (mapc (lambda (e) (unless (funcall pred e) (throw 'org-every nil))) seq)
21805 (defun org-some (pred seq)
21806 "Return true if PREDICATE is true of any element of SEQ.
21807 Adapted from `some' in cl.el."
21808 (catch 'org-some
21809 (mapc (lambda (e) (when (funcall pred e) (throw 'org-some t))) seq)
21810 nil))
21812 (defun org-back-over-empty-lines ()
21813 "Move backwards over whitespace, to the beginning of the first empty line.
21814 Returns the number of empty lines passed."
21815 (let ((pos (point)))
21816 (if (cdr (assoc 'heading org-blank-before-new-entry))
21817 (skip-chars-backward " \t\n\r")
21818 (unless (eobp)
21819 (forward-line -1)))
21820 (beginning-of-line 2)
21821 (goto-char (min (point) pos))
21822 (count-lines (point) pos)))
21824 (defun org-skip-whitespace ()
21825 (skip-chars-forward " \t\n\r"))
21827 (defun org-point-in-group (point group &optional context)
21828 "Check if POINT is in match-group GROUP.
21829 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21830 match. If the match group does not exist or point is not inside it,
21831 return nil."
21832 (and (match-beginning group)
21833 (>= point (match-beginning group))
21834 (<= point (match-end group))
21835 (if context
21836 (list context (match-beginning group) (match-end group))
21837 t)))
21839 (defun org-switch-to-buffer-other-window (&rest args)
21840 "Switch to buffer in a second window on the current frame.
21841 In particular, do not allow pop-up frames.
21842 Returns the newly created buffer."
21843 (org-no-popups
21844 (apply 'switch-to-buffer-other-window args)))
21846 (defun org-combine-plists (&rest plists)
21847 "Create a single property list from all plists in PLISTS.
21848 The process starts by copying the first list, and then setting properties
21849 from the other lists. Settings in the last list are the most significant
21850 ones and overrule settings in the other lists."
21851 (let ((rtn (copy-sequence (pop plists)))
21852 p v ls)
21853 (while plists
21854 (setq ls (pop plists))
21855 (while ls
21856 (setq p (pop ls) v (pop ls))
21857 (setq rtn (plist-put rtn p v))))
21858 rtn))
21860 (defun org-replace-escapes (string table)
21861 "Replace %-escapes in STRING with values in TABLE.
21862 TABLE is an association list with keys like \"%a\" and string values.
21863 The sequences in STRING may contain normal field width and padding information,
21864 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21865 so values can contain further %-escapes if they are define later in TABLE."
21866 (let ((tbl (copy-alist table))
21867 (case-fold-search nil)
21868 (pchg 0)
21869 e re rpl)
21870 (while (setq e (pop tbl))
21871 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21872 (when (and (cdr e) (string-match re (cdr e)))
21873 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21874 (safe "SREF"))
21875 (add-text-properties 0 3 (list 'sref sref) safe)
21876 (setcdr e (replace-match safe t t (cdr e)))))
21877 (while (string-match re string)
21878 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21879 (cdr e)))
21880 (setq string (replace-match rpl t t string))))
21881 (while (setq pchg (next-property-change pchg string))
21882 (let ((sref (get-text-property pchg 'sref string)))
21883 (when (and sref (string-match "SREF" string pchg))
21884 (setq string (replace-match sref t t string)))))
21885 string))
21887 (defun org-sublist (list start end)
21888 "Return a section of LIST, from START to END.
21889 Counting starts at 1."
21890 (let (rtn (c start))
21891 (setq list (nthcdr (1- start) list))
21892 (while (and list (<= c end))
21893 (push (pop list) rtn)
21894 (setq c (1+ c)))
21895 (nreverse rtn)))
21897 (defun org-find-base-buffer-visiting (file)
21898 "Like `find-buffer-visiting' but always return the base buffer and
21899 not an indirect buffer."
21900 (let ((buf (or (get-file-buffer file)
21901 (find-buffer-visiting file))))
21902 (if buf
21903 (or (buffer-base-buffer buf) buf)
21904 nil)))
21906 (defun org-image-file-name-regexp (&optional extensions)
21907 "Return regexp matching the file names of images.
21908 If EXTENSIONS is given, only match these."
21909 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21910 (image-file-name-regexp)
21911 (let ((image-file-name-extensions
21912 (or extensions
21913 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21914 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21915 (concat "\\."
21916 (regexp-opt (nconc (mapcar 'upcase
21917 image-file-name-extensions)
21918 image-file-name-extensions)
21920 "\\'"))))
21922 (defun org-file-image-p (file &optional extensions)
21923 "Return non-nil if FILE is an image."
21924 (save-match-data
21925 (string-match (org-image-file-name-regexp extensions) file)))
21927 (defun org-get-cursor-date (&optional with-time)
21928 "Return the date at cursor in as a time.
21929 This works in the calendar and in the agenda, anywhere else it just
21930 returns the current time.
21931 If WITH-TIME is non-nil, returns the time of the event at point (in
21932 the agenda) or the current time of the day."
21933 (let (date day defd tp tm hod mod)
21934 (when with-time
21935 (setq tp (get-text-property (point) 'time))
21936 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21937 (setq hod (string-to-number (match-string 1 tp))
21938 mod (string-to-number (match-string 2 tp))))
21939 (or tp (setq hod (nth 2 (decode-time (current-time)))
21940 mod (nth 1 (decode-time (current-time))))))
21941 (cond
21942 ((eq major-mode 'calendar-mode)
21943 (setq date (calendar-cursor-to-date)
21944 defd (encode-time 0 (or mod 0) (or hod 0)
21945 (nth 1 date) (nth 0 date) (nth 2 date))))
21946 ((eq major-mode 'org-agenda-mode)
21947 (setq day (get-text-property (point) 'day))
21948 (if day
21949 (setq date (calendar-gregorian-from-absolute day)
21950 defd (encode-time 0 (or mod 0) (or hod 0)
21951 (nth 1 date) (nth 0 date) (nth 2 date))))))
21952 (or defd (current-time))))
21954 (defun org-mark-subtree (&optional up)
21955 "Mark the current subtree.
21956 This puts point at the start of the current subtree, and mark at
21957 the end. If a numeric prefix UP is given, move up into the
21958 hierarchy of headlines by UP levels before marking the subtree."
21959 (interactive "P")
21960 (org-with-limited-levels
21961 (cond ((org-at-heading-p) (beginning-of-line))
21962 ((org-before-first-heading-p) (user-error "Not in a subtree"))
21963 (t (outline-previous-visible-heading 1))))
21964 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21965 (if (org-called-interactively-p 'any)
21966 (call-interactively 'org-mark-element)
21967 (org-mark-element)))
21970 ;;; Indentation
21972 (defun org-indent-line ()
21973 "Indent line depending on context."
21974 (interactive)
21975 (let* ((pos (point))
21976 (itemp (org-at-item-p))
21977 (case-fold-search t)
21978 (org-drawer-regexp (or org-drawer-regexp "\000"))
21979 (inline-task-p (and (featurep 'org-inlinetask)
21980 (org-inlinetask-in-task-p)))
21981 (inline-re (and inline-task-p
21982 (org-inlinetask-outline-regexp)))
21983 column)
21984 (if (and orgstruct-is-++ (eq pos (point)))
21985 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21986 (indent-according-to-mode))
21987 (beginning-of-line 1)
21988 (cond
21989 ;; Headings
21990 ((looking-at org-outline-regexp) (setq column 0))
21991 ;; Footnote definition
21992 ((looking-at org-footnote-definition-re) (setq column 0))
21993 ;; Literal examples
21994 ((looking-at "[ \t]*:\\( \\|$\\)")
21995 (setq column (org-get-indentation))) ; do nothing
21996 ;; Lists
21997 ((ignore-errors (goto-char (org-in-item-p)))
21998 (setq column (if itemp
21999 (org-get-indentation)
22000 (org-list-item-body-column (point))))
22001 (goto-char pos))
22002 ;; Drawers
22003 ((and (looking-at "[ \t]*:END:")
22004 (save-excursion (re-search-backward org-drawer-regexp nil t)))
22005 (save-excursion
22006 (goto-char (1- (match-beginning 1)))
22007 (setq column (current-column))))
22008 ;; Special blocks
22009 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
22010 (save-excursion
22011 (re-search-backward
22012 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
22013 (setq column (org-get-indentation (match-string 0))))
22014 ((and (not (looking-at "[ \t]*#\\+begin_"))
22015 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
22016 (save-excursion
22017 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
22018 (setq column
22019 (cond ((equal (downcase (match-string 1)) "src")
22020 ;; src blocks: let `org-edit-src-exit' handle them
22021 (org-get-indentation))
22022 ((equal (downcase (match-string 1)) "example")
22023 (max (org-get-indentation)
22024 (org-get-indentation (match-string 0))))
22026 (org-get-indentation (match-string 0))))))
22027 ;; This line has nothing special, look at the previous relevant
22028 ;; line to compute indentation
22030 (beginning-of-line 0)
22031 (while (and (not (bobp))
22032 (not (looking-at org-table-line-regexp))
22033 (not (looking-at org-drawer-regexp))
22034 ;; When point started in an inline task, do not move
22035 ;; above task starting line.
22036 (not (and inline-task-p (looking-at inline-re)))
22037 ;; Skip drawers, blocks, empty lines, verbatim,
22038 ;; comments, tables, footnotes definitions, lists,
22039 ;; inline tasks.
22040 (or (and (looking-at "[ \t]*:END:")
22041 (re-search-backward org-drawer-regexp nil t))
22042 (and (looking-at "[ \t]*#\\+end_")
22043 (re-search-backward "[ \t]*#\\+begin_"nil t))
22044 (looking-at "[ \t]*[\n:#|]")
22045 (looking-at org-footnote-definition-re)
22046 (and (not inline-task-p)
22047 (featurep 'org-inlinetask)
22048 (org-inlinetask-in-task-p)
22049 (or (org-inlinetask-goto-beginning) t))))
22050 (beginning-of-line 0))
22051 (cond
22052 ;; There was a list item above.
22053 ((ignore-errors (goto-char (org-in-item-p)))
22054 (goto-char (org-list-get-top-point (org-list-struct)))
22055 (setq column (org-get-indentation)))
22056 ;; There was an heading above.
22057 ((looking-at "\\*+[ \t]+")
22058 (if (not org-adapt-indentation)
22059 (setq column 0)
22060 (goto-char (match-end 0))
22061 (setq column (current-column))))
22062 ;; A drawer had started and is unfinished
22063 ((looking-at org-drawer-regexp)
22064 (goto-char (1- (match-beginning 1)))
22065 (setq column (current-column)))
22066 ;; Else, nothing noticeable found: get indentation and go on.
22067 (t (setq column (org-get-indentation))))))
22068 ;; Now apply indentation and move cursor accordingly
22069 (goto-char pos)
22070 (if (<= (current-column) (current-indentation))
22071 (org-indent-line-to column)
22072 (save-excursion (org-indent-line-to column)))
22073 ;; Special polishing for properties, see `org-property-format'
22074 (setq column (current-column))
22075 (beginning-of-line 1)
22076 (if (looking-at org-property-re)
22077 (replace-match (concat (match-string 4)
22078 (format org-property-format
22079 (match-string 1) (match-string 3)))
22080 t t))
22081 (org-move-to-column column))))
22083 (defun org-indent-drawer ()
22084 "Indent the drawer at point."
22085 (interactive)
22086 (let ((p (point))
22087 (e (and (save-excursion (re-search-forward ":END:" nil t))
22088 (match-end 0)))
22089 (folded
22090 (save-excursion
22091 (end-of-line)
22092 (when (overlays-at (point))
22093 (member 'invisible (overlay-properties
22094 (car (overlays-at (point)))))))))
22095 (when folded (org-cycle))
22096 (indent-for-tab-command)
22097 (while (and (move-beginning-of-line 2) (< (point) e))
22098 (indent-for-tab-command))
22099 (goto-char p)
22100 (when folded (org-cycle)))
22101 (message "Drawer at point indented"))
22103 (defun org-indent-block ()
22104 "Indent the block at point."
22105 (interactive)
22106 (let ((p (point))
22107 (case-fold-search t)
22108 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
22109 (match-end 0)))
22110 (folded
22111 (save-excursion
22112 (end-of-line)
22113 (when (overlays-at (point))
22114 (member 'invisible (overlay-properties
22115 (car (overlays-at (point)))))))))
22116 (when folded (org-cycle))
22117 (indent-for-tab-command)
22118 (while (and (move-beginning-of-line 2) (< (point) e))
22119 (indent-for-tab-command))
22120 (goto-char p)
22121 (when folded (org-cycle)))
22122 (message "Block at point indented"))
22124 (defun org-indent-region (start end)
22125 "Indent region."
22126 (interactive "r")
22127 (save-excursion
22128 (let ((line-end (org-current-line end)))
22129 (goto-char start)
22130 (while (< (org-current-line) line-end)
22131 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
22132 (t (call-interactively 'org-indent-line)))
22133 (move-beginning-of-line 2)))))
22136 ;;; Filling
22138 ;; We use our own fill-paragraph and auto-fill functions.
22140 ;; `org-fill-paragraph' relies on adaptive filling and context
22141 ;; checking. Appropriate `fill-prefix' is computed with
22142 ;; `org-adaptive-fill-function'.
22144 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22145 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22146 ;; `org-adaptive-fill-function' value. Internally,
22147 ;; `org-comment-line-break-function' breaks the line.
22149 ;; `org-setup-filling' installs filling and auto-filling related
22150 ;; variables during `org-mode' initialization.
22152 (defvar org-element-paragraph-separate) ; org-element.el
22153 (defun org-setup-filling ()
22154 (require 'org-element)
22155 ;; Prevent auto-fill from inserting unwanted new items.
22156 (when (boundp 'fill-nobreak-predicate)
22157 (org-set-local
22158 'fill-nobreak-predicate
22159 (org-uniquify
22160 (append fill-nobreak-predicate
22161 '(org-fill-line-break-nobreak-p
22162 org-fill-paragraph-with-timestamp-nobreak-p)))))
22163 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22164 (org-set-local 'paragraph-start paragraph-ending)
22165 (org-set-local 'paragraph-separate paragraph-ending))
22166 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22167 (org-set-local 'auto-fill-inhibit-regexp nil)
22168 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22169 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22170 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22172 (defun org-fill-line-break-nobreak-p ()
22173 "Non-nil when a new line at point would create an Org line break."
22174 (save-excursion
22175 (skip-chars-backward "[ \t]")
22176 (skip-chars-backward "\\\\")
22177 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22179 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22180 "Non-nil when a new line at point would split a timestamp."
22181 (and (org-at-timestamp-p t)
22182 (not (looking-at org-ts-regexp-both))))
22184 (declare-function message-in-body-p "message" ())
22185 (defvar orgtbl-line-start-regexp) ; From org-table.el
22186 (defun org-adaptive-fill-function ()
22187 "Compute a fill prefix for the current line.
22188 Return fill prefix, as a string, or nil if current line isn't
22189 meant to be filled. For convenience, if `adaptive-fill-regexp'
22190 matches in paragraphs or comments, use it."
22191 (catch 'exit
22192 (when (derived-mode-p 'message-mode)
22193 (save-excursion
22194 (beginning-of-line)
22195 (cond ((or (not (message-in-body-p))
22196 (looking-at orgtbl-line-start-regexp))
22197 (throw 'exit nil))
22198 ((looking-at message-cite-prefix-regexp)
22199 (throw 'exit (match-string-no-properties 0)))
22200 ((looking-at org-outline-regexp)
22201 (throw 'exit (make-string (length (match-string 0)) ? ))))))
22202 (org-with-wide-buffer
22203 (let* ((p (line-beginning-position))
22204 (element (save-excursion
22205 (beginning-of-line)
22206 (or (ignore-errors (org-element-at-point))
22207 (user-error "An element cannot be parsed line %d"
22208 (line-number-at-pos (point))))))
22209 (type (org-element-type element))
22210 (post-affiliated (org-element-property :post-affiliated element)))
22211 (unless (and post-affiliated (< p post-affiliated))
22212 (case type
22213 (comment
22214 (save-excursion
22215 (beginning-of-line)
22216 (looking-at "[ \t]*")
22217 (concat (match-string 0) "# ")))
22218 (footnote-definition "")
22219 ((item plain-list)
22220 (make-string (org-list-item-body-column
22221 (or post-affiliated
22222 (org-element-property :begin element)))
22223 ? ))
22224 (paragraph
22225 ;; Fill prefix is usually the same as the current line,
22226 ;; unless the paragraph is at the beginning of an item.
22227 (let ((parent (org-element-property :parent element)))
22228 (save-excursion
22229 (beginning-of-line)
22230 (cond ((eq (org-element-type parent) 'item)
22231 (make-string (org-list-item-body-column
22232 (org-element-property :begin parent))
22233 ? ))
22234 ((and adaptive-fill-regexp
22235 ;; Locally disable
22236 ;; `adaptive-fill-function' to let
22237 ;; `fill-context-prefix' handle
22238 ;; `adaptive-fill-regexp' variable.
22239 (let (adaptive-fill-function)
22240 (fill-context-prefix
22241 post-affiliated
22242 (org-element-property :end element)))))
22243 ((looking-at "[ \t]+") (match-string 0))
22244 (t "")))))
22245 (comment-block
22246 ;; Only fill contents if P is within block boundaries.
22247 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22248 (forward-line)
22249 (point)))
22250 (cend (save-excursion
22251 (goto-char (org-element-property :end element))
22252 (skip-chars-backward " \r\t\n")
22253 (line-beginning-position))))
22254 (when (and (>= p cbeg) (< p cend))
22255 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22256 (match-string 0)
22257 ""))))))))))
22259 (declare-function message-goto-body "message" ())
22260 (defvar message-cite-prefix-regexp) ; From message.el
22261 (defun org-fill-paragraph (&optional justify)
22262 "Fill element at point, when applicable.
22264 This function only applies to comment blocks, comments, example
22265 blocks and paragraphs. Also, as a special case, re-align table
22266 when point is at one.
22268 If JUSTIFY is non-nil (interactively, with prefix argument),
22269 justify as well. If `sentence-end-double-space' is non-nil, then
22270 period followed by one space does not end a sentence, so don't
22271 break a line there. The variable `fill-column' controls the
22272 width for filling.
22274 For convenience, when point is at a plain list, an item or
22275 a footnote definition, try to fill the first paragraph within."
22276 (interactive)
22277 (if (and (derived-mode-p 'message-mode)
22278 (or (not (message-in-body-p))
22279 (save-excursion (move-beginning-of-line 1)
22280 (looking-at message-cite-prefix-regexp))))
22281 ;; First ensure filling is correct in message-mode.
22282 (let ((fill-paragraph-function
22283 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22284 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22285 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22286 (paragraph-separate
22287 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22288 (fill-paragraph nil))
22289 (with-syntax-table org-mode-transpose-word-syntax-table
22290 ;; Move to end of line in order to get the first paragraph
22291 ;; within a plain list or a footnote definition.
22292 (let ((element (save-excursion
22293 (end-of-line)
22294 (or (ignore-errors (org-element-at-point))
22295 (user-error "An element cannot be parsed line %d"
22296 (line-number-at-pos (point)))))))
22297 ;; First check if point is in a blank line at the beginning of
22298 ;; the buffer. In that case, ignore filling.
22299 (case (org-element-type element)
22300 ;; Use major mode filling function is src blocks.
22301 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22302 ;; Align Org tables, leave table.el tables as-is.
22303 (table-row (org-table-align) t)
22304 (table
22305 (when (eq (org-element-property :type element) 'org)
22306 (save-excursion
22307 (goto-char (org-element-property :post-affiliated element))
22308 (org-table-align)))
22310 (paragraph
22311 ;; Paragraphs may contain `line-break' type objects.
22312 (let ((beg (max (point-min)
22313 (org-element-property :contents-begin element)))
22314 (end (min (point-max)
22315 (org-element-property :contents-end element))))
22316 ;; Do nothing if point is at an affiliated keyword.
22317 (if (< (line-end-position) beg) t
22318 (when (derived-mode-p 'message-mode)
22319 ;; In `message-mode', do not fill following citation
22320 ;; in current paragraph nor text before message body.
22321 (let ((body-start (save-excursion (message-goto-body))))
22322 (when body-start (setq beg (max body-start beg))))
22323 (when (save-excursion
22324 (re-search-forward
22325 (concat "^" message-cite-prefix-regexp) end t))
22326 (setq end (match-beginning 0))))
22327 ;; Fill paragraph, taking line breaks into account.
22328 ;; For that, slice the paragraph using line breaks as
22329 ;; separators, and fill the parts in reverse order to
22330 ;; avoid messing with markers.
22331 (save-excursion
22332 (goto-char end)
22333 (mapc
22334 (lambda (pos)
22335 (fill-region-as-paragraph pos (point) justify)
22336 (goto-char pos))
22337 ;; Find the list of ending positions for line breaks
22338 ;; in the current paragraph. Add paragraph
22339 ;; beginning to include first slice.
22340 (nreverse
22341 (cons beg
22342 (org-element-map
22343 (org-element--parse-objects
22344 beg end nil (org-element-restriction 'paragraph))
22345 'line-break
22346 (lambda (lb) (org-element-property :end lb)))))))
22347 t)))
22348 ;; Contents of `comment-block' type elements should be
22349 ;; filled as plain text, but only if point is within block
22350 ;; markers.
22351 (comment-block
22352 (let* ((case-fold-search t)
22353 (beg (save-excursion
22354 (goto-char (org-element-property :begin element))
22355 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22356 (forward-line)
22357 (point)))
22358 (end (save-excursion
22359 (goto-char (org-element-property :end element))
22360 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22361 (line-beginning-position))))
22362 (if (or (< (point) beg) (> (point) end)) t
22363 (fill-region-as-paragraph
22364 (save-excursion (end-of-line)
22365 (re-search-backward "^[ \t]*$" beg 'move)
22366 (line-beginning-position))
22367 (save-excursion (beginning-of-line)
22368 (re-search-forward "^[ \t]*$" end 'move)
22369 (line-beginning-position))
22370 justify))))
22371 ;; Fill comments.
22372 (comment
22373 (let ((begin (org-element-property :post-affiliated element))
22374 (end (org-element-property :end element)))
22375 (when (and (>= (point) begin) (<= (point) end))
22376 (let ((begin (save-excursion
22377 (end-of-line)
22378 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22379 (progn (forward-line) (point))
22380 begin)))
22381 (end (save-excursion
22382 (end-of-line)
22383 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22384 (1- (line-beginning-position))
22385 (skip-chars-backward " \r\t\n")
22386 (line-end-position)))))
22387 ;; Do not fill comments when at a blank line.
22388 (when (> end begin)
22389 (let ((fill-prefix
22390 (save-excursion
22391 (beginning-of-line)
22392 (looking-at "[ \t]*#")
22393 (let ((comment-prefix (match-string 0)))
22394 (goto-char (match-end 0))
22395 (if (looking-at adaptive-fill-regexp)
22396 (concat comment-prefix (match-string 0))
22397 (concat comment-prefix " "))))))
22398 (save-excursion
22399 (fill-region-as-paragraph begin end justify))))))
22401 ;; Ignore every other element.
22402 (otherwise t))))))
22404 (defun org-auto-fill-function ()
22405 "Auto-fill function."
22406 ;; Check if auto-filling is meaningful.
22407 (let ((fc (current-fill-column)))
22408 (when (and fc (> (current-column) fc))
22409 (let* ((fill-prefix (org-adaptive-fill-function))
22410 ;; Enforce empty fill prefix, if required. Otherwise, it
22411 ;; will be computed again.
22412 (adaptive-fill-mode (not (equal fill-prefix ""))))
22413 (when fill-prefix (do-auto-fill))))))
22415 (defun org-comment-line-break-function (&optional soft)
22416 "Break line at point and indent, continuing comment if within one.
22417 The inserted newline is marked hard if variable
22418 `use-hard-newlines' is true, unless optional argument SOFT is
22419 non-nil."
22420 (if soft (insert-and-inherit ?\n) (newline 1))
22421 (save-excursion (forward-char -1) (delete-horizontal-space))
22422 (delete-horizontal-space)
22423 (indent-to-left-margin)
22424 (insert-before-markers-and-inherit fill-prefix))
22427 ;;; Comments
22429 ;; Org comments syntax is quite complex. It requires the entire line
22430 ;; to be just a comment. Also, even with the right syntax at the
22431 ;; beginning of line, some some elements (i.e. verse-block or
22432 ;; example-block) don't accept comments. Usual Emacs comment commands
22433 ;; cannot cope with those requirements. Therefore, Org replaces them.
22435 ;; Org still relies on `comment-dwim', but cannot trust
22436 ;; `comment-only-p'. So, `comment-region-function' and
22437 ;; `uncomment-region-function' both point
22438 ;; to`org-comment-or-uncomment-region'. Eventually,
22439 ;; `org-insert-comment' takes care of insertion of comments at the
22440 ;; beginning of line.
22442 ;; `org-setup-comments-handling' install comments related variables
22443 ;; during `org-mode' initialization.
22445 (defun org-setup-comments-handling ()
22446 (interactive)
22447 (org-set-local 'comment-use-syntax nil)
22448 (org-set-local 'comment-start "# ")
22449 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22450 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22451 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22452 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22454 (defun org-insert-comment ()
22455 "Insert an empty comment above current line.
22456 If the line is empty, insert comment at its beginning."
22457 (beginning-of-line)
22458 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
22459 (org-indent-line)
22460 (insert "# "))
22462 (defvar comment-empty-lines) ; From newcomment.el.
22463 (defun org-comment-or-uncomment-region (beg end &rest ignore)
22464 "Comment or uncomment each non-blank line in the region.
22465 Uncomment each non-blank line between BEG and END if it only
22466 contains commented lines. Otherwise, comment them."
22467 (save-restriction
22468 ;; Restrict region
22469 (narrow-to-region (save-excursion (goto-char beg)
22470 (skip-chars-forward " \r\t\n" end)
22471 (line-beginning-position))
22472 (save-excursion (goto-char end)
22473 (skip-chars-backward " \r\t\n" beg)
22474 (line-end-position)))
22475 (let ((uncommentp
22476 ;; UNCOMMENTP is non-nil when every non blank line between
22477 ;; BEG and END is a comment.
22478 (save-excursion
22479 (goto-char (point-min))
22480 (while (and (not (eobp))
22481 (let ((element (org-element-at-point)))
22482 (and (eq (org-element-type element) 'comment)
22483 (goto-char (min (point-max)
22484 (org-element-property
22485 :end element)))))))
22486 (eobp))))
22487 (if uncommentp
22488 ;; Only blank lines and comments in region: uncomment it.
22489 (save-excursion
22490 (goto-char (point-min))
22491 (while (not (eobp))
22492 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22493 (replace-match "" nil nil nil 1))
22494 (forward-line)))
22495 ;; Comment each line in region.
22496 (let ((min-indent (point-max)))
22497 ;; First find the minimum indentation across all lines.
22498 (save-excursion
22499 (goto-char (point-min))
22500 (while (and (not (eobp)) (not (zerop min-indent)))
22501 (unless (looking-at "[ \t]*$")
22502 (setq min-indent (min min-indent (current-indentation))))
22503 (forward-line)))
22504 ;; Then loop over all lines.
22505 (save-excursion
22506 (goto-char (point-min))
22507 (while (not (eobp))
22508 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22509 ;; Don't get fooled by invisible text (e.g. link path)
22510 ;; when moving to column MIN-INDENT.
22511 (let ((buffer-invisibility-spec nil))
22512 (org-move-to-column min-indent t))
22513 (insert comment-start))
22514 (forward-line))))))))
22517 ;;; Planning
22519 ;; This section contains tools to operate on timestamp objects, as
22520 ;; returned by, e.g. `org-element-context'.
22522 (defun org-timestamp-has-time-p (timestamp)
22523 "Non-nil when TIMESTAMP has a time specified."
22524 (org-element-property :hour-start timestamp))
22526 (defun org-timestamp-format (timestamp format &optional end utc)
22527 "Format a TIMESTAMP element into a string.
22529 FORMAT is a format specifier to be passed to
22530 `format-time-string'.
22532 When optional argument END is non-nil, use end of date-range or
22533 time-range, if possible.
22535 When optional argument UTC is non-nil, time will be expressed as
22536 Universal Time."
22537 (format-time-string
22538 format
22539 (apply 'encode-time
22540 (cons 0
22541 (mapcar
22542 (lambda (prop) (or (org-element-property prop timestamp) 0))
22543 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22544 '(:minute-start :hour-start :day-start :month-start
22545 :year-start)))))
22546 utc))
22548 (defun org-timestamp-split-range (timestamp &optional end)
22549 "Extract a timestamp object from a date or time range.
22551 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22552 the end of the range. Otherwise, extract its start.
22554 Return a new timestamp object sharing the same parent as
22555 TIMESTAMP."
22556 (let ((type (org-element-property :type timestamp)))
22557 (if (memq type '(active inactive diary)) timestamp
22558 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22559 ;; Set new type.
22560 (org-element-put-property
22561 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22562 ;; Copy start properties over end properties if END is
22563 ;; non-nil. Otherwise, copy end properties over `start' ones.
22564 (let ((p-alist '((:minute-start . :minute-end)
22565 (:hour-start . :hour-end)
22566 (:day-start . :day-end)
22567 (:month-start . :month-end)
22568 (:year-start . :year-end))))
22569 (dolist (p-cell p-alist)
22570 (org-element-put-property
22571 split-ts
22572 (funcall (if end 'car 'cdr) p-cell)
22573 (org-element-property
22574 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22575 ;; Eventually refresh `:raw-value'.
22576 (org-element-put-property split-ts :raw-value nil)
22577 (org-element-put-property
22578 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22580 (defun org-timestamp-translate (timestamp &optional boundary)
22581 "Apply `org-translate-time' on a TIMESTAMP object.
22582 When optional argument BOUNDARY is non-nil, it is either the
22583 symbol `start' or `end'. In this case, only translate the
22584 starting or ending part of TIMESTAMP if it is a date or time
22585 range. Otherwise, translate both parts."
22586 (if (and (not boundary)
22587 (memq (org-element-property :type timestamp)
22588 '(active-range inactive-range)))
22589 (concat
22590 (org-translate-time
22591 (org-element-property :raw-value
22592 (org-timestamp-split-range timestamp)))
22593 "--"
22594 (org-translate-time
22595 (org-element-property :raw-value
22596 (org-timestamp-split-range timestamp t))))
22597 (org-translate-time
22598 (org-element-property
22599 :raw-value
22600 (if (not boundary) timestamp
22601 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22605 ;;; Other stuff.
22607 (defun org-toggle-fixed-width-section (arg)
22608 "Toggle the fixed-width export.
22609 If there is no active region, the QUOTE keyword at the current headline is
22610 inserted or removed. When present, it causes the text between this headline
22611 and the next to be exported as fixed-width text, and unmodified.
22612 If there is an active region, this command adds or removes a colon as the
22613 first character of this line. If the first character of a line is a colon,
22614 this line is also exported in fixed-width font."
22615 (interactive "P")
22616 (let* ((cc 0)
22617 (regionp (org-region-active-p))
22618 (beg (if regionp (region-beginning) (point)))
22619 (end (if regionp (region-end)))
22620 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22621 (case-fold-search nil)
22622 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22623 off)
22624 (if regionp
22625 (save-excursion
22626 (goto-char beg)
22627 (setq cc (current-column))
22628 (beginning-of-line 1)
22629 (setq off (looking-at re))
22630 (while (> nlines 0)
22631 (setq nlines (1- nlines))
22632 (beginning-of-line 1)
22633 (cond
22634 (arg
22635 (org-move-to-column cc t)
22636 (insert ": \n")
22637 (forward-line -1))
22638 ((and off (looking-at re))
22639 (replace-match "" t t nil 1))
22640 ((not off) (org-move-to-column cc t) (insert ": ")))
22641 (forward-line 1)))
22642 (save-excursion
22643 (org-back-to-heading)
22644 (cond
22645 ((looking-at (format org-heading-keyword-regexp-format
22646 org-quote-string))
22647 (goto-char (match-end 1))
22648 (looking-at (concat " +" org-quote-string))
22649 (replace-match "" t t)
22650 (when (eolp) (insert " ")))
22651 ((looking-at org-outline-regexp)
22652 (goto-char (match-end 0))
22653 (insert org-quote-string " ")))))))
22655 (defun org-reftex-citation ()
22656 "Use reftex-citation to insert a citation into the buffer.
22657 This looks for a line like
22659 #+BIBLIOGRAPHY: foo plain option:-d
22661 and derives from it that foo.bib is the bibliography file relevant
22662 for this document. It then installs the necessary environment for RefTeX
22663 to work in this buffer and calls `reftex-citation' to insert a citation
22664 into the buffer.
22666 Export of such citations to both LaTeX and HTML is handled by the contributed
22667 package ox-bibtex by Taru Karttunen."
22668 (interactive)
22669 (let ((reftex-docstruct-symbol 'rds)
22670 (reftex-cite-format "\\cite{%l}")
22671 rds bib)
22672 (save-excursion
22673 (save-restriction
22674 (widen)
22675 (let ((case-fold-search t)
22676 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22677 (if (not (save-excursion
22678 (or (re-search-forward re nil t)
22679 (re-search-backward re nil t))))
22680 (error "No bibliography defined in file")
22681 (setq bib (concat (match-string 1) ".bib")
22682 rds (list (list 'bib bib)))))))
22683 (call-interactively 'reftex-citation)))
22685 ;;;; Functions extending outline functionality
22687 (defun org-beginning-of-line (&optional arg)
22688 "Go to the beginning of the current line. If that is invisible, continue
22689 to a visible line beginning. This makes the function of C-a more intuitive.
22690 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22691 first attempt, and only move to after the tags when the cursor is already
22692 beyond the end of the headline."
22693 (interactive "P")
22694 (let ((pos (point))
22695 (special (if (consp org-special-ctrl-a/e)
22696 (car org-special-ctrl-a/e)
22697 org-special-ctrl-a/e))
22698 refpos)
22699 (if (org-bound-and-true-p visual-line-mode)
22700 (beginning-of-visual-line 1)
22701 (beginning-of-line 1))
22702 (if (and arg (fboundp 'move-beginning-of-line))
22703 (call-interactively 'move-beginning-of-line)
22704 (if (bobp)
22706 (backward-char 1)
22707 (if (org-truely-invisible-p)
22708 (while (and (not (bobp)) (org-truely-invisible-p))
22709 (backward-char 1)
22710 (beginning-of-line 1))
22711 (forward-char 1))))
22712 (when special
22713 (cond
22714 ((and (looking-at org-complex-heading-regexp)
22715 (= (char-after (match-end 1)) ?\ ))
22716 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22717 (point-at-eol)))
22718 (goto-char
22719 (if (eq special t)
22720 (cond ((> pos refpos) refpos)
22721 ((= pos (point)) refpos)
22722 (t (point)))
22723 (cond ((> pos (point)) (point))
22724 ((not (eq last-command this-command)) (point))
22725 (t refpos)))))
22726 ((org-at-item-p)
22727 ;; Being at an item and not looking at an the item means point
22728 ;; was previously moved to beginning of a visual line, which
22729 ;; doesn't contain the item. Therefore, do nothing special,
22730 ;; just stay here.
22731 (when (looking-at org-list-full-item-re)
22732 ;; Set special position at first white space character after
22733 ;; bullet, and check-box, if any.
22734 (let ((after-bullet
22735 (let ((box (match-end 3)))
22736 (if (not box) (match-end 1)
22737 (let ((after (char-after box)))
22738 (if (and after (= after ? )) (1+ box) box))))))
22739 ;; Special case: Move point to special position when
22740 ;; currently after it or at beginning of line.
22741 (if (eq special t)
22742 (when (or (> pos after-bullet) (= (point) pos))
22743 (goto-char after-bullet))
22744 ;; Reversed case: Move point to special position when
22745 ;; point was already at beginning of line and command is
22746 ;; repeated.
22747 (when (and (= (point) pos) (eq last-command this-command))
22748 (goto-char after-bullet))))))))
22749 (org-no-warnings
22750 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22751 (setq disable-point-adjustment
22752 (or (not (invisible-p (point)))
22753 (not (invisible-p (max (point-min) (1- (point))))))))
22755 (defun org-end-of-line (&optional arg)
22756 "Go to the end of the line.
22757 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22758 tags on the first attempt, and only move to after the tags when
22759 the cursor is already beyond the end of the headline."
22760 (interactive "P")
22761 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22762 org-special-ctrl-a/e))
22763 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22764 'end-of-visual-line)
22765 ((fboundp 'move-end-of-line) 'move-end-of-line)
22766 (t 'end-of-line))))
22767 (if (or (not special) arg) (call-interactively move-fun)
22768 (let* ((element (save-excursion (beginning-of-line)
22769 (org-element-at-point)))
22770 (type (org-element-type element)))
22771 (cond
22772 ((memq type '(headline inlinetask))
22773 (let ((pos (point)))
22774 (beginning-of-line 1)
22775 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22776 (if (eq special t)
22777 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22778 (goto-char (match-beginning 1))
22779 (goto-char (match-end 0)))
22780 (if (or (< pos (match-end 0))
22781 (not (eq this-command last-command)))
22782 (goto-char (match-end 0))
22783 (goto-char (match-beginning 1))))
22784 (call-interactively move-fun))))
22785 ((org-element-property :hiddenp element)
22786 ;; If element is hidden, `move-end-of-line' would put point
22787 ;; after it. Use `end-of-line' to stay on current line.
22788 (call-interactively 'end-of-line))
22789 (t (call-interactively move-fun)))))
22790 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22791 (setq disable-point-adjustment
22792 (or (not (invisible-p (point)))
22793 (not (invisible-p (max (point-min) (1- (point))))))))
22795 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22796 (define-key org-mode-map "\C-e" 'org-end-of-line)
22798 (defun org-backward-sentence (&optional arg)
22799 "Go to beginning of sentence, or beginning of table field.
22800 This will call `backward-sentence' or `org-table-beginning-of-field',
22801 depending on context."
22802 (interactive "P")
22803 (cond
22804 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22805 (t (call-interactively 'backward-sentence))))
22807 (defun org-forward-sentence (&optional arg)
22808 "Go to end of sentence, or end of table field.
22809 This will call `forward-sentence' or `org-table-end-of-field',
22810 depending on context."
22811 (interactive "P")
22812 (cond
22813 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22814 (t (call-interactively 'forward-sentence))))
22816 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22817 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22819 (defun org-kill-line (&optional arg)
22820 "Kill line, to tags or end of line."
22821 (interactive "P")
22822 (cond
22823 ((or (not org-special-ctrl-k)
22824 (bolp)
22825 (not (org-at-heading-p)))
22826 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22827 org-ctrl-k-protect-subtree)
22828 (if (or (eq org-ctrl-k-protect-subtree 'error)
22829 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22830 (user-error "C-k aborted as it would kill a hidden subtree")))
22831 (call-interactively
22832 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22833 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22834 (kill-region (point) (match-beginning 1))
22835 (org-set-tags nil t))
22836 (t (kill-region (point) (point-at-eol)))))
22838 (define-key org-mode-map "\C-k" 'org-kill-line)
22840 (defun org-yank (&optional arg)
22841 "Yank. If the kill is a subtree, treat it specially.
22842 This command will look at the current kill and check if is a single
22843 subtree, or a series of subtrees[1]. If it passes the test, and if the
22844 cursor is at the beginning of a line or after the stars of a currently
22845 empty headline, then the yank is handled specially. How exactly depends
22846 on the value of the following variables, both set by default.
22848 org-yank-folded-subtrees
22849 When set, the subtree(s) will be folded after insertion, but only
22850 if doing so would now swallow text after the yanked text.
22852 org-yank-adjusted-subtrees
22853 When set, the subtree will be promoted or demoted in order to
22854 fit into the local outline tree structure, which means that the level
22855 will be adjusted so that it becomes the smaller one of the two
22856 *visible* surrounding headings.
22858 Any prefix to this command will cause `yank' to be called directly with
22859 no special treatment. In particular, a simple \\[universal-argument] prefix \
22860 will just
22861 plainly yank the text as it is.
22863 \[1] The test checks if the first non-white line is a heading
22864 and if there are no other headings with fewer stars."
22865 (interactive "P")
22866 (org-yank-generic 'yank arg))
22868 (defun org-yank-generic (command arg)
22869 "Perform some yank-like command.
22871 This function implements the behavior described in the `org-yank'
22872 documentation. However, it has been generalized to work for any
22873 interactive command with similar behavior."
22875 ;; pretend to be command COMMAND
22876 (setq this-command command)
22878 (if arg
22879 (call-interactively command)
22881 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22882 (and (org-kill-is-subtree-p)
22883 (or (bolp)
22884 (and (looking-at "[ \t]*$")
22885 (string-match
22886 "\\`\\*+\\'"
22887 (buffer-substring (point-at-bol) (point)))))))
22888 swallowp)
22889 (cond
22890 ((and subtreep org-yank-folded-subtrees)
22891 (let ((beg (point))
22892 end)
22893 (if (and subtreep org-yank-adjusted-subtrees)
22894 (org-paste-subtree nil nil 'for-yank)
22895 (call-interactively command))
22897 (setq end (point))
22898 (goto-char beg)
22899 (when (and (bolp) subtreep
22900 (not (setq swallowp
22901 (org-yank-folding-would-swallow-text beg end))))
22902 (org-with-limited-levels
22903 (or (looking-at org-outline-regexp)
22904 (re-search-forward org-outline-regexp-bol end t))
22905 (while (and (< (point) end) (looking-at org-outline-regexp))
22906 (hide-subtree)
22907 (org-cycle-show-empty-lines 'folded)
22908 (condition-case nil
22909 (outline-forward-same-level 1)
22910 (error (goto-char end))))))
22911 (when swallowp
22912 (message
22913 "Inserted text not folded because that would swallow text"))
22915 (goto-char end)
22916 (skip-chars-forward " \t\n\r")
22917 (beginning-of-line 1)
22918 (push-mark beg 'nomsg)))
22919 ((and subtreep org-yank-adjusted-subtrees)
22920 (let ((beg (point-at-bol)))
22921 (org-paste-subtree nil nil 'for-yank)
22922 (push-mark beg 'nomsg)))
22924 (call-interactively command))))))
22926 (defun org-yank-folding-would-swallow-text (beg end)
22927 "Would hide-subtree at BEG swallow any text after END?"
22928 (let (level)
22929 (org-with-limited-levels
22930 (save-excursion
22931 (goto-char beg)
22932 (when (or (looking-at org-outline-regexp)
22933 (re-search-forward org-outline-regexp-bol end t))
22934 (setq level (org-outline-level)))
22935 (goto-char end)
22936 (skip-chars-forward " \t\r\n\v\f")
22937 (if (or (eobp)
22938 (and (bolp) (looking-at org-outline-regexp)
22939 (<= (org-outline-level) level)))
22940 nil ; Nothing would be swallowed
22941 t))))) ; something would swallow
22943 (define-key org-mode-map "\C-y" 'org-yank)
22945 (defun org-truely-invisible-p ()
22946 "Check if point is at a character currently not visible.
22947 This version does not only check the character property, but also
22948 `visible-mode'."
22949 ;; Early versions of noutline don't have `outline-invisible-p'.
22950 (if (org-bound-and-true-p visible-mode)
22952 (outline-invisible-p)))
22954 (defun org-invisible-p2 ()
22955 "Check if point is at a character currently not visible."
22956 (save-excursion
22957 (if (and (eolp) (not (bobp))) (backward-char 1))
22958 ;; Early versions of noutline don't have `outline-invisible-p'.
22959 (outline-invisible-p)))
22961 (defun org-back-to-heading (&optional invisible-ok)
22962 "Call `outline-back-to-heading', but provide a better error message."
22963 (condition-case nil
22964 (outline-back-to-heading invisible-ok)
22965 (error (error "Before first headline at position %d in buffer %s"
22966 (point) (current-buffer)))))
22968 (defun org-before-first-heading-p ()
22969 "Before first heading?"
22970 (save-excursion
22971 (end-of-line)
22972 (null (re-search-backward org-outline-regexp-bol nil t))))
22974 (defun org-at-heading-p (&optional ignored)
22975 (outline-on-heading-p t))
22976 ;; Compatibility alias with Org versions < 7.8.03
22977 (defalias 'org-on-heading-p 'org-at-heading-p)
22979 (defun org-at-comment-p nil
22980 "Is cursor in a line starting with a # character?"
22981 (save-excursion
22982 (beginning-of-line)
22983 (looking-at "^#")))
22985 (defun org-at-drawer-p nil
22986 "Is cursor at a drawer keyword?"
22987 (save-excursion
22988 (move-beginning-of-line 1)
22989 (looking-at org-drawer-regexp)))
22991 (defun org-at-block-p nil
22992 "Is cursor at a block keyword?"
22993 (save-excursion
22994 (move-beginning-of-line 1)
22995 (looking-at org-block-regexp)))
22997 (defun org-point-at-end-of-empty-headline ()
22998 "If point is at the end of an empty headline, return t, else nil.
22999 If the heading only contains a TODO keyword, it is still still considered
23000 empty."
23001 (and (looking-at "[ \t]*$")
23002 (when org-todo-line-regexp
23003 (save-excursion
23004 (beginning-of-line 1)
23005 (let ((case-fold-search nil))
23006 (looking-at org-todo-line-regexp)
23007 (string= (match-string 3) ""))))))
23009 (defun org-at-heading-or-item-p ()
23010 (or (org-at-heading-p) (org-at-item-p)))
23012 (defun org-at-target-p ()
23013 (or (org-in-regexp org-radio-target-regexp)
23014 (org-in-regexp org-target-regexp)))
23015 ;; Compatibility alias with Org versions < 7.8.03
23016 (defalias 'org-on-target-p 'org-at-target-p)
23018 (defun org-up-heading-all (arg)
23019 "Move to the heading line of which the present line is a subheading.
23020 This function considers both visible and invisible heading lines.
23021 With argument, move up ARG levels."
23022 (if (fboundp 'outline-up-heading-all)
23023 (outline-up-heading-all arg) ; emacs 21 version of outline.el
23024 (outline-up-heading arg t))) ; emacs 22 version of outline.el
23026 (defun org-up-heading-safe ()
23027 "Move to the heading line of which the present line is a subheading.
23028 This version will not throw an error. It will return the level of the
23029 headline found, or nil if no higher level is found.
23031 Also, this function will be a lot faster than `outline-up-heading',
23032 because it relies on stars being the outline starters. This can really
23033 make a significant difference in outlines with very many siblings."
23034 (let (start-level re)
23035 (org-back-to-heading t)
23036 (setq start-level (funcall outline-level))
23037 (if (equal start-level 1)
23039 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
23040 (if (re-search-backward re nil t)
23041 (funcall outline-level)))))
23043 (defun org-first-sibling-p ()
23044 "Is this heading the first child of its parents?"
23045 (interactive)
23046 (let ((re org-outline-regexp-bol)
23047 level l)
23048 (unless (org-at-heading-p t)
23049 (user-error "Not at a heading"))
23050 (setq level (funcall outline-level))
23051 (save-excursion
23052 (if (not (re-search-backward re nil t))
23054 (setq l (funcall outline-level))
23055 (< l level)))))
23057 (defun org-goto-sibling (&optional previous)
23058 "Goto the next sibling, even if it is invisible.
23059 When PREVIOUS is set, go to the previous sibling instead. Returns t
23060 when a sibling was found. When none is found, return nil and don't
23061 move point."
23062 (let ((fun (if previous 're-search-backward 're-search-forward))
23063 (pos (point))
23064 (re org-outline-regexp-bol)
23065 level l)
23066 (when (condition-case nil (org-back-to-heading t) (error nil))
23067 (setq level (funcall outline-level))
23068 (catch 'exit
23069 (or previous (forward-char 1))
23070 (while (funcall fun re nil t)
23071 (setq l (funcall outline-level))
23072 (when (< l level) (goto-char pos) (throw 'exit nil))
23073 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23074 (goto-char pos)
23075 nil))))
23077 (defun org-show-siblings ()
23078 "Show all siblings of the current headline."
23079 (save-excursion
23080 (while (org-goto-sibling) (org-flag-heading nil)))
23081 (save-excursion
23082 (while (org-goto-sibling 'previous)
23083 (org-flag-heading nil))))
23085 (defun org-goto-first-child ()
23086 "Goto the first child, even if it is invisible.
23087 Return t when a child was found. Otherwise don't move point and
23088 return nil."
23089 (let (level (pos (point)) (re org-outline-regexp-bol))
23090 (when (condition-case nil (org-back-to-heading t) (error nil))
23091 (setq level (outline-level))
23092 (forward-char 1)
23093 (if (and (re-search-forward re nil t) (> (outline-level) level))
23094 (progn (goto-char (match-beginning 0)) t)
23095 (goto-char pos) nil))))
23097 (defun org-show-hidden-entry ()
23098 "Show an entry where even the heading is hidden."
23099 (save-excursion
23100 (org-show-entry)))
23102 (defun org-flag-heading (flag &optional entry)
23103 "Flag the current heading. FLAG non-nil means make invisible.
23104 When ENTRY is non-nil, show the entire entry."
23105 (save-excursion
23106 (org-back-to-heading t)
23107 ;; Check if we should show the entire entry
23108 (if entry
23109 (progn
23110 (org-show-entry)
23111 (save-excursion
23112 (and (outline-next-heading)
23113 (org-flag-heading nil))))
23114 (outline-flag-region (max (point-min) (1- (point)))
23115 (save-excursion (outline-end-of-heading) (point))
23116 flag))))
23118 (defun org-get-next-sibling ()
23119 "Move to next heading of the same level, and return point.
23120 If there is no such heading, return nil.
23121 This is like outline-next-sibling, but invisible headings are ok."
23122 (let ((level (funcall outline-level)))
23123 (outline-next-heading)
23124 (while (and (not (eobp)) (> (funcall outline-level) level))
23125 (outline-next-heading))
23126 (if (or (eobp) (< (funcall outline-level) level))
23128 (point))))
23130 (defun org-get-last-sibling ()
23131 "Move to previous heading of the same level, and return point.
23132 If there is no such heading, return nil."
23133 (let ((opoint (point))
23134 (level (funcall outline-level)))
23135 (outline-previous-heading)
23136 (when (and (/= (point) opoint) (outline-on-heading-p t))
23137 (while (and (> (funcall outline-level) level)
23138 (not (bobp)))
23139 (outline-previous-heading))
23140 (if (< (funcall outline-level) level)
23142 (point)))))
23144 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23145 "Goto to the end of a subtree."
23146 ;; This contains an exact copy of the original function, but it uses
23147 ;; `org-back-to-heading', to make it work also in invisible
23148 ;; trees. And is uses an invisible-ok argument.
23149 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23150 ;; Furthermore, when used inside Org, finding the end of a large subtree
23151 ;; with many children and grandchildren etc, this can be much faster
23152 ;; than the outline version.
23153 (org-back-to-heading invisible-ok)
23154 (let ((first t)
23155 (level (funcall outline-level)))
23156 (if (and (derived-mode-p 'org-mode) (< level 1000))
23157 ;; A true heading (not a plain list item), in Org-mode
23158 ;; This means we can easily find the end by looking
23159 ;; only for the right number of stars. Using a regexp to do
23160 ;; this is so much faster than using a Lisp loop.
23161 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23162 (forward-char 1)
23163 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23164 ;; something else, do it the slow way
23165 (while (and (not (eobp))
23166 (or first (> (funcall outline-level) level)))
23167 (setq first nil)
23168 (outline-next-heading)))
23169 (unless to-heading
23170 (if (memq (preceding-char) '(?\n ?\^M))
23171 (progn
23172 ;; Go to end of line before heading
23173 (forward-char -1)
23174 (if (memq (preceding-char) '(?\n ?\^M))
23175 ;; leave blank line before heading
23176 (forward-char -1))))))
23177 (point))
23179 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
23180 "Use Org version in org-mode, for dramatic speed-up."
23181 (if (derived-mode-p 'org-mode)
23182 (progn
23183 (org-end-of-subtree nil t)
23184 (unless (eobp) (backward-char 1)))
23185 ad-do-it))
23187 (defun org-end-of-meta-data-and-drawers ()
23188 "Jump to the first text after meta data and drawers in the current entry.
23189 This will move over empty lines, lines with planning time stamps,
23190 clocking lines, and drawers."
23191 (org-back-to-heading t)
23192 (let ((end (save-excursion (outline-next-heading) (point)))
23193 (re (concat "\\(" org-drawer-regexp "\\)"
23194 "\\|" "[ \t]*" org-keyword-time-regexp)))
23195 (forward-line 1)
23196 (while (re-search-forward re end t)
23197 (if (not (match-end 1))
23198 ;; empty or planning line
23199 (forward-line 1)
23200 ;; a drawer, find the end
23201 (re-search-forward "^[ \t]*:END:" end 'move)
23202 (forward-line 1)))
23203 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23204 (point)))
23206 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23207 "Move forward to the ARG'th subheading at same level as this one.
23208 Stop at the first and last subheadings of a superior heading.
23209 Normally this only looks at visible headings, but when INVISIBLE-OK is
23210 non-nil it will also look at invisible ones."
23211 (interactive "p")
23212 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23213 (if (and arg (< arg 0))
23214 (goto-char (point-min))
23215 (outline-next-heading))
23216 (org-at-heading-p)
23217 (let ((level (- (match-end 0) (match-beginning 0) 1))
23218 (f (if (and arg (< arg 0))
23219 're-search-backward
23220 're-search-forward))
23221 (count (if arg (abs arg) 1))
23222 (result (point)))
23223 (while (and (prog1 (> count 0)
23224 (forward-char (if (and arg (< arg 0)) -1 1)))
23225 (funcall f org-outline-regexp-bol nil 'move))
23226 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23227 (cond ((< l level) (setq count 0))
23228 ((and (= l level)
23229 (or invisible-ok
23230 (progn
23231 (goto-char (line-beginning-position))
23232 (not (outline-invisible-p)))))
23233 (setq count (1- count))
23234 (when (eq l level)
23235 (setq result (point)))))))
23236 (goto-char result))
23237 (beginning-of-line 1)))
23239 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23240 "Move backward to the ARG'th subheading at same level as this one.
23241 Stop at the first and last subheadings of a superior heading."
23242 (interactive "p")
23243 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23245 (defun org-next-block (arg &optional backward block-regexp)
23246 "Jump to the next block.
23247 With a prefix argument ARG, jump forward ARG many source blocks.
23248 When BACKWARD is non-nil, jump to the previous block.
23249 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23250 (interactive "p")
23251 (let ((re (or block-regexp org-block-regexp))
23252 (re-search-fn (or (and backward 're-search-backward)
23253 're-search-forward)))
23254 (if (looking-at re) (forward-char 1))
23255 (condition-case nil
23256 (funcall re-search-fn re nil nil arg)
23257 (error (error "No %s code blocks" (if backward "previous" "further" ))))
23258 (goto-char (match-beginning 0)) (org-show-context)))
23260 (defun org-previous-block (arg &optional block-regexp)
23261 "Jump to the previous block.
23262 With a prefix argument ARG, jump backward ARG many source blocks.
23263 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23264 (interactive "p")
23265 (org-next-block arg t block-regexp))
23267 (defun org-forward-element ()
23268 "Move forward by one element.
23269 Move to the next element at the same level, when possible."
23270 (interactive)
23271 (cond ((eobp) (user-error "Cannot move further down"))
23272 ((org-with-limited-levels (org-at-heading-p))
23273 (let ((origin (point)))
23274 (goto-char (org-end-of-subtree nil t))
23275 (unless (org-with-limited-levels (org-at-heading-p))
23276 (goto-char origin)
23277 (user-error "Cannot move further down"))))
23279 (let* ((elem (org-element-at-point))
23280 (end (org-element-property :end elem))
23281 (parent (org-element-property :parent elem)))
23282 (cond ((and parent (= (org-element-property :contents-end parent) end))
23283 (goto-char (org-element-property :end parent)))
23284 ((integer-or-marker-p end) (goto-char end))
23285 (t (message "No element at point")))))))
23287 (defun org-backward-element ()
23288 "Move backward by one element.
23289 Move to the previous element at the same level, when possible."
23290 (interactive)
23291 (cond ((bobp) (user-error "Cannot move further up"))
23292 ((org-with-limited-levels (org-at-heading-p))
23293 ;; At a headline, move to the previous one, if any, or stay
23294 ;; here.
23295 (let ((origin (point)))
23296 (org-with-limited-levels (org-backward-heading-same-level 1))
23297 ;; When current headline has no sibling above, move to its
23298 ;; parent.
23299 (when (= (point) origin)
23300 (or (org-with-limited-levels (org-up-heading-safe))
23301 (progn (goto-char origin)
23302 (user-error "Cannot move further up"))))))
23304 (let* ((trail (org-element-at-point 'keep-trail))
23305 (elem (car trail))
23306 (prev-elem (nth 1 trail))
23307 (beg (org-element-property :begin elem)))
23308 (cond
23309 ;; Move to beginning of current element if point isn't
23310 ;; there already.
23311 ((null beg) (message "No element at point"))
23312 ((/= (point) beg) (goto-char beg))
23313 (prev-elem (goto-char (org-element-property :begin prev-elem)))
23314 ((org-before-first-heading-p) (goto-char (point-min)))
23315 (t (org-back-to-heading)))))))
23317 (defun org-up-element ()
23318 "Move to upper element."
23319 (interactive)
23320 (if (org-with-limited-levels (org-at-heading-p))
23321 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23322 (let* ((elem (org-element-at-point))
23323 (parent (org-element-property :parent elem)))
23324 (if parent (goto-char (org-element-property :begin parent))
23325 (if (org-with-limited-levels (org-before-first-heading-p))
23326 (user-error "No surrounding element")
23327 (org-with-limited-levels (org-back-to-heading)))))))
23329 (defvar org-element-greater-elements)
23330 (defun org-down-element ()
23331 "Move to inner element."
23332 (interactive)
23333 (let ((element (org-element-at-point)))
23334 (cond
23335 ((memq (org-element-type element) '(plain-list table))
23336 (goto-char (org-element-property :contents-begin element))
23337 (forward-char))
23338 ((memq (org-element-type element) org-element-greater-elements)
23339 ;; If contents are hidden, first disclose them.
23340 (when (org-element-property :hiddenp element) (org-cycle))
23341 (goto-char (or (org-element-property :contents-begin element)
23342 (user-error "No content for this element"))))
23343 (t (user-error "No inner element")))))
23345 (defun org-drag-element-backward ()
23346 "Move backward element at point."
23347 (interactive)
23348 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
23349 (let* ((trail (org-element-at-point 'keep-trail))
23350 (elem (car trail))
23351 (prev-elem (nth 1 trail)))
23352 ;; Error out if no previous element or previous element is
23353 ;; a parent of the current one.
23354 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23355 (user-error "Cannot drag element backward")
23356 (let ((pos (point)))
23357 (org-element-swap-A-B prev-elem elem)
23358 (goto-char (+ (org-element-property :begin prev-elem)
23359 (- pos (org-element-property :begin elem)))))))))
23361 (defun org-drag-element-forward ()
23362 "Move forward element at point."
23363 (interactive)
23364 (let* ((pos (point))
23365 (elem (org-element-at-point)))
23366 (when (= (point-max) (org-element-property :end elem))
23367 (user-error "Cannot drag element forward"))
23368 (goto-char (org-element-property :end elem))
23369 (let ((next-elem (org-element-at-point)))
23370 (when (or (org-element-nested-p elem next-elem)
23371 (and (eq (org-element-type next-elem) 'headline)
23372 (not (eq (org-element-type elem) 'headline))))
23373 (goto-char pos)
23374 (user-error "Cannot drag element forward"))
23375 ;; Compute new position of point: it's shifted by NEXT-ELEM
23376 ;; body's length (without final blanks) and by the length of
23377 ;; blanks between ELEM and NEXT-ELEM.
23378 (let ((size-next (- (save-excursion
23379 (goto-char (org-element-property :end next-elem))
23380 (skip-chars-backward " \r\t\n")
23381 (forward-line)
23382 ;; Small correction if buffer doesn't end
23383 ;; with a newline character.
23384 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23385 (org-element-property :begin next-elem)))
23386 (size-blank (- (org-element-property :end elem)
23387 (save-excursion
23388 (goto-char (org-element-property :end elem))
23389 (skip-chars-backward " \r\t\n")
23390 (forward-line)
23391 (point)))))
23392 (org-element-swap-A-B elem next-elem)
23393 (goto-char (+ pos size-next size-blank))))))
23395 (defun org-drag-line-forward (arg)
23396 "Drag the line at point ARG lines forward."
23397 (interactive "p")
23398 (dotimes (n (abs arg))
23399 (let ((c (current-column)))
23400 (if (< 0 arg)
23401 (progn
23402 (beginning-of-line 2)
23403 (transpose-lines 1)
23404 (beginning-of-line 0))
23405 (transpose-lines 1)
23406 (beginning-of-line -1))
23407 (org-move-to-column c))))
23409 (defun org-drag-line-backward (arg)
23410 "Drag the line at point ARG lines backward."
23411 (interactive "p")
23412 (org-drag-line-forward (- arg)))
23414 (defun org-mark-element ()
23415 "Put point at beginning of this element, mark at end.
23417 Interactively, if this command is repeated or (in Transient Mark
23418 mode) if the mark is active, it marks the next element after the
23419 ones already marked."
23420 (interactive)
23421 (let (deactivate-mark)
23422 (if (and (org-called-interactively-p 'any)
23423 (or (and (eq last-command this-command) (mark t))
23424 (and transient-mark-mode mark-active)))
23425 (set-mark
23426 (save-excursion
23427 (goto-char (mark))
23428 (goto-char (org-element-property :end (org-element-at-point)))))
23429 (let ((element (org-element-at-point)))
23430 (end-of-line)
23431 (push-mark (org-element-property :end element) t t)
23432 (goto-char (org-element-property :begin element))))))
23434 (defun org-narrow-to-element ()
23435 "Narrow buffer to current element."
23436 (interactive)
23437 (let ((elem (org-element-at-point)))
23438 (cond
23439 ((eq (car elem) 'headline)
23440 (narrow-to-region
23441 (org-element-property :begin elem)
23442 (org-element-property :end elem)))
23443 ((memq (car elem) org-element-greater-elements)
23444 (narrow-to-region
23445 (org-element-property :contents-begin elem)
23446 (org-element-property :contents-end elem)))
23448 (narrow-to-region
23449 (org-element-property :begin elem)
23450 (org-element-property :end elem))))))
23452 (defun org-transpose-element ()
23453 "Transpose current and previous elements, keeping blank lines between.
23454 Point is moved after both elements."
23455 (interactive)
23456 (org-skip-whitespace)
23457 (let ((end (org-element-property :end (org-element-at-point))))
23458 (org-drag-element-backward)
23459 (goto-char end)))
23461 (defun org-unindent-buffer ()
23462 "Un-indent the visible part of the buffer.
23463 Relative indentation (between items, inside blocks, etc.) isn't
23464 modified."
23465 (interactive)
23466 (unless (eq major-mode 'org-mode)
23467 (user-error "Cannot un-indent a buffer not in Org mode"))
23468 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
23469 unindent-tree ; For byte-compiler.
23470 (unindent-tree
23471 (function
23472 (lambda (contents)
23473 (mapc
23474 (lambda (element)
23475 (if (memq (org-element-type element) '(headline section))
23476 (funcall unindent-tree (org-element-contents element))
23477 (save-excursion
23478 (save-restriction
23479 (narrow-to-region
23480 (org-element-property :begin element)
23481 (org-element-property :end element))
23482 (org-do-remove-indentation)))))
23483 (reverse contents))))))
23484 (funcall unindent-tree (org-element-contents parse-tree))))
23486 (defun org-show-subtree ()
23487 "Show everything after this heading at deeper levels."
23488 (interactive)
23489 (outline-flag-region
23490 (point)
23491 (save-excursion
23492 (org-end-of-subtree t t))
23493 nil))
23495 (defun org-show-entry ()
23496 "Show the body directly following this heading.
23497 Show the heading too, if it is currently invisible."
23498 (interactive)
23499 (save-excursion
23500 (condition-case nil
23501 (progn
23502 (org-back-to-heading t)
23503 (outline-flag-region
23504 (max (point-min) (1- (point)))
23505 (save-excursion
23506 (if (re-search-forward
23507 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23508 (match-beginning 1)
23509 (point-max)))
23510 nil)
23511 (org-cycle-hide-drawers 'children))
23512 (error nil))))
23514 (defun org-make-options-regexp (kwds &optional extra)
23515 "Make a regular expression for keyword lines."
23516 (concat
23517 "^#\\+\\("
23518 (mapconcat 'regexp-quote kwds "\\|")
23519 (if extra (concat "\\|" extra))
23520 "\\):[ \t]*\\(.*\\)"))
23522 ;; Make isearch reveal the necessary context
23523 (defun org-isearch-end ()
23524 "Reveal context after isearch exits."
23525 (when isearch-success ; only if search was successful
23526 (if (featurep 'xemacs)
23527 ;; Under XEmacs, the hook is run in the correct place,
23528 ;; we directly show the context.
23529 (org-show-context 'isearch)
23530 ;; In Emacs the hook runs *before* restoring the overlays.
23531 ;; So we have to use a one-time post-command-hook to do this.
23532 ;; (Emacs 22 has a special variable, see function `org-mode')
23533 (unless (and (boundp 'isearch-mode-end-hook-quit)
23534 isearch-mode-end-hook-quit)
23535 ;; Only when the isearch was not quitted.
23536 (org-add-hook 'post-command-hook 'org-isearch-post-command
23537 'append 'local)))
23538 (org-fix-ellipsis-at-bol)))
23540 (defun org-isearch-post-command ()
23541 "Remove self from hook, and show context."
23542 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23543 (org-show-context 'isearch))
23546 ;;;; Integration with and fixes for other packages
23548 ;;; Imenu support
23550 (defvar org-imenu-markers nil
23551 "All markers currently used by Imenu.")
23552 (make-variable-buffer-local 'org-imenu-markers)
23554 (defun org-imenu-new-marker (&optional pos)
23555 "Return a new marker for use by Imenu, and remember the marker."
23556 (let ((m (make-marker)))
23557 (move-marker m (or pos (point)))
23558 (push m org-imenu-markers)
23561 (defun org-imenu-get-tree ()
23562 "Produce the index for Imenu."
23563 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23564 (setq org-imenu-markers nil)
23565 (let* ((n org-imenu-depth)
23566 (re (concat "^" (org-get-limited-outline-regexp)))
23567 (subs (make-vector (1+ n) nil))
23568 (last-level 0)
23569 m level head0 head)
23570 (save-excursion
23571 (save-restriction
23572 (widen)
23573 (goto-char (point-max))
23574 (while (re-search-backward re nil t)
23575 (setq level (org-reduced-level (funcall outline-level)))
23576 (when (and (<= level n)
23577 (looking-at org-complex-heading-regexp)
23578 (setq head0 (org-match-string-no-properties 4)))
23579 (setq head (org-link-display-format head0)
23580 m (org-imenu-new-marker))
23581 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23582 (if (>= level last-level)
23583 (push (cons head m) (aref subs level))
23584 (push (cons head (aref subs (1+ level))) (aref subs level))
23585 (loop for i from (1+ level) to n do (aset subs i nil)))
23586 (setq last-level level)))))
23587 (aref subs 1)))
23589 (eval-after-load "imenu"
23590 '(progn
23591 (add-hook 'imenu-after-jump-hook
23592 (lambda ()
23593 (if (derived-mode-p 'org-mode)
23594 (org-show-context 'org-goto))))))
23596 (defun org-link-display-format (link)
23597 "Replace a link with its the description.
23598 If there is no description, use the link target."
23599 (save-match-data
23600 (if (string-match org-bracket-link-analytic-regexp link)
23601 (replace-match (if (match-end 5)
23602 (match-string 5 link)
23603 (concat (match-string 1 link)
23604 (match-string 3 link)))
23605 nil t link)
23606 link)))
23608 (defun org-toggle-link-display ()
23609 "Toggle the literal or descriptive display of links."
23610 (interactive)
23611 (if org-descriptive-links
23612 (progn (org-remove-from-invisibility-spec '(org-link))
23613 (org-restart-font-lock)
23614 (setq org-descriptive-links nil))
23615 (progn (add-to-invisibility-spec '(org-link))
23616 (org-restart-font-lock)
23617 (setq org-descriptive-links t))))
23619 ;; Speedbar support
23621 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23622 "Overlay marking the agenda restriction line in speedbar.")
23623 (overlay-put org-speedbar-restriction-lock-overlay
23624 'face 'org-agenda-restriction-lock)
23625 (overlay-put org-speedbar-restriction-lock-overlay
23626 'help-echo "Agendas are currently limited to this item.")
23627 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23629 (defun org-speedbar-set-agenda-restriction ()
23630 "Restrict future agenda commands to the location at point in speedbar.
23631 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23632 (interactive)
23633 (require 'org-agenda)
23634 (let (p m tp np dir txt)
23635 (cond
23636 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23637 'org-imenu t))
23638 (setq m (get-text-property p 'org-imenu-marker))
23639 (with-current-buffer (marker-buffer m)
23640 (goto-char m)
23641 (org-agenda-set-restriction-lock 'subtree)))
23642 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23643 'speedbar-function 'speedbar-find-file))
23644 (setq tp (previous-single-property-change
23645 (1+ p) 'speedbar-function)
23646 np (next-single-property-change
23647 tp 'speedbar-function)
23648 dir (speedbar-line-directory)
23649 txt (buffer-substring-no-properties (or tp (point-min))
23650 (or np (point-max))))
23651 (with-current-buffer (find-file-noselect
23652 (let ((default-directory dir))
23653 (expand-file-name txt)))
23654 (unless (derived-mode-p 'org-mode)
23655 (user-error "Cannot restrict to non-Org-mode file"))
23656 (org-agenda-set-restriction-lock 'file)))
23657 (t (user-error "Don't know how to restrict Org-mode's agenda")))
23658 (move-overlay org-speedbar-restriction-lock-overlay
23659 (point-at-bol) (point-at-eol))
23660 (setq current-prefix-arg nil)
23661 (org-agenda-maybe-redo)))
23663 (defvar speedbar-file-key-map)
23664 (declare-function speedbar-add-supported-extension "speedbar" (extension))
23665 (eval-after-load "speedbar"
23666 '(progn
23667 (speedbar-add-supported-extension ".org")
23668 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23669 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23670 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23671 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23672 (add-hook 'speedbar-visiting-tag-hook
23673 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23675 ;;; Fixes and Hacks for problems with other packages
23677 ;; Make flyspell not check words in links, to not mess up our keymap
23678 (defvar org-element-affiliated-keywords) ; From org-element.el
23679 (defvar org-element-block-name-alist) ; From org-element.el
23680 (defun org-mode-flyspell-verify ()
23681 "Don't let flyspell put overlays at active buttons, or on
23682 {todo,all-time,additional-option-like}-keywords."
23683 (require 'org-element) ; For `org-element-affiliated-keywords'
23684 (let ((pos (max (1- (point)) (point-min)))
23685 (word (thing-at-point 'word)))
23686 (and (not (get-text-property pos 'keymap))
23687 (not (get-text-property pos 'org-no-flyspell))
23688 (not (member word org-todo-keywords-1))
23689 (not (member word org-all-time-keywords))
23690 (not (member word org-options-keywords))
23691 (not (member word (mapcar 'car org-startup-options)))
23692 (not (member-ignore-case word org-element-affiliated-keywords))
23693 (not (member-ignore-case word (org-get-export-keywords)))
23694 (not (member-ignore-case
23695 word (mapcar 'car org-element-block-name-alist)))
23696 (not (member-ignore-case word '("BEGIN" "END" "ATTR")))
23697 (not (org-in-src-block-p)))))
23699 (defun org-remove-flyspell-overlays-in (beg end)
23700 "Remove flyspell overlays in region."
23701 (and (org-bound-and-true-p flyspell-mode)
23702 (fboundp 'flyspell-delete-region-overlays)
23703 (flyspell-delete-region-overlays beg end))
23704 (add-text-properties beg end '(org-no-flyspell t)))
23706 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23707 (eval-after-load "bookmark"
23708 '(if (boundp 'bookmark-after-jump-hook)
23709 ;; We can use the hook
23710 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23711 ;; Hook not available, use advice
23712 (defadvice bookmark-jump (after org-make-visible activate)
23713 "Make the position visible."
23714 (org-bookmark-jump-unhide))))
23716 ;; Make sure saveplace shows the location if it was hidden
23717 (eval-after-load "saveplace"
23718 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23719 "Make the position visible."
23720 (org-bookmark-jump-unhide)))
23722 ;; Make sure ecb shows the location if it was hidden
23723 (eval-after-load "ecb"
23724 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23725 "Make hierarchy visible when jumping into location from ECB tree buffer."
23726 (if (derived-mode-p 'org-mode)
23727 (org-show-context))))
23729 (defun org-bookmark-jump-unhide ()
23730 "Unhide the current position, to show the bookmark location."
23731 (and (derived-mode-p 'org-mode)
23732 (or (outline-invisible-p)
23733 (save-excursion (goto-char (max (point-min) (1- (point))))
23734 (outline-invisible-p)))
23735 (org-show-context 'bookmark-jump)))
23737 ;; Make session.el ignore our circular variable
23738 (defvar session-globals-exclude)
23739 (eval-after-load "session"
23740 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23742 ;;;; Finish up
23744 (provide 'org)
23746 (run-hooks 'org-load-hook)
23748 ;;; org.el ends here