org.el (org-refile): Fix refiling the active region within an list
[org-mode.git] / lisp / org.el
blob4266e27c2df6f13ebbcda2ad90d583f55f97a074
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-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
420 (const :tag "C mac-message: Links to messages in Apple Mail" org-mac-message)
421 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
422 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
423 (const :tag "C mew: Links to Mew folders/messages" org-mew)
424 (const :tag "C mtags: Support for muse-like tags" org-mtags)
425 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
426 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
427 (const :tag "C registry: A registry for Org-mode links" org-registry)
428 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
429 (const :tag "C secretary: Team management with org-mode" org-secretary)
430 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
431 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
432 (const :tag "C track: Keep up with Org-mode development" org-track)
433 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
434 (const :tag "C vm: Links to VM folders/messages" org-vm)
435 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
436 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
437 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
439 (defvar org-export-registered-backends) ; From ox.el
440 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
441 (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 VALUE stands for the
455 new value of the variable, after updating it:
457 \(progn
458 \(setq org-export-registered-backends
459 \(org-remove-if-not
460 \(lambda (backend)
461 \(or (memq backend val)
462 \(catch 'parentp
463 \(mapc
464 \(lambda (b)
465 \(and (org-export-derived-backend-p b (car backend))
466 \(throw 'parentp t)))
467 val)
468 nil)))
469 org-export-registered-backends))
470 \(let ((new-list (mapcar 'car org-export-registered-backends)))
471 \(dolist (backend val)
472 \(cond
473 \((not (load (format \"ox-%s\" backend) t t))
474 \(message \"Problems while trying to load export back-end `%s'\"
475 backend))
476 \((not (memq backend new-list)) (push backend new-list))))
477 \(set-default var new-list)))
479 Adding a back-end to this list will also pull the back-end it
480 depends on, if any."
481 :group 'org
482 :group 'org-export
483 :version "24.4"
484 :package-version '(Org . "8.0")
485 :initialize 'custom-initialize-set
486 :set (lambda (var val)
487 (if (not (featurep 'ox)) (set-default var val)
488 ;; Any back-end not required anymore (not present in VAL and not
489 ;; a parent of any back-end in the new value) is removed from the
490 ;; list of registered back-ends.
491 (setq org-export-registered-backends
492 (org-remove-if-not
493 (lambda (backend)
494 (or (memq backend val)
495 (catch 'parentp
496 (mapc
497 (lambda (b)
498 (and (org-export-derived-backend-p b (car backend))
499 (throw 'parentp t)))
500 val)
501 nil)))
502 org-export-registered-backends))
503 ;; Now build NEW-LIST of both new back-ends and required
504 ;; parents.
505 (let ((new-list (mapcar 'car org-export-registered-backends)))
506 (dolist (backend val)
507 (cond
508 ((not (load (format "ox-%s" backend) t t))
509 (message "Problems while trying to load export back-end `%s'"
510 backend))
511 ((not (memq backend new-list)) (push backend new-list))))
512 ;; Set VAR to that list with fixed dependencies.
513 (set-default var new-list))))
514 :type '(set :greedy t
515 (const :tag " ascii Export buffer to ASCII format" ascii)
516 (const :tag " beamer Export buffer to Beamer presentation" beamer)
517 (const :tag " html Export buffer to HTML format" html)
518 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
519 (const :tag " latex Export buffer to LaTeX format" latex)
520 (const :tag " man Export buffer to MAN format" man)
521 (const :tag " md Export buffer to Markdown format" md)
522 (const :tag " odt Export buffer to ODT format" odt)
523 (const :tag " org Export buffer to Org format" org)
524 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
525 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
526 (const :tag "C deck Export buffer to deck.js presentations" deck)
527 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
528 (const :tag "C groff Export buffer to Groff format" groff)
529 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
530 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
531 (const :tag "C s5 Export buffer to s5 presentations" s5)
532 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
534 (eval-after-load 'ox
535 '(mapc
536 (lambda (backend)
537 (condition-case nil (require (intern (format "ox-%s" backend)))
538 (error (message "Problems while trying to load export back-end `%s'"
539 backend))))
540 org-export-backends))
542 (defcustom org-support-shift-select nil
543 "Non-nil means make shift-cursor commands select text when possible.
545 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
546 start selecting a region, or enlarge regions started in this way.
547 In Org-mode, in special contexts, these same keys are used for
548 other purposes, important enough to compete with shift selection.
549 Org tries to balance these needs by supporting `shift-select-mode'
550 outside these special contexts, under control of this variable.
552 The default of this variable is nil, to avoid confusing behavior. Shifted
553 cursor keys will then execute Org commands in the following contexts:
554 - on a headline, changing TODO state (left/right) and priority (up/down)
555 - on a time stamp, changing the time
556 - in a plain list item, changing the bullet type
557 - in a property definition line, switching between allowed values
558 - in the BEGIN line of a clock table (changing the time block).
559 Outside these contexts, the commands will throw an error.
561 When this variable is t and the cursor is not in a special
562 context, Org-mode will support shift-selection for making and
563 enlarging regions. To make this more effective, the bullet
564 cycling will no longer happen anywhere in an item line, but only
565 if the cursor is exactly on the bullet.
567 If you set this variable to the symbol `always', then the keys
568 will not be special in headlines, property lines, and item lines,
569 to make shift selection work there as well. If this is what you
570 want, you can use the following alternative commands: `C-c C-t'
571 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
572 can be used to switch TODO sets, `C-c -' to cycle item bullet
573 types, and properties can be edited by hand or in column view.
575 However, when the cursor is on a timestamp, shift-cursor commands
576 will still edit the time stamp - this is just too good to give up.
578 XEmacs user should have this variable set to nil, because
579 `shift-select-mode' is in Emacs 23 or later only."
580 :group 'org
581 :type '(choice
582 (const :tag "Never" nil)
583 (const :tag "When outside special context" t)
584 (const :tag "Everywhere except timestamps" always)))
586 (defcustom org-loop-over-headlines-in-active-region nil
587 "Shall some commands act upon headlines in the active region?
589 When set to `t', some commands will be performed in all headlines
590 within the active region.
592 When set to `start-level', some commands will be performed in all
593 headlines within the active region, provided that these headlines
594 are of the same level than the first one.
596 When set to a string, those commands will be performed on the
597 matching headlines within the active region. Such string must be
598 a tags/property/todo match as it is used in the agenda tags view.
600 The list of commands is: `org-schedule', `org-deadline',
601 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
602 `org-archive-to-archive-sibling'. The archiving commands skip
603 already archived entries."
604 :type '(choice (const :tag "Don't loop" nil)
605 (const :tag "All headlines in active region" t)
606 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
607 (string :tag "Tags/Property/Todo matcher"))
608 :version "24.1"
609 :group 'org-todo
610 :group 'org-archive)
612 (defgroup org-startup nil
613 "Options concerning startup of Org-mode."
614 :tag "Org Startup"
615 :group 'org)
617 (defcustom org-startup-folded t
618 "Non-nil means entering Org-mode will switch to OVERVIEW.
619 This can also be configured on a per-file basis by adding one of
620 the following lines anywhere in the buffer:
622 #+STARTUP: fold (or `overview', this is equivalent)
623 #+STARTUP: nofold (or `showall', this is equivalent)
624 #+STARTUP: content
625 #+STARTUP: showeverything
627 By default, this option is ignored when Org opens agenda files
628 for the first time. If you want the agenda to honor the startup
629 option, set `org-agenda-inhibit-startup' to nil."
630 :group 'org-startup
631 :type '(choice
632 (const :tag "nofold: show all" nil)
633 (const :tag "fold: overview" t)
634 (const :tag "content: all headlines" content)
635 (const :tag "show everything, even drawers" showeverything)))
637 (defcustom org-startup-truncated t
638 "Non-nil means entering Org-mode will set `truncate-lines'.
639 This is useful since some lines containing links can be very long and
640 uninteresting. Also tables look terrible when wrapped."
641 :group 'org-startup
642 :type 'boolean)
644 (defcustom org-startup-indented nil
645 "Non-nil means turn on `org-indent-mode' on startup.
646 This can also be configured on a per-file basis by adding one of
647 the following lines anywhere in the buffer:
649 #+STARTUP: indent
650 #+STARTUP: noindent"
651 :group 'org-structure
652 :type '(choice
653 (const :tag "Not" nil)
654 (const :tag "Globally (slow on startup in large files)" t)))
656 (defcustom org-use-sub-superscripts t
657 "Non-nil means interpret \"_\" and \"^\" for display.
658 When this option is turned on, you can use TeX-like syntax for sub- and
659 superscripts. Several characters after \"_\" or \"^\" will be
660 considered as a single item - so grouping with {} is normally not
661 needed. For example, the following things will be parsed as single
662 sub- or superscripts.
664 10^24 or 10^tau several digits will be considered 1 item.
665 10^-12 or 10^-tau a leading sign with digits or a word
666 x^2-y^3 will be read as x^2 - y^3, because items are
667 terminated by almost any nonword/nondigit char.
668 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
670 Still, ambiguity is possible - so when in doubt use {} to enclose
671 the sub/superscript. If you set this variable to the symbol
672 `{}', the braces are *required* in order to trigger
673 interpretations as sub/superscript. This can be helpful in
674 documents that need \"_\" frequently in plain text."
675 :group 'org-startup
676 :version "24.1"
677 :type '(choice
678 (const :tag "Always interpret" t)
679 (const :tag "Only with braces" {})
680 (const :tag "Never interpret" nil)))
682 (defcustom org-startup-with-beamer-mode nil
683 "Non-nil means turn on `org-beamer-mode' on startup.
684 This can also be configured on a per-file basis by adding one of
685 the following lines anywhere in the buffer:
687 #+STARTUP: beamer"
688 :group 'org-startup
689 :version "24.1"
690 :type 'boolean)
692 (defcustom org-startup-align-all-tables nil
693 "Non-nil means align all tables when visiting a file.
694 This is useful when the column width in tables is forced with <N> cookies
695 in table fields. Such tables will look correct only after the first re-align.
696 This can also be configured on a per-file basis by adding one of
697 the following lines anywhere in the buffer:
698 #+STARTUP: align
699 #+STARTUP: noalign"
700 :group 'org-startup
701 :type 'boolean)
703 (defcustom org-startup-with-inline-images nil
704 "Non-nil means show inline images when loading a new Org file.
705 This can also be configured on a per-file basis by adding one of
706 the following lines anywhere in the buffer:
707 #+STARTUP: inlineimages
708 #+STARTUP: noinlineimages"
709 :group 'org-startup
710 :version "24.1"
711 :type 'boolean)
713 (defcustom org-startup-with-latex-preview nil
714 "Non-nil means preview LaTeX fragments when loading a new Org file.
716 This can also be configured on a per-file basis by adding one of
717 the followinglines anywhere in the buffer:
718 #+STARTUP: latexpreview
719 #+STARTUP: nolatexpreview"
720 :group 'org-startup
721 :version "24.4"
722 :package-version '(Org . "8.0")
723 :type 'boolean)
725 (defcustom org-insert-mode-line-in-empty-file nil
726 "Non-nil means insert the first line setting Org-mode in empty files.
727 When the function `org-mode' is called interactively in an empty file, this
728 normally means that the file name does not automatically trigger Org-mode.
729 To ensure that the file will always be in Org-mode in the future, a
730 line enforcing Org-mode will be inserted into the buffer, if this option
731 has been set."
732 :group 'org-startup
733 :type 'boolean)
735 (defcustom org-replace-disputed-keys nil
736 "Non-nil means use alternative key bindings for some keys.
737 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
738 These keys are also used by other packages like shift-selection-mode'
739 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
740 If you want to use Org-mode together with one of these other modes,
741 or more generally if you would like to move some Org-mode commands to
742 other keys, set this variable and configure the keys with the variable
743 `org-disputed-keys'.
745 This option is only relevant at load-time of Org-mode, and must be set
746 *before* org.el is loaded. Changing it requires a restart of Emacs to
747 become effective."
748 :group 'org-startup
749 :type 'boolean)
751 (defcustom org-use-extra-keys nil
752 "Non-nil means use extra key sequence definitions for certain commands.
753 This happens automatically if you run XEmacs or if `window-system'
754 is nil. This variable lets you do the same manually. You must
755 set it before loading org.
757 Example: on Carbon Emacs 22 running graphically, with an external
758 keyboard on a Powerbook, the default way of setting M-left might
759 not work for either Alt or ESC. Setting this variable will make
760 it work for ESC."
761 :group 'org-startup
762 :type 'boolean)
764 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
766 (defcustom org-disputed-keys
767 '(([(shift up)] . [(meta p)])
768 ([(shift down)] . [(meta n)])
769 ([(shift left)] . [(meta -)])
770 ([(shift right)] . [(meta +)])
771 ([(control shift right)] . [(meta shift +)])
772 ([(control shift left)] . [(meta shift -)]))
773 "Keys for which Org-mode and other modes compete.
774 This is an alist, cars are the default keys, second element specifies
775 the alternative to use when `org-replace-disputed-keys' is t.
777 Keys can be specified in any syntax supported by `define-key'.
778 The value of this option takes effect only at Org-mode's startup,
779 therefore you'll have to restart Emacs to apply it after changing."
780 :group 'org-startup
781 :type 'alist)
783 (defun org-key (key)
784 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
785 Or return the original if not disputed.
786 Also apply the translations defined in `org-xemacs-key-equivalents'."
787 (when org-replace-disputed-keys
788 (let* ((nkey (key-description key))
789 (x (org-find-if (lambda (x)
790 (equal (key-description (car x)) nkey))
791 org-disputed-keys)))
792 (setq key (if x (cdr x) key))))
793 (when (featurep 'xemacs)
794 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
795 key)
797 (defun org-find-if (predicate seq)
798 (catch 'exit
799 (while seq
800 (if (funcall predicate (car seq))
801 (throw 'exit (car seq))
802 (pop seq)))))
804 (defun org-defkey (keymap key def)
805 "Define a key, possibly translated, as returned by `org-key'."
806 (define-key keymap (org-key key) def))
808 (defcustom org-ellipsis nil
809 "The ellipsis to use in the Org-mode outline.
810 When nil, just use the standard three dots. When a string, use that instead,
811 When a face, use the standard 3 dots, but with the specified face.
812 The change affects only Org-mode (which will then use its own display table).
813 Changing this requires executing `M-x org-mode' in a buffer to become
814 effective."
815 :group 'org-startup
816 :type '(choice (const :tag "Default" nil)
817 (face :tag "Face" :value org-warning)
818 (string :tag "String" :value "...#")))
820 (defvar org-display-table nil
821 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
823 (defgroup org-keywords nil
824 "Keywords in Org-mode."
825 :tag "Org Keywords"
826 :group 'org)
828 (defcustom org-deadline-string "DEADLINE:"
829 "String to mark deadline entries.
830 A deadline is this string, followed by a time stamp. Should be a word,
831 terminated by a colon. You can insert a schedule keyword and
832 a timestamp with \\[org-deadline].
833 Changes become only effective after restarting Emacs."
834 :group 'org-keywords
835 :type 'string)
837 (defcustom org-scheduled-string "SCHEDULED:"
838 "String to mark scheduled TODO entries.
839 A schedule is this string, followed by a time stamp. Should be a word,
840 terminated by a colon. You can insert a schedule keyword and
841 a timestamp with \\[org-schedule].
842 Changes become only effective after restarting Emacs."
843 :group 'org-keywords
844 :type 'string)
846 (defcustom org-closed-string "CLOSED:"
847 "String used as the prefix for timestamps logging closing a TODO entry."
848 :group 'org-keywords
849 :type 'string)
851 (defcustom org-clock-string "CLOCK:"
852 "String used as prefix for timestamps clocking work hours on an item."
853 :group 'org-keywords
854 :type 'string)
856 (defcustom org-closed-keep-when-no-todo nil
857 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
858 :group 'org-todo
859 :group 'org-keywords
860 :version "24.4"
861 :package-version '(Org . "8.0")
862 :type 'boolean)
864 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
865 org-scheduled-string "\\|"
866 org-deadline-string "\\|"
867 org-closed-string "\\|"
868 org-clock-string "\\)")
869 "Matches a line with planning or clock info.")
871 (defcustom org-comment-string "COMMENT"
872 "Entries starting with this keyword will never be exported.
873 An entry can be toggled between COMMENT and normal with
874 \\[org-toggle-comment].
875 Changes become only effective after restarting Emacs."
876 :group 'org-keywords
877 :type 'string)
879 (defcustom org-quote-string "QUOTE"
880 "Entries starting with this keyword will be exported in fixed-width font.
881 Quoting applies only to the text in the entry following the headline, and does
882 not extend beyond the next headline, even if that is lower level.
883 An entry can be toggled between QUOTE and normal with
884 \\[org-toggle-fixed-width-section]."
885 :group 'org-keywords
886 :type 'string)
888 (defconst org-repeat-re
889 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
890 "Regular expression for specifying repeated events.
891 After a match, group 1 contains the repeat expression.")
893 (defgroup org-structure nil
894 "Options concerning the general structure of Org-mode files."
895 :tag "Org Structure"
896 :group 'org)
898 (defgroup org-reveal-location nil
899 "Options about how to make context of a location visible."
900 :tag "Org Reveal Location"
901 :group 'org-structure)
903 (defconst org-context-choice
904 '(choice
905 (const :tag "Always" t)
906 (const :tag "Never" nil)
907 (repeat :greedy t :tag "Individual contexts"
908 (cons
909 (choice :tag "Context"
910 (const agenda)
911 (const org-goto)
912 (const occur-tree)
913 (const tags-tree)
914 (const link-search)
915 (const mark-goto)
916 (const bookmark-jump)
917 (const isearch)
918 (const default))
919 (boolean))))
920 "Contexts for the reveal options.")
922 (defcustom org-show-hierarchy-above '((default . t))
923 "Non-nil means show full hierarchy when revealing a location.
924 Org-mode often shows locations in an org-mode file which might have
925 been invisible before. When this is set, the hierarchy of headings
926 above the exposed location is shown.
927 Turning this off for example for sparse trees makes them very compact.
928 Instead of t, this can also be an alist specifying this option for different
929 contexts. Valid contexts are
930 agenda when exposing an entry from the agenda
931 org-goto when using the command `org-goto' on key C-c C-j
932 occur-tree when using the command `org-occur' on key C-c /
933 tags-tree when constructing a sparse tree based on tags matches
934 link-search when exposing search matches associated with a link
935 mark-goto when exposing the jump goal of a mark
936 bookmark-jump when exposing a bookmark location
937 isearch when exiting from an incremental search
938 default default for all contexts not set explicitly"
939 :group 'org-reveal-location
940 :type org-context-choice)
942 (defcustom org-show-following-heading '((default . nil))
943 "Non-nil means show following heading when revealing a location.
944 Org-mode often shows locations in an org-mode file which might have
945 been invisible before. When this is set, the heading following the
946 match is shown.
947 Turning this off for example for sparse trees makes them very compact,
948 but makes it harder to edit the location of the match. In such a case,
949 use the command \\[org-reveal] to show more context.
950 Instead of t, this can also be an alist specifying this option for different
951 contexts. See `org-show-hierarchy-above' for valid contexts."
952 :group 'org-reveal-location
953 :type org-context-choice)
955 (defcustom org-show-siblings '((default . nil) (isearch t) (bookmark-jump t))
956 "Non-nil means show all sibling heading when revealing a location.
957 Org-mode often shows locations in an org-mode file which might have
958 been invisible before. When this is set, the sibling of the current entry
959 heading are all made visible. If `org-show-hierarchy-above' is t,
960 the same happens on each level of the hierarchy above the current entry.
962 By default this is on for the isearch context, off for all other contexts.
963 Turning this off for example for sparse trees makes them very compact,
964 but makes it harder to edit the location of the match. In such a case,
965 use the command \\[org-reveal] to show more context.
966 Instead of t, this can also be an alist specifying this option for different
967 contexts. See `org-show-hierarchy-above' for valid contexts."
968 :group 'org-reveal-location
969 :type org-context-choice
970 :version "24.4"
971 :package-version '(Org . "8.0"))
973 (defcustom org-show-entry-below '((default . nil))
974 "Non-nil means show the entry below a headline when revealing a location.
975 Org-mode often shows locations in an org-mode file which might have
976 been invisible before. When this is set, the text below the headline that is
977 exposed is also shown.
979 By default this is off for all contexts.
980 Instead of t, this can also be an alist specifying this option for different
981 contexts. See `org-show-hierarchy-above' for valid contexts."
982 :group 'org-reveal-location
983 :type org-context-choice)
985 (defcustom org-indirect-buffer-display 'other-window
986 "How should indirect tree buffers be displayed?
987 This applies to indirect buffers created with the commands
988 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
989 Valid values are:
990 current-window Display in the current window
991 other-window Just display in another window.
992 dedicated-frame Create one new frame, and re-use it each time.
993 new-frame Make a new frame each time. Note that in this case
994 previously-made indirect buffers are kept, and you need to
995 kill these buffers yourself."
996 :group 'org-structure
997 :group 'org-agenda-windows
998 :type '(choice
999 (const :tag "In current window" current-window)
1000 (const :tag "In current frame, other window" other-window)
1001 (const :tag "Each time a new frame" new-frame)
1002 (const :tag "One dedicated frame" dedicated-frame)))
1004 (defcustom org-use-speed-commands nil
1005 "Non-nil means activate single letter commands at beginning of a headline.
1006 This may also be a function to test for appropriate locations where speed
1007 commands should be active."
1008 :group 'org-structure
1009 :type '(choice
1010 (const :tag "Never" nil)
1011 (const :tag "At beginning of headline stars" t)
1012 (function)))
1014 (defcustom org-speed-commands-user nil
1015 "Alist of additional speed commands.
1016 This list will be checked before `org-speed-commands-default'
1017 when the variable `org-use-speed-commands' is non-nil
1018 and when the cursor is at the beginning of a headline.
1019 The car if each entry is a string with a single letter, which must
1020 be assigned to `self-insert-command' in the global map.
1021 The cdr is either a command to be called interactively, a function
1022 to be called, or a form to be evaluated.
1023 An entry that is just a list with a single string will be interpreted
1024 as a descriptive headline that will be added when listing the speed
1025 commands in the Help buffer using the `?' speed command."
1026 :group 'org-structure
1027 :type '(repeat :value ("k" . ignore)
1028 (choice :value ("k" . ignore)
1029 (list :tag "Descriptive Headline" (string :tag "Headline"))
1030 (cons :tag "Letter and Command"
1031 (string :tag "Command letter")
1032 (choice
1033 (function)
1034 (sexp))))))
1036 (defgroup org-cycle nil
1037 "Options concerning visibility cycling in Org-mode."
1038 :tag "Org Cycle"
1039 :group 'org-structure)
1041 (defcustom org-cycle-skip-children-state-if-no-children t
1042 "Non-nil means skip CHILDREN state in entries that don't have any."
1043 :group 'org-cycle
1044 :type 'boolean)
1046 (defcustom org-cycle-max-level nil
1047 "Maximum level which should still be subject to visibility cycling.
1048 Levels higher than this will, for cycling, be treated as text, not a headline.
1049 When `org-odd-levels-only' is set, a value of N in this variable actually
1050 means 2N-1 stars as the limiting headline.
1051 When nil, cycle all levels.
1052 Note that the limiting level of cycling is also influenced by
1053 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1054 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1055 than its value."
1056 :group 'org-cycle
1057 :type '(choice
1058 (const :tag "No limit" nil)
1059 (integer :tag "Maximum level")))
1061 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
1062 "Names of drawers. Drawers are not opened by cycling on the headline above.
1063 Drawers only open with a TAB on the drawer line itself. A drawer looks like
1064 this:
1065 :DRAWERNAME:
1066 .....
1067 :END:
1068 The drawer \"PROPERTIES\" is special for capturing properties through
1069 the property API.
1071 Drawers can be defined on the per-file basis with a line like:
1073 #+DRAWERS: HIDDEN STATE PROPERTIES"
1074 :group 'org-structure
1075 :group 'org-cycle
1076 :type '(repeat (string :tag "Drawer Name")))
1078 (defcustom org-hide-block-startup nil
1079 "Non-nil means entering Org-mode will fold all blocks.
1080 This can also be set in on a per-file basis with
1082 #+STARTUP: hideblocks
1083 #+STARTUP: showblocks"
1084 :group 'org-startup
1085 :group 'org-cycle
1086 :type 'boolean)
1088 (defcustom org-cycle-global-at-bob nil
1089 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1090 This makes it possible to do global cycling without having to use S-TAB or
1091 \\[universal-argument] TAB. For this special case to work, the first line
1092 of the buffer must not be a headline -- it may be empty or some other text.
1093 When used in this way, `org-cycle-hook' is disabled temporarily to make
1094 sure the cursor stays at the beginning of the buffer. When this option is
1095 nil, don't do anything special at the beginning of the buffer."
1096 :group 'org-cycle
1097 :type 'boolean)
1099 (defcustom org-cycle-level-after-item/entry-creation t
1100 "Non-nil means cycle entry level or item indentation in new empty entries.
1102 When the cursor is at the end of an empty headline, i.e., with only stars
1103 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1104 and then all possible ancestor states, before returning to the original state.
1105 This makes data entry extremely fast: M-RET to create a new headline,
1106 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1108 When the cursor is at the end of an empty plain list item, one TAB will
1109 make it a subitem, two or more tabs will back up to make this an item
1110 higher up in the item hierarchy."
1111 :group 'org-cycle
1112 :type 'boolean)
1114 (defcustom org-cycle-emulate-tab t
1115 "Where should `org-cycle' emulate TAB.
1116 nil Never
1117 white Only in completely white lines
1118 whitestart Only at the beginning of lines, before the first non-white char
1119 t Everywhere except in headlines
1120 exc-hl-bol Everywhere except at the start of a headline
1121 If TAB is used in a place where it does not emulate TAB, the current subtree
1122 visibility is cycled."
1123 :group 'org-cycle
1124 :type '(choice (const :tag "Never" nil)
1125 (const :tag "Only in completely white lines" white)
1126 (const :tag "Before first char in a line" whitestart)
1127 (const :tag "Everywhere except in headlines" t)
1128 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1130 (defcustom org-cycle-separator-lines 2
1131 "Number of empty lines needed to keep an empty line between collapsed trees.
1132 If you leave an empty line between the end of a subtree and the following
1133 headline, this empty line is hidden when the subtree is folded.
1134 Org-mode will leave (exactly) one empty line visible if the number of
1135 empty lines is equal or larger to the number given in this variable.
1136 So the default 2 means at least 2 empty lines after the end of a subtree
1137 are needed to produce free space between a collapsed subtree and the
1138 following headline.
1140 If the number is negative, and the number of empty lines is at least -N,
1141 all empty lines are shown.
1143 Special case: when 0, never leave empty lines in collapsed view."
1144 :group 'org-cycle
1145 :type 'integer)
1146 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1148 (defcustom org-pre-cycle-hook nil
1149 "Hook that is run before visibility cycling is happening.
1150 The function(s) in this hook must accept a single argument which indicates
1151 the new state that will be set right after running this hook. The
1152 argument is a symbol. Before a global state change, it can have the values
1153 `overview', `content', or `all'. Before a local state change, it can have
1154 the values `folded', `children', or `subtree'."
1155 :group 'org-cycle
1156 :type 'hook)
1158 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1159 org-cycle-hide-drawers
1160 org-cycle-hide-inline-tasks
1161 org-cycle-show-empty-lines
1162 org-optimize-window-after-visibility-change)
1163 "Hook that is run after `org-cycle' has changed the buffer visibility.
1164 The function(s) in this hook must accept a single argument which indicates
1165 the new state that was set by the most recent `org-cycle' command. The
1166 argument is a symbol. After a global state change, it can have the values
1167 `overview', `contents', or `all'. After a local state change, it can have
1168 the values `folded', `children', or `subtree'."
1169 :group 'org-cycle
1170 :type 'hook)
1172 (defgroup org-edit-structure nil
1173 "Options concerning structure editing in Org-mode."
1174 :tag "Org Edit Structure"
1175 :group 'org-structure)
1177 (defcustom org-odd-levels-only nil
1178 "Non-nil means skip even levels and only use odd levels for the outline.
1179 This has the effect that two stars are being added/taken away in
1180 promotion/demotion commands. It also influences how levels are
1181 handled by the exporters.
1182 Changing it requires restart of `font-lock-mode' to become effective
1183 for fontification also in regions already fontified.
1184 You may also set this on a per-file basis by adding one of the following
1185 lines to the buffer:
1187 #+STARTUP: odd
1188 #+STARTUP: oddeven"
1189 :group 'org-edit-structure
1190 :group 'org-appearance
1191 :type 'boolean)
1193 (defcustom org-adapt-indentation t
1194 "Non-nil means adapt indentation to outline node level.
1196 When this variable is set, Org assumes that you write outlines by
1197 indenting text in each node to align with the headline (after the stars).
1198 The following issues are influenced by this variable:
1200 - When this is set and the *entire* text in an entry is indented, the
1201 indentation is increased by one space in a demotion command, and
1202 decreased by one in a promotion command. If any line in the entry
1203 body starts with text at column 0, indentation is not changed at all.
1205 - Property drawers and planning information is inserted indented when
1206 this variable s set. When nil, they will not be indented.
1208 - TAB indents a line relative to context. The lines below a headline
1209 will be indented when this variable is set.
1211 Note that this is all about true indentation, by adding and removing
1212 space characters. See also `org-indent.el' which does level-dependent
1213 indentation in a virtual way, i.e. at display time in Emacs."
1214 :group 'org-edit-structure
1215 :type 'boolean)
1217 (defcustom org-special-ctrl-a/e nil
1218 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1220 When t, `C-a' will bring back the cursor to the beginning of the
1221 headline text, i.e. after the stars and after a possible TODO
1222 keyword. In an item, this will be the position after bullet and
1223 check-box, if any. When the cursor is already at that position,
1224 another `C-a' will bring it to the beginning of the line.
1226 `C-e' will jump to the end of the headline, ignoring the presence
1227 of tags in the headline. A second `C-e' will then jump to the
1228 true end of the line, after any tags. This also means that, when
1229 this variable is non-nil, `C-e' also will never jump beyond the
1230 end of the heading of a folded section, i.e. not after the
1231 ellipses.
1233 When set to the symbol `reversed', the first `C-a' or `C-e' works
1234 normally, going to the true line boundary first. Only a directly
1235 following, identical keypress will bring the cursor to the
1236 special positions.
1238 This may also be a cons cell where the behavior for `C-a' and
1239 `C-e' is set separately."
1240 :group 'org-edit-structure
1241 :type '(choice
1242 (const :tag "off" nil)
1243 (const :tag "on: after stars/bullet and before tags first" t)
1244 (const :tag "reversed: true line boundary first" reversed)
1245 (cons :tag "Set C-a and C-e separately"
1246 (choice :tag "Special C-a"
1247 (const :tag "off" nil)
1248 (const :tag "on: after stars/bullet first" t)
1249 (const :tag "reversed: before stars/bullet first" reversed))
1250 (choice :tag "Special C-e"
1251 (const :tag "off" nil)
1252 (const :tag "on: before tags first" t)
1253 (const :tag "reversed: after tags first" reversed)))))
1254 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1256 (defcustom org-special-ctrl-k nil
1257 "Non-nil means `C-k' will behave specially in headlines.
1258 When nil, `C-k' will call the default `kill-line' command.
1259 When t, the following will happen while the cursor is in the headline:
1261 - When the cursor is at the beginning of a headline, kill the entire
1262 line and possible the folded subtree below the line.
1263 - When in the middle of the headline text, kill the headline up to the tags.
1264 - When after the headline text, kill the tags."
1265 :group 'org-edit-structure
1266 :type 'boolean)
1268 (defcustom org-ctrl-k-protect-subtree nil
1269 "Non-nil means, do not delete a hidden subtree with C-k.
1270 When set to the symbol `error', simply throw an error when C-k is
1271 used to kill (part-of) a headline that has hidden text behind it.
1272 Any other non-nil value will result in a query to the user, if it is
1273 OK to kill that hidden subtree. When nil, kill without remorse."
1274 :group 'org-edit-structure
1275 :version "24.1"
1276 :type '(choice
1277 (const :tag "Do not protect hidden subtrees" nil)
1278 (const :tag "Protect hidden subtrees with a security query" t)
1279 (const :tag "Never kill a hidden subtree with C-k" error)))
1281 (defcustom org-catch-invisible-edits nil
1282 "Check if in invisible region before inserting or deleting a character.
1283 Valid values are:
1285 nil Do not check, so just do invisible edits.
1286 error Throw an error and do nothing.
1287 show Make point visible, and do the requested edit.
1288 show-and-error Make point visible, then throw an error and abort the edit.
1289 smart Make point visible, and do insertion/deletion if it is
1290 adjacent to visible text and the change feels predictable.
1291 Never delete a previously invisible character or add in the
1292 middle or right after an invisible region. Basically, this
1293 allows insertion and backward-delete right before ellipses.
1294 FIXME: maybe in this case we should not even show?"
1295 :group 'org-edit-structure
1296 :version "24.1"
1297 :type '(choice
1298 (const :tag "Do not check" nil)
1299 (const :tag "Throw error when trying to edit" error)
1300 (const :tag "Unhide, but do not do the edit" show-and-error)
1301 (const :tag "Show invisible part and do the edit" show)
1302 (const :tag "Be smart and do the right thing" smart)))
1304 (defcustom org-yank-folded-subtrees t
1305 "Non-nil means when yanking subtrees, fold them.
1306 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1307 it starts with a heading and all other headings in it are either children
1308 or siblings, then fold all the subtrees. However, do this only if no
1309 text after the yank would be swallowed into a folded tree by this action."
1310 :group 'org-edit-structure
1311 :type 'boolean)
1313 (defcustom org-yank-adjusted-subtrees nil
1314 "Non-nil means when yanking subtrees, adjust the level.
1315 With this setting, `org-paste-subtree' is used to insert the subtree, see
1316 this function for details."
1317 :group 'org-edit-structure
1318 :type 'boolean)
1320 (defcustom org-M-RET-may-split-line '((default . t))
1321 "Non-nil means M-RET will split the line at the cursor position.
1322 When nil, it will go to the end of the line before making a
1323 new line.
1324 You may also set this option in a different way for different
1325 contexts. Valid contexts are:
1327 headline when creating a new headline
1328 item when creating a new item
1329 table in a table field
1330 default the value to be used for all contexts not explicitly
1331 customized"
1332 :group 'org-structure
1333 :group 'org-table
1334 :type '(choice
1335 (const :tag "Always" t)
1336 (const :tag "Never" nil)
1337 (repeat :greedy t :tag "Individual contexts"
1338 (cons
1339 (choice :tag "Context"
1340 (const headline)
1341 (const item)
1342 (const table)
1343 (const default))
1344 (boolean)))))
1347 (defcustom org-insert-heading-respect-content nil
1348 "Non-nil means insert new headings after the current subtree.
1349 When nil, the new heading is created directly after the current line.
1350 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1351 this variable on for the duration of the command."
1352 :group 'org-structure
1353 :type 'boolean)
1355 (defcustom org-blank-before-new-entry '((heading . auto)
1356 (plain-list-item . auto))
1357 "Should `org-insert-heading' leave a blank line before new heading/item?
1358 The value is an alist, with `heading' and `plain-list-item' as CAR,
1359 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1360 which case Org will look at the surrounding headings/items and try to
1361 make an intelligent decision whether to insert a blank line or not.
1363 For plain lists, if `org-list-empty-line-terminates-plain-lists' is set,
1364 the setting here is ignored and no empty line is inserted to avoid breaking
1365 the list structure."
1366 :group 'org-edit-structure
1367 :type '(list
1368 (cons (const heading)
1369 (choice (const :tag "Never" nil)
1370 (const :tag "Always" t)
1371 (const :tag "Auto" auto)))
1372 (cons (const plain-list-item)
1373 (choice (const :tag "Never" nil)
1374 (const :tag "Always" t)
1375 (const :tag "Auto" auto)))))
1377 (defcustom org-insert-heading-hook nil
1378 "Hook being run after inserting a new heading."
1379 :group 'org-edit-structure
1380 :type 'hook)
1382 (defcustom org-enable-fixed-width-editor t
1383 "Non-nil means lines starting with \":\" are treated as fixed-width.
1384 This currently only means they are never auto-wrapped.
1385 When nil, such lines will be treated like ordinary lines.
1386 See also the QUOTE keyword."
1387 :group 'org-edit-structure
1388 :type 'boolean)
1390 (defcustom org-goto-auto-isearch t
1391 "Non-nil means typing characters in `org-goto' starts incremental search.
1392 When nil, you can use these keybindings to navigate the buffer:
1394 q Quit the org-goto interface
1395 n Go to the next visible heading
1396 p Go to the previous visible heading
1397 f Go one heading forward on same level
1398 b Go one heading backward on same level
1399 u Go one heading up"
1400 :group 'org-edit-structure
1401 :type 'boolean)
1403 (defgroup org-sparse-trees nil
1404 "Options concerning sparse trees in Org-mode."
1405 :tag "Org Sparse Trees"
1406 :group 'org-structure)
1408 (defcustom org-highlight-sparse-tree-matches t
1409 "Non-nil means highlight all matches that define a sparse tree.
1410 The highlights will automatically disappear the next time the buffer is
1411 changed by an edit command."
1412 :group 'org-sparse-trees
1413 :type 'boolean)
1415 (defcustom org-remove-highlights-with-change t
1416 "Non-nil means any change to the buffer will remove temporary highlights.
1417 Such highlights are created by `org-occur' and `org-clock-display'.
1418 When nil, `C-c C-c needs to be used to get rid of the highlights.
1419 The highlights created by `org-preview-latex-fragment' always need
1420 `C-c C-c' to be removed."
1421 :group 'org-sparse-trees
1422 :group 'org-time
1423 :type 'boolean)
1426 (defcustom org-occur-hook '(org-first-headline-recenter)
1427 "Hook that is run after `org-occur' has constructed a sparse tree.
1428 This can be used to recenter the window to show as much of the structure
1429 as possible."
1430 :group 'org-sparse-trees
1431 :type 'hook)
1433 (defgroup org-imenu-and-speedbar nil
1434 "Options concerning imenu and speedbar in Org-mode."
1435 :tag "Org Imenu and Speedbar"
1436 :group 'org-structure)
1438 (defcustom org-imenu-depth 2
1439 "The maximum level for Imenu access to Org-mode headlines.
1440 This also applied for speedbar access."
1441 :group 'org-imenu-and-speedbar
1442 :type 'integer)
1444 (defgroup org-table nil
1445 "Options concerning tables in Org-mode."
1446 :tag "Org Table"
1447 :group 'org)
1449 (defcustom org-enable-table-editor 'optimized
1450 "Non-nil means lines starting with \"|\" are handled by the table editor.
1451 When nil, such lines will be treated like ordinary lines.
1453 When equal to the symbol `optimized', the table editor will be optimized to
1454 do the following:
1455 - Automatic overwrite mode in front of whitespace in table fields.
1456 This makes the structure of the table stay in tact as long as the edited
1457 field does not exceed the column width.
1458 - Minimize the number of realigns. Normally, the table is aligned each time
1459 TAB or RET are pressed to move to another field. With optimization this
1460 happens only if changes to a field might have changed the column width.
1461 Optimization requires replacing the functions `self-insert-command',
1462 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1463 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1464 very good at guessing when a re-align will be necessary, but you can always
1465 force one with \\[org-ctrl-c-ctrl-c].
1467 If you would like to use the optimized version in Org-mode, but the
1468 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1470 This variable can be used to turn on and off the table editor during a session,
1471 but in order to toggle optimization, a restart is required.
1473 See also the variable `org-table-auto-blank-field'."
1474 :group 'org-table
1475 :type '(choice
1476 (const :tag "off" nil)
1477 (const :tag "on" t)
1478 (const :tag "on, optimized" optimized)))
1480 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1481 (version<= emacs-version "24.1"))
1482 "Non-nil means cluster self-insert commands for undo when possible.
1483 If this is set, then, like in the Emacs command loop, 20 consecutive
1484 characters will be undone together.
1485 This is configurable, because there is some impact on typing performance."
1486 :group 'org-table
1487 :type 'boolean)
1489 (defcustom org-table-tab-recognizes-table.el t
1490 "Non-nil means TAB will automatically notice a table.el table.
1491 When it sees such a table, it moves point into it and - if necessary -
1492 calls `table-recognize-table'."
1493 :group 'org-table-editing
1494 :type 'boolean)
1496 (defgroup org-link nil
1497 "Options concerning links in Org-mode."
1498 :tag "Org Link"
1499 :group 'org)
1501 (defvar org-link-abbrev-alist-local nil
1502 "Buffer-local version of `org-link-abbrev-alist', which see.
1503 The value of this is taken from the #+LINK lines.")
1504 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1506 (defcustom org-link-abbrev-alist nil
1507 "Alist of link abbreviations.
1508 The car of each element is a string, to be replaced at the start of a link.
1509 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1510 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1512 [[linkkey:tag][description]]
1514 The 'linkkey' must be a word word, starting with a letter, followed
1515 by letters, numbers, '-' or '_'.
1517 If REPLACE is a string, the tag will simply be appended to create the link.
1518 If the string contains \"%s\", the tag will be inserted there. If the string
1519 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1520 at that point (see the function `url-hexify-string'). If the string contains
1521 the specifier \"%(my-function)\", then the custom function `my-function' will
1522 be invoked: this function takes the tag as its only argument and must return
1523 a string.
1525 REPLACE may also be a function that will be called with the tag as the
1526 only argument to create the link, which should be returned as a string.
1528 See the manual for examples."
1529 :group 'org-link
1530 :type '(repeat
1531 (cons
1532 (string :tag "Protocol")
1533 (choice
1534 (string :tag "Format")
1535 (function)))))
1537 (defcustom org-descriptive-links t
1538 "Non-nil means Org will display descriptive links.
1539 E.g. [[http://orgmode.org][Org website]] will be displayed as
1540 \"Org Website\", hiding the link itself and just displaying its
1541 description. When set to `nil', Org will display the full links
1542 literally.
1544 You can interactively set the value of this variable by calling
1545 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1546 :group 'org-link
1547 :type 'boolean)
1549 (defcustom org-link-file-path-type 'adaptive
1550 "How the path name in file links should be stored.
1551 Valid values are:
1553 relative Relative to the current directory, i.e. the directory of the file
1554 into which the link is being inserted.
1555 absolute Absolute path, if possible with ~ for home directory.
1556 noabbrev Absolute path, no abbreviation of home directory.
1557 adaptive Use relative path for files in the current directory and sub-
1558 directories of it. For other files, use an absolute path."
1559 :group 'org-link
1560 :type '(choice
1561 (const relative)
1562 (const absolute)
1563 (const noabbrev)
1564 (const adaptive)))
1566 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1567 "Types of links that should be activated in Org-mode files.
1568 This is a list of symbols, each leading to the activation of a certain link
1569 type. In principle, it does not hurt to turn on most link types - there may
1570 be a small gain when turning off unused link types. The types are:
1572 bracket The recommended [[link][description]] or [[link]] links with hiding.
1573 angle Links in angular brackets that may contain whitespace like
1574 <bbdb:Carsten Dominik>.
1575 plain Plain links in normal text, no whitespace, like http://google.com.
1576 radio Text that is matched by a radio target, see manual for details.
1577 tag Tag settings in a headline (link to tag search).
1578 date Time stamps (link to calendar).
1579 footnote Footnote labels.
1581 Changing this variable requires a restart of Emacs to become effective."
1582 :group 'org-link
1583 :type '(set :greedy t
1584 (const :tag "Double bracket links" bracket)
1585 (const :tag "Angular bracket links" angle)
1586 (const :tag "Plain text links" plain)
1587 (const :tag "Radio target matches" radio)
1588 (const :tag "Tags" tag)
1589 (const :tag "Timestamps" date)
1590 (const :tag "Footnotes" footnote)))
1592 (defcustom org-make-link-description-function nil
1593 "Function to use for generating link descriptions from links.
1594 When nil, the link location will be used. This function must take
1595 two parameters: the first one is the link, the second one is the
1596 description generated by `org-insert-link'. The function should
1597 return the description to use."
1598 :group 'org-link
1599 :type 'function)
1601 (defgroup org-link-store nil
1602 "Options concerning storing links in Org-mode."
1603 :tag "Org Store Link"
1604 :group 'org-link)
1606 (defcustom org-url-hexify-p t
1607 "When non-nil, hexify URL when creating a link."
1608 :type 'boolean
1609 :version "24.3"
1610 :group 'org-link-store)
1612 (defcustom org-email-link-description-format "Email %c: %.30s"
1613 "Format of the description part of a link to an email or usenet message.
1614 The following %-escapes will be replaced by corresponding information:
1616 %F full \"From\" field
1617 %f name, taken from \"From\" field, address if no name
1618 %T full \"To\" field
1619 %t first name in \"To\" field, address if no name
1620 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1621 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1622 %s subject
1623 %d date
1624 %m message-id.
1626 You may use normal field width specification between the % and the letter.
1627 This is for example useful to limit the length of the subject.
1629 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1630 :group 'org-link-store
1631 :type 'string)
1633 (defcustom org-from-is-user-regexp
1634 (let (r1 r2)
1635 (when (and user-mail-address (not (string= user-mail-address "")))
1636 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1637 (when (and user-full-name (not (string= user-full-name "")))
1638 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1639 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1640 "Regexp matched against the \"From:\" header of an email or usenet message.
1641 It should match if the message is from the user him/herself."
1642 :group 'org-link-store
1643 :type 'regexp)
1645 (defcustom org-context-in-file-links t
1646 "Non-nil means file links from `org-store-link' contain context.
1647 A search string will be added to the file name with :: as separator and
1648 used to find the context when the link is activated by the command
1649 `org-open-at-point'. When this option is t, the entire active region
1650 will be placed in the search string of the file link. If set to a
1651 positive integer, only the first n lines of context will be stored.
1653 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1654 negates this setting for the duration of the command."
1655 :group 'org-link-store
1656 :type '(choice boolean integer))
1658 (defcustom org-keep-stored-link-after-insertion nil
1659 "Non-nil means keep link in list for entire session.
1661 The command `org-store-link' adds a link pointing to the current
1662 location to an internal list. These links accumulate during a session.
1663 The command `org-insert-link' can be used to insert links into any
1664 Org-mode file (offering completion for all stored links). When this
1665 option is nil, every link which has been inserted once using \\[org-insert-link]
1666 will be removed from the list, to make completing the unused links
1667 more efficient."
1668 :group 'org-link-store
1669 :type 'boolean)
1671 (defgroup org-link-follow nil
1672 "Options concerning following links in Org-mode."
1673 :tag "Org Follow Link"
1674 :group 'org-link)
1676 (defcustom org-link-translation-function nil
1677 "Function to translate links with different syntax to Org syntax.
1678 This can be used to translate links created for example by the Planner
1679 or emacs-wiki packages to Org syntax.
1680 The function must accept two parameters, a TYPE containing the link
1681 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1682 which is everything after the link protocol. It should return a cons
1683 with possibly modified values of type and path.
1684 Org contains a function for this, so if you set this variable to
1685 `org-translate-link-from-planner', you should be able follow many
1686 links created by planner."
1687 :group 'org-link-follow
1688 :type 'function)
1690 (defcustom org-follow-link-hook nil
1691 "Hook that is run after a link has been followed."
1692 :group 'org-link-follow
1693 :type 'hook)
1695 (defcustom org-tab-follows-link nil
1696 "Non-nil means on links TAB will follow the link.
1697 Needs to be set before org.el is loaded.
1698 This really should not be used, it does not make sense, and the
1699 implementation is bad."
1700 :group 'org-link-follow
1701 :type 'boolean)
1703 (defcustom org-return-follows-link nil
1704 "Non-nil means on links RET will follow the link.
1705 In tables, the special behavior of RET has precedence."
1706 :group 'org-link-follow
1707 :type 'boolean)
1709 (defcustom org-mouse-1-follows-link
1710 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1711 "Non-nil means mouse-1 on a link will follow the link.
1712 A longer mouse click will still set point. Does not work on XEmacs.
1713 Needs to be set before org.el is loaded."
1714 :group 'org-link-follow
1715 :type 'boolean)
1717 (defcustom org-mark-ring-length 4
1718 "Number of different positions to be recorded in the ring.
1719 Changing this requires a restart of Emacs to work correctly."
1720 :group 'org-link-follow
1721 :type 'integer)
1723 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1724 "Non-nil means internal links in Org files must exactly match a headline.
1725 When nil, the link search tries to match a phrase with all words
1726 in the search text."
1727 :group 'org-link-follow
1728 :version "24.1"
1729 :type '(choice
1730 (const :tag "Use fuzzy text search" nil)
1731 (const :tag "Match only exact headline" t)
1732 (const :tag "Match exact headline or query to create it"
1733 query-to-create)))
1735 (defcustom org-link-frame-setup
1736 '((vm . vm-visit-folder-other-frame)
1737 (vm-imap . vm-visit-imap-folder-other-frame)
1738 (gnus . org-gnus-no-new-news)
1739 (file . find-file-other-window)
1740 (wl . wl-other-frame))
1741 "Setup the frame configuration for following links.
1742 When following a link with Emacs, it may often be useful to display
1743 this link in another window or frame. This variable can be used to
1744 set this up for the different types of links.
1745 For VM, use any of
1746 `vm-visit-folder'
1747 `vm-visit-folder-other-window'
1748 `vm-visit-folder-other-frame'
1749 For Gnus, use any of
1750 `gnus'
1751 `gnus-other-frame'
1752 `org-gnus-no-new-news'
1753 For FILE, use any of
1754 `find-file'
1755 `find-file-other-window'
1756 `find-file-other-frame'
1757 For Wanderlust use any of
1758 `wl'
1759 `wl-other-frame'
1760 For the calendar, use the variable `calendar-setup'.
1761 For BBDB, it is currently only possible to display the matches in
1762 another window."
1763 :group 'org-link-follow
1764 :type '(list
1765 (cons (const vm)
1766 (choice
1767 (const vm-visit-folder)
1768 (const vm-visit-folder-other-window)
1769 (const vm-visit-folder-other-frame)))
1770 (cons (const gnus)
1771 (choice
1772 (const gnus)
1773 (const gnus-other-frame)
1774 (const org-gnus-no-new-news)))
1775 (cons (const file)
1776 (choice
1777 (const find-file)
1778 (const find-file-other-window)
1779 (const find-file-other-frame)))
1780 (cons (const wl)
1781 (choice
1782 (const wl)
1783 (const wl-other-frame)))))
1785 (defcustom org-display-internal-link-with-indirect-buffer nil
1786 "Non-nil means use indirect buffer to display infile links.
1787 Activating internal links (from one location in a file to another location
1788 in the same file) normally just jumps to the location. When the link is
1789 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1790 is displayed in
1791 another window. When this option is set, the other window actually displays
1792 an indirect buffer clone of the current buffer, to avoid any visibility
1793 changes to the current buffer."
1794 :group 'org-link-follow
1795 :type 'boolean)
1797 (defcustom org-open-non-existing-files nil
1798 "Non-nil means `org-open-file' will open non-existing files.
1799 When nil, an error will be generated.
1800 This variable applies only to external applications because they
1801 might choke on non-existing files. If the link is to a file that
1802 will be opened in Emacs, the variable is ignored."
1803 :group 'org-link-follow
1804 :type 'boolean)
1806 (defcustom org-open-directory-means-index-dot-org nil
1807 "Non-nil means a link to a directory really means to index.org.
1808 When nil, following a directory link will run dired or open a finder/explorer
1809 window on that directory."
1810 :group 'org-link-follow
1811 :type 'boolean)
1813 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1814 "Function and arguments to call for following mailto links.
1815 This is a list with the first element being a Lisp function, and the
1816 remaining elements being arguments to the function. In string arguments,
1817 %a will be replaced by the address, and %s will be replaced by the subject
1818 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1819 :group 'org-link-follow
1820 :type '(choice
1821 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1822 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1823 (const :tag "message-mail" (message-mail "%a" "%s"))
1824 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1826 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1827 "Non-nil means ask for confirmation before executing shell links.
1828 Shell links can be dangerous: just think about a link
1830 [[shell:rm -rf ~/*][Google Search]]
1832 This link would show up in your Org-mode document as \"Google Search\",
1833 but really it would remove your entire home directory.
1834 Therefore we advise against setting this variable to nil.
1835 Just change it to `y-or-n-p' if you want to confirm with a
1836 single keystroke rather than having to type \"yes\"."
1837 :group 'org-link-follow
1838 :type '(choice
1839 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1840 (const :tag "with y-or-n (faster)" y-or-n-p)
1841 (const :tag "no confirmation (dangerous)" nil)))
1842 (put 'org-confirm-shell-link-function
1843 'safe-local-variable
1844 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1846 (defcustom org-confirm-shell-link-not-regexp ""
1847 "A regexp to skip confirmation for shell links."
1848 :group 'org-link-follow
1849 :version "24.1"
1850 :type 'regexp)
1852 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1853 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1854 Elisp links can be dangerous: just think about a link
1856 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1858 This link would show up in your Org-mode document as \"Google Search\",
1859 but really it would remove your entire home directory.
1860 Therefore we advise against setting this variable to nil.
1861 Just change it to `y-or-n-p' if you want to confirm with a
1862 single keystroke rather than having to type \"yes\"."
1863 :group 'org-link-follow
1864 :type '(choice
1865 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1866 (const :tag "with y-or-n (faster)" y-or-n-p)
1867 (const :tag "no confirmation (dangerous)" nil)))
1868 (put 'org-confirm-shell-link-function
1869 'safe-local-variable
1870 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1872 (defcustom org-confirm-elisp-link-not-regexp ""
1873 "A regexp to skip confirmation for Elisp links."
1874 :group 'org-link-follow
1875 :version "24.1"
1876 :type 'regexp)
1878 (defconst org-file-apps-defaults-gnu
1879 '((remote . emacs)
1880 (system . mailcap)
1881 (t . mailcap))
1882 "Default file applications on a UNIX or GNU/Linux system.
1883 See `org-file-apps'.")
1885 (defconst org-file-apps-defaults-macosx
1886 '((remote . emacs)
1887 (t . "open %s")
1888 (system . "open %s")
1889 ("ps.gz" . "gv %s")
1890 ("eps.gz" . "gv %s")
1891 ("dvi" . "xdvi %s")
1892 ("fig" . "xfig %s"))
1893 "Default file applications on a MacOS X system.
1894 The system \"open\" is known as a default, but we use X11 applications
1895 for some files for which the OS does not have a good default.
1896 See `org-file-apps'.")
1898 (defconst org-file-apps-defaults-windowsnt
1899 (list
1900 '(remote . emacs)
1901 (cons t
1902 (list (if (featurep 'xemacs)
1903 'mswindows-shell-execute
1904 'w32-shell-execute)
1905 "open" 'file))
1906 (cons 'system
1907 (list (if (featurep 'xemacs)
1908 'mswindows-shell-execute
1909 'w32-shell-execute)
1910 "open" 'file)))
1911 "Default file applications on a Windows NT system.
1912 The system \"open\" is used for most files.
1913 See `org-file-apps'.")
1915 (defcustom org-file-apps
1916 '((auto-mode . emacs)
1917 ("\\.mm\\'" . default)
1918 ("\\.x?html?\\'" . default)
1919 ("\\.pdf\\'" . default))
1920 "External applications for opening `file:path' items in a document.
1921 Org-mode uses system defaults for different file types, but
1922 you can use this variable to set the application for a given file
1923 extension. The entries in this list are cons cells where the car identifies
1924 files and the cdr the corresponding command. Possible values for the
1925 file identifier are
1926 \"string\" A string as a file identifier can be interpreted in different
1927 ways, depending on its contents:
1929 - Alphanumeric characters only:
1930 Match links with this file extension.
1931 Example: (\"pdf\" . \"evince %s\")
1932 to open PDFs with evince.
1934 - Regular expression: Match links where the
1935 filename matches the regexp. If you want to
1936 use groups here, use shy groups.
1938 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1939 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1940 to open *.html and *.xhtml with firefox.
1942 - Regular expression which contains (non-shy) groups:
1943 Match links where the whole link, including \"::\", and
1944 anything after that, matches the regexp.
1945 In a custom command string, %1, %2, etc. are replaced with
1946 the parts of the link that were matched by the groups.
1947 For backwards compatibility, if a command string is given
1948 that does not use any of the group matches, this case is
1949 handled identically to the second one (i.e. match against
1950 file name only).
1951 In a custom lisp form, you can access the group matches with
1952 (match-string n link).
1954 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1955 to open [[file:document.pdf::5]] with evince at page 5.
1957 `directory' Matches a directory
1958 `remote' Matches a remote file, accessible through tramp or efs.
1959 Remote files most likely should be visited through Emacs
1960 because external applications cannot handle such paths.
1961 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1962 so all files Emacs knows how to handle. Using this with
1963 command `emacs' will open most files in Emacs. Beware that this
1964 will also open html files inside Emacs, unless you add
1965 (\"html\" . default) to the list as well.
1966 t Default for files not matched by any of the other options.
1967 `system' The system command to open files, like `open' on Windows
1968 and Mac OS X, and mailcap under GNU/Linux. This is the command
1969 that will be selected if you call `C-c C-o' with a double
1970 \\[universal-argument] \\[universal-argument] prefix.
1972 Possible values for the command are:
1973 `emacs' The file will be visited by the current Emacs process.
1974 `default' Use the default application for this file type, which is the
1975 association for t in the list, most likely in the system-specific
1976 part.
1977 This can be used to overrule an unwanted setting in the
1978 system-specific variable.
1979 `system' Use the system command for opening files, like \"open\".
1980 This command is specified by the entry whose car is `system'.
1981 Most likely, the system-specific version of this variable
1982 does define this command, but you can overrule/replace it
1983 here.
1984 string A command to be executed by a shell; %s will be replaced
1985 by the path to the file.
1986 sexp A Lisp form which will be evaluated. The file path will
1987 be available in the Lisp variable `file'.
1988 For more examples, see the system specific constants
1989 `org-file-apps-defaults-macosx'
1990 `org-file-apps-defaults-windowsnt'
1991 `org-file-apps-defaults-gnu'."
1992 :group 'org-link-follow
1993 :type '(repeat
1994 (cons (choice :value ""
1995 (string :tag "Extension")
1996 (const :tag "System command to open files" system)
1997 (const :tag "Default for unrecognized files" t)
1998 (const :tag "Remote file" remote)
1999 (const :tag "Links to a directory" directory)
2000 (const :tag "Any files that have Emacs modes"
2001 auto-mode))
2002 (choice :value ""
2003 (const :tag "Visit with Emacs" emacs)
2004 (const :tag "Use default" default)
2005 (const :tag "Use the system command" system)
2006 (string :tag "Command")
2007 (sexp :tag "Lisp form")))))
2009 (defcustom org-doi-server-url "http://dx.doi.org/"
2010 "The URL of the DOI server."
2011 :type 'string
2012 :version "24.3"
2013 :group 'org-link-follow)
2015 (defgroup org-refile nil
2016 "Options concerning refiling entries in Org-mode."
2017 :tag "Org Refile"
2018 :group 'org)
2020 (defcustom org-directory "~/org"
2021 "Directory with org files.
2022 This is just a default location to look for Org files. There is no need
2023 at all to put your files into this directory. It is only used in the
2024 following situations:
2026 1. When a capture template specifies a target file that is not an
2027 absolute path. The path will then be interpreted relative to
2028 `org-directory'
2029 2. When a capture note is filed away in an interactive way (when exiting the
2030 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2031 with `org-directory' as the default path."
2032 :group 'org-refile
2033 :group 'org-remember
2034 :group 'org-capture
2035 :type 'directory)
2037 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2038 "Default target for storing notes.
2039 Used as a fall back file for org-remember.el and org-capture.el, for
2040 templates that do not specify a target file."
2041 :group 'org-refile
2042 :group 'org-remember
2043 :group 'org-capture
2044 :type '(choice
2045 (const :tag "Default from remember-data-file" nil)
2046 file))
2048 (defcustom org-goto-interface 'outline
2049 "The default interface to be used for `org-goto'.
2050 Allowed values are:
2051 outline The interface shows an outline of the relevant file
2052 and the correct heading is found by moving through
2053 the outline or by searching with incremental search.
2054 outline-path-completion Headlines in the current buffer are offered via
2055 completion. This is the interface also used by
2056 the refile command."
2057 :group 'org-refile
2058 :type '(choice
2059 (const :tag "Outline" outline)
2060 (const :tag "Outline-path-completion" outline-path-completion)))
2062 (defcustom org-goto-max-level 5
2063 "Maximum target level when running `org-goto' with refile interface."
2064 :group 'org-refile
2065 :type 'integer)
2067 (defcustom org-reverse-note-order nil
2068 "Non-nil means store new notes at the beginning of a file or entry.
2069 When nil, new notes will be filed to the end of a file or entry.
2070 This can also be a list with cons cells of regular expressions that
2071 are matched against file names, and values."
2072 :group 'org-remember
2073 :group 'org-capture
2074 :group 'org-refile
2075 :type '(choice
2076 (const :tag "Reverse always" t)
2077 (const :tag "Reverse never" nil)
2078 (repeat :tag "By file name regexp"
2079 (cons regexp boolean))))
2081 (defcustom org-log-refile nil
2082 "Information to record when a task is refiled.
2084 Possible values are:
2086 nil Don't add anything
2087 time Add a time stamp to the task
2088 note Prompt for a note and add it with template `org-log-note-headings'
2090 This option can also be set with on a per-file-basis with
2092 #+STARTUP: nologrefile
2093 #+STARTUP: logrefile
2094 #+STARTUP: lognoterefile
2096 You can have local logging settings for a subtree by setting the LOGGING
2097 property to one or more of these keywords.
2099 When bulk-refiling from the agenda, the value `note' is forbidden and
2100 will temporarily be changed to `time'."
2101 :group 'org-refile
2102 :group 'org-progress
2103 :version "24.1"
2104 :type '(choice
2105 (const :tag "No logging" nil)
2106 (const :tag "Record timestamp" time)
2107 (const :tag "Record timestamp with note." note)))
2109 (defcustom org-refile-targets nil
2110 "Targets for refiling entries with \\[org-refile].
2111 This is a list of cons cells. Each cell contains:
2112 - a specification of the files to be considered, either a list of files,
2113 or a symbol whose function or variable value will be used to retrieve
2114 a file name or a list of file names. If you use `org-agenda-files' for
2115 that, all agenda files will be scanned for targets. Nil means consider
2116 headings in the current buffer.
2117 - A specification of how to find candidate refile targets. This may be
2118 any of:
2119 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2120 This tag has to be present in all target headlines, inheritance will
2121 not be considered.
2122 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2123 todo keyword.
2124 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2125 headlines that are refiling targets.
2126 - a cons cell (:level . N). Any headline of level N is considered a target.
2127 Note that, when `org-odd-levels-only' is set, level corresponds to
2128 order in hierarchy, not to the number of stars.
2129 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2130 Note that, when `org-odd-levels-only' is set, level corresponds to
2131 order in hierarchy, not to the number of stars.
2133 Each element of this list generates a set of possible targets.
2134 The union of these sets is presented (with completion) to
2135 the user by `org-refile'.
2137 You can set the variable `org-refile-target-verify-function' to a function
2138 to verify each headline found by the simple criteria above.
2140 When this variable is nil, all top-level headlines in the current buffer
2141 are used, equivalent to the value `((nil . (:level . 1))'."
2142 :group 'org-refile
2143 :type '(repeat
2144 (cons
2145 (choice :value org-agenda-files
2146 (const :tag "All agenda files" org-agenda-files)
2147 (const :tag "Current buffer" nil)
2148 (function) (variable) (file))
2149 (choice :tag "Identify target headline by"
2150 (cons :tag "Specific tag" (const :value :tag) (string))
2151 (cons :tag "TODO keyword" (const :value :todo) (string))
2152 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2153 (cons :tag "Level number" (const :value :level) (integer))
2154 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2156 (defcustom org-refile-target-verify-function nil
2157 "Function to verify if the headline at point should be a refile target.
2158 The function will be called without arguments, with point at the
2159 beginning of the headline. It should return t and leave point
2160 where it is if the headline is a valid target for refiling.
2162 If the target should not be selected, the function must return nil.
2163 In addition to this, it may move point to a place from where the search
2164 should be continued. For example, the function may decide that the entire
2165 subtree of the current entry should be excluded and move point to the end
2166 of the subtree."
2167 :group 'org-refile
2168 :type 'function)
2170 (defcustom org-refile-use-cache nil
2171 "Non-nil means cache refile targets to speed up the process.
2172 The cache for a particular file will be updated automatically when
2173 the buffer has been killed, or when any of the marker used for flagging
2174 refile targets no longer points at a live buffer.
2175 If you have added new entries to a buffer that might themselves be targets,
2176 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2177 find that easier, `C-u C-u C-u C-c C-w'."
2178 :group 'org-refile
2179 :version "24.1"
2180 :type 'boolean)
2182 (defcustom org-refile-use-outline-path nil
2183 "Non-nil means provide refile targets as paths.
2184 So a level 3 headline will be available as level1/level2/level3.
2186 When the value is `file', also include the file name (without directory)
2187 into the path. In this case, you can also stop the completion after
2188 the file name, to get entries inserted as top level in the file.
2190 When `full-file-path', include the full file path."
2191 :group 'org-refile
2192 :type '(choice
2193 (const :tag "Not" nil)
2194 (const :tag "Yes" t)
2195 (const :tag "Start with file name" file)
2196 (const :tag "Start with full file path" full-file-path)))
2198 (defcustom org-outline-path-complete-in-steps t
2199 "Non-nil means complete the outline path in hierarchical steps.
2200 When Org-mode uses the refile interface to select an outline path
2201 \(see variable `org-refile-use-outline-path'), the completion of
2202 the path can be done is a single go, or if can be done in steps down
2203 the headline hierarchy. Going in steps is probably the best if you
2204 do not use a special completion package like `ido' or `icicles'.
2205 However, when using these packages, going in one step can be very
2206 fast, while still showing the whole path to the entry."
2207 :group 'org-refile
2208 :type 'boolean)
2210 (defcustom org-refile-allow-creating-parent-nodes nil
2211 "Non-nil means allow to create new nodes as refile targets.
2212 New nodes are then created by adding \"/new node name\" to the completion
2213 of an existing node. When the value of this variable is `confirm',
2214 new node creation must be confirmed by the user (recommended)
2215 When nil, the completion must match an existing entry.
2217 Note that, if the new heading is not seen by the criteria
2218 listed in `org-refile-targets', multiple instances of the same
2219 heading would be created by trying again to file under the new
2220 heading."
2221 :group 'org-refile
2222 :type '(choice
2223 (const :tag "Never" nil)
2224 (const :tag "Always" t)
2225 (const :tag "Prompt for confirmation" confirm)))
2227 (defcustom org-refile-active-region-within-subtree nil
2228 "Non-nil means also refile active region within a subtree.
2230 By default `org-refile' doesn't allow refiling regions if they
2231 don't contain a set of subtrees, but it might be convenient to
2232 do so sometimes: in that case, the first line of the region is
2233 converted to a headline before refiling."
2234 :group 'org-refile
2235 :version "24.1"
2236 :type 'boolean)
2238 (defgroup org-todo nil
2239 "Options concerning TODO items in Org-mode."
2240 :tag "Org TODO"
2241 :group 'org)
2243 (defgroup org-progress nil
2244 "Options concerning Progress logging in Org-mode."
2245 :tag "Org Progress"
2246 :group 'org-time)
2248 (defvar org-todo-interpretation-widgets
2249 '((:tag "Sequence (cycling hits every state)" sequence)
2250 (:tag "Type (cycling directly to DONE)" type))
2251 "The available interpretation symbols for customizing `org-todo-keywords'.
2252 Interested libraries should add to this list.")
2254 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2255 "List of TODO entry keyword sequences and their interpretation.
2256 \\<org-mode-map>This is a list of sequences.
2258 Each sequence starts with a symbol, either `sequence' or `type',
2259 indicating if the keywords should be interpreted as a sequence of
2260 action steps, or as different types of TODO items. The first
2261 keywords are states requiring action - these states will select a headline
2262 for inclusion into the global TODO list Org-mode produces. If one of
2263 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2264 signify that no further action is necessary. If \"|\" is not found,
2265 the last keyword is treated as the only DONE state of the sequence.
2267 The command \\[org-todo] cycles an entry through these states, and one
2268 additional state where no keyword is present. For details about this
2269 cycling, see the manual.
2271 TODO keywords and interpretation can also be set on a per-file basis with
2272 the special #+SEQ_TODO and #+TYP_TODO lines.
2274 Each keyword can optionally specify a character for fast state selection
2275 \(in combination with the variable `org-use-fast-todo-selection')
2276 and specifiers for state change logging, using the same syntax that
2277 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2278 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2279 indicates to record a time stamp each time this state is selected.
2281 Each keyword may also specify if a timestamp or a note should be
2282 recorded when entering or leaving the state, by adding additional
2283 characters in the parenthesis after the keyword. This looks like this:
2284 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2285 record only the time of the state change. With X and Y being either
2286 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2287 Y when leaving the state if and only if the *target* state does not
2288 define X. You may omit any of the fast-selection key or X or /Y,
2289 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2291 For backward compatibility, this variable may also be just a list
2292 of keywords. In this case the interpretation (sequence or type) will be
2293 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2294 :group 'org-todo
2295 :group 'org-keywords
2296 :type '(choice
2297 (repeat :tag "Old syntax, just keywords"
2298 (string :tag "Keyword"))
2299 (repeat :tag "New syntax"
2300 (cons
2301 (choice
2302 :tag "Interpretation"
2303 ;;Quick and dirty way to see
2304 ;;`org-todo-interpretations'. This takes the
2305 ;;place of item arguments
2306 :convert-widget
2307 (lambda (widget)
2308 (widget-put widget
2309 :args (mapcar
2310 #'(lambda (x)
2311 (widget-convert
2312 (cons 'const x)))
2313 org-todo-interpretation-widgets))
2314 widget))
2315 (repeat
2316 (string :tag "Keyword"))))))
2318 (defvar org-todo-keywords-1 nil
2319 "All TODO and DONE keywords active in a buffer.")
2320 (make-variable-buffer-local 'org-todo-keywords-1)
2321 (defvar org-todo-keywords-for-agenda nil)
2322 (defvar org-done-keywords-for-agenda nil)
2323 (defvar org-drawers-for-agenda nil)
2324 (defvar org-todo-keyword-alist-for-agenda nil)
2325 (defvar org-tag-alist-for-agenda nil
2326 "Alist of all tags from all agenda files.")
2327 (defvar org-tag-groups-alist-for-agenda nil
2328 "Alist of all groups tags from all current agenda files.")
2329 (defvar org-tag-groups-alist nil)
2330 (make-variable-buffer-local 'org-tag-groups-alist)
2331 (defvar org-agenda-contributing-files nil)
2332 (defvar org-not-done-keywords nil)
2333 (make-variable-buffer-local 'org-not-done-keywords)
2334 (defvar org-done-keywords nil)
2335 (make-variable-buffer-local 'org-done-keywords)
2336 (defvar org-todo-heads nil)
2337 (make-variable-buffer-local 'org-todo-heads)
2338 (defvar org-todo-sets nil)
2339 (make-variable-buffer-local 'org-todo-sets)
2340 (defvar org-todo-log-states nil)
2341 (make-variable-buffer-local 'org-todo-log-states)
2342 (defvar org-todo-kwd-alist nil)
2343 (make-variable-buffer-local 'org-todo-kwd-alist)
2344 (defvar org-todo-key-alist nil)
2345 (make-variable-buffer-local 'org-todo-key-alist)
2346 (defvar org-todo-key-trigger nil)
2347 (make-variable-buffer-local 'org-todo-key-trigger)
2349 (defcustom org-todo-interpretation 'sequence
2350 "Controls how TODO keywords are interpreted.
2351 This variable is in principle obsolete and is only used for
2352 backward compatibility, if the interpretation of todo keywords is
2353 not given already in `org-todo-keywords'. See that variable for
2354 more information."
2355 :group 'org-todo
2356 :group 'org-keywords
2357 :type '(choice (const sequence)
2358 (const type)))
2360 (defcustom org-use-fast-todo-selection t
2361 "Non-nil means use the fast todo selection scheme with C-c C-t.
2362 This variable describes if and under what circumstances the cycling
2363 mechanism for TODO keywords will be replaced by a single-key, direct
2364 selection scheme.
2366 When nil, fast selection is never used.
2368 When the symbol `prefix', it will be used when `org-todo' is called
2369 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2370 `C-u t' in an agenda buffer.
2372 When t, fast selection is used by default. In this case, the prefix
2373 argument forces cycling instead.
2375 In all cases, the special interface is only used if access keys have
2376 actually been assigned by the user, i.e. if keywords in the configuration
2377 are followed by a letter in parenthesis, like TODO(t)."
2378 :group 'org-todo
2379 :type '(choice
2380 (const :tag "Never" nil)
2381 (const :tag "By default" t)
2382 (const :tag "Only with C-u C-c C-t" prefix)))
2384 (defcustom org-provide-todo-statistics t
2385 "Non-nil means update todo statistics after insert and toggle.
2386 ALL-HEADLINES means update todo statistics by including headlines
2387 with no TODO keyword as well, counting them as not done.
2388 A list of TODO keywords means the same, but skip keywords that are
2389 not in this list.
2391 When this is set, todo statistics is updated in the parent of the
2392 current entry each time a todo state is changed."
2393 :group 'org-todo
2394 :type '(choice
2395 (const :tag "Yes, only for TODO entries" t)
2396 (const :tag "Yes, including all entries" 'all-headlines)
2397 (repeat :tag "Yes, for TODOs in this list"
2398 (string :tag "TODO keyword"))
2399 (other :tag "No TODO statistics" nil)))
2401 (defcustom org-hierarchical-todo-statistics t
2402 "Non-nil means TODO statistics covers just direct children.
2403 When nil, all entries in the subtree are considered.
2404 This has only an effect if `org-provide-todo-statistics' is set.
2405 To set this to nil for only a single subtree, use a COOKIE_DATA
2406 property and include the word \"recursive\" into the value."
2407 :group 'org-todo
2408 :type 'boolean)
2410 (defcustom org-after-todo-state-change-hook nil
2411 "Hook which is run after the state of a TODO item was changed.
2412 The new state (a string with a TODO keyword, or nil) is available in the
2413 Lisp variable `org-state'."
2414 :group 'org-todo
2415 :type 'hook)
2417 (defvar org-blocker-hook nil
2418 "Hook for functions that are allowed to block a state change.
2420 Functions in this hook should not modify the buffer.
2421 Each function gets as its single argument a property list,
2422 see `org-trigger-hook' for more information about this list.
2424 If any of the functions in this hook returns nil, the state change
2425 is blocked.")
2427 (defvar org-trigger-hook nil
2428 "Hook for functions that are triggered by a state change.
2430 Each function gets as its single argument a property list with at
2431 least the following elements:
2433 (:type type-of-change :position pos-at-entry-start
2434 :from old-state :to new-state)
2436 Depending on the type, more properties may be present.
2438 This mechanism is currently implemented for:
2440 TODO state changes
2441 ------------------
2442 :type todo-state-change
2443 :from previous state (keyword as a string), or nil, or a symbol
2444 'todo' or 'done', to indicate the general type of state.
2445 :to new state, like in :from")
2447 (defcustom org-enforce-todo-dependencies nil
2448 "Non-nil means undone TODO entries will block switching the parent to DONE.
2449 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2450 be blocked if any prior sibling is not yet done.
2451 Finally, if the parent is blocked because of ordered siblings of its own,
2452 the child will also be blocked."
2453 :set (lambda (var val)
2454 (set var val)
2455 (if val
2456 (add-hook 'org-blocker-hook
2457 'org-block-todo-from-children-or-siblings-or-parent)
2458 (remove-hook 'org-blocker-hook
2459 'org-block-todo-from-children-or-siblings-or-parent)))
2460 :group 'org-todo
2461 :type 'boolean)
2463 (defcustom org-enforce-todo-checkbox-dependencies nil
2464 "Non-nil means unchecked boxes will block switching the parent to DONE.
2465 When this is nil, checkboxes have no influence on switching TODO states.
2466 When non-nil, you first need to check off all check boxes before the TODO
2467 entry can be switched to DONE.
2468 This variable needs to be set before org.el is loaded, and you need to
2469 restart Emacs after a change to make the change effective. The only way
2470 to change is while Emacs is running is through the customize interface."
2471 :set (lambda (var val)
2472 (set var val)
2473 (if val
2474 (add-hook 'org-blocker-hook
2475 'org-block-todo-from-checkboxes)
2476 (remove-hook 'org-blocker-hook
2477 'org-block-todo-from-checkboxes)))
2478 :group 'org-todo
2479 :type 'boolean)
2481 (defcustom org-treat-insert-todo-heading-as-state-change nil
2482 "Non-nil means inserting a TODO heading is treated as state change.
2483 So when the command \\[org-insert-todo-heading] is used, state change
2484 logging will apply if appropriate. When nil, the new TODO item will
2485 be inserted directly, and no logging will take place."
2486 :group 'org-todo
2487 :type 'boolean)
2489 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2490 "Non-nil means switching TODO states with S-cursor counts as state change.
2491 This is the default behavior. However, setting this to nil allows a
2492 convenient way to select a TODO state and bypass any logging associated
2493 with that."
2494 :group 'org-todo
2495 :type 'boolean)
2497 (defcustom org-todo-state-tags-triggers nil
2498 "Tag changes that should be triggered by TODO state changes.
2499 This is a list. Each entry is
2501 (state-change (tag . flag) .......)
2503 State-change can be a string with a state, and empty string to indicate the
2504 state that has no TODO keyword, or it can be one of the symbols `todo'
2505 or `done', meaning any not-done or done state, respectively."
2506 :group 'org-todo
2507 :group 'org-tags
2508 :type '(repeat
2509 (cons (choice :tag "When changing to"
2510 (const :tag "Not-done state" todo)
2511 (const :tag "Done state" done)
2512 (string :tag "State"))
2513 (repeat
2514 (cons :tag "Tag action"
2515 (string :tag "Tag")
2516 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2518 (defcustom org-log-done nil
2519 "Information to record when a task moves to the DONE state.
2521 Possible values are:
2523 nil Don't add anything, just change the keyword
2524 time Add a time stamp to the task
2525 note Prompt for a note and add it with template `org-log-note-headings'
2527 This option can also be set with on a per-file-basis with
2529 #+STARTUP: nologdone
2530 #+STARTUP: logdone
2531 #+STARTUP: lognotedone
2533 You can have local logging settings for a subtree by setting the LOGGING
2534 property to one or more of these keywords."
2535 :group 'org-todo
2536 :group 'org-progress
2537 :type '(choice
2538 (const :tag "No logging" nil)
2539 (const :tag "Record CLOSED timestamp" time)
2540 (const :tag "Record CLOSED timestamp with note." note)))
2542 ;; Normalize old uses of org-log-done.
2543 (cond
2544 ((eq org-log-done t) (setq org-log-done 'time))
2545 ((and (listp org-log-done) (memq 'done org-log-done))
2546 (setq org-log-done 'note)))
2548 (defcustom org-log-reschedule nil
2549 "Information to record when the scheduling date of a tasks is modified.
2551 Possible values are:
2553 nil Don't add anything, just change the date
2554 time Add a time stamp to the task
2555 note Prompt for a note and add it with template `org-log-note-headings'
2557 This option can also be set with on a per-file-basis with
2559 #+STARTUP: nologreschedule
2560 #+STARTUP: logreschedule
2561 #+STARTUP: lognotereschedule"
2562 :group 'org-todo
2563 :group 'org-progress
2564 :type '(choice
2565 (const :tag "No logging" nil)
2566 (const :tag "Record timestamp" time)
2567 (const :tag "Record timestamp with note." note)))
2569 (defcustom org-log-redeadline nil
2570 "Information to record when the deadline date of a tasks is modified.
2572 Possible values are:
2574 nil Don't add anything, just change the date
2575 time Add a time stamp to the task
2576 note Prompt for a note and add it with template `org-log-note-headings'
2578 This option can also be set with on a per-file-basis with
2580 #+STARTUP: nologredeadline
2581 #+STARTUP: logredeadline
2582 #+STARTUP: lognoteredeadline
2584 You can have local logging settings for a subtree by setting the LOGGING
2585 property to one or more of these keywords."
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-note-clock-out nil
2594 "Non-nil means record a note when clocking out of an item.
2595 This can also be configured on a per-file basis by adding one of
2596 the following lines anywhere in the buffer:
2598 #+STARTUP: lognoteclock-out
2599 #+STARTUP: nolognoteclock-out"
2600 :group 'org-todo
2601 :group 'org-progress
2602 :type 'boolean)
2604 (defcustom org-log-done-with-time t
2605 "Non-nil means the CLOSED time stamp will contain date and time.
2606 When nil, only the date will be recorded."
2607 :group 'org-progress
2608 :type 'boolean)
2610 (defcustom org-log-note-headings
2611 '((done . "CLOSING NOTE %t")
2612 (state . "State %-12s from %-12S %t")
2613 (note . "Note taken on %t")
2614 (reschedule . "Rescheduled from %S on %t")
2615 (delschedule . "Not scheduled, was %S on %t")
2616 (redeadline . "New deadline from %S on %t")
2617 (deldeadline . "Removed deadline, was %S on %t")
2618 (refile . "Refiled on %t")
2619 (clock-out . ""))
2620 "Headings for notes added to entries.
2621 The value is an alist, with the car being a symbol indicating the note
2622 context, and the cdr is the heading to be used. The heading may also be the
2623 empty string.
2624 %t in the heading will be replaced by a time stamp.
2625 %T will be an active time stamp instead the default inactive one
2626 %d will be replaced by a short-format time stamp.
2627 %D will be replaced by an active short-format time stamp.
2628 %s will be replaced by the new TODO state, in double quotes.
2629 %S will be replaced by the old TODO state, in double quotes.
2630 %u will be replaced by the user name.
2631 %U will be replaced by the full user name.
2633 In fact, it is not a good idea to change the `state' entry, because
2634 agenda log mode depends on the format of these entries."
2635 :group 'org-todo
2636 :group 'org-progress
2637 :type '(list :greedy t
2638 (cons (const :tag "Heading when closing an item" done) string)
2639 (cons (const :tag
2640 "Heading when changing todo state (todo sequence only)"
2641 state) string)
2642 (cons (const :tag "Heading when just taking a note" note) string)
2643 (cons (const :tag "Heading when clocking out" clock-out) string)
2644 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2645 (cons (const :tag "Heading when rescheduling" reschedule) string)
2646 (cons (const :tag "Heading when changing deadline" redeadline) string)
2647 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2648 (cons (const :tag "Heading when refiling" refile) string)))
2650 (unless (assq 'note org-log-note-headings)
2651 (push '(note . "%t") org-log-note-headings))
2653 (defcustom org-log-into-drawer nil
2654 "Non-nil means insert state change notes and time stamps into a drawer.
2655 When nil, state changes notes will be inserted after the headline and
2656 any scheduling and clock lines, but not inside a drawer.
2658 The value of this variable should be the name of the drawer to use.
2659 LOGBOOK is proposed as the default drawer for this purpose, you can
2660 also set this to a string to define the drawer of your choice.
2662 A value of t is also allowed, representing \"LOGBOOK\".
2664 A value of t or nil can also be set with on a per-file-basis with
2666 #+STARTUP: logdrawer
2667 #+STARTUP: nologdrawer
2669 If this variable is set, `org-log-state-notes-insert-after-drawers'
2670 will be ignored.
2672 You can set the property LOG_INTO_DRAWER to overrule this setting for
2673 a subtree."
2674 :group 'org-todo
2675 :group 'org-progress
2676 :type '(choice
2677 (const :tag "Not into a drawer" nil)
2678 (const :tag "LOGBOOK" t)
2679 (string :tag "Other")))
2681 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2683 (defun org-log-into-drawer ()
2684 "Return the value of `org-log-into-drawer', but let properties overrule.
2685 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2686 used instead of the default value."
2687 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2688 (cond
2689 ((not p) org-log-into-drawer)
2690 ((equal p "nil") nil)
2691 ((equal p "t") "LOGBOOK")
2692 (t p))))
2694 (defcustom org-log-state-notes-insert-after-drawers nil
2695 "Non-nil means insert state change notes after any drawers in entry.
2696 Only the drawers that *immediately* follow the headline and the
2697 deadline/scheduled line are skipped.
2698 When nil, insert notes right after the heading and perhaps the line
2699 with deadline/scheduling if present.
2701 This variable will have no effect if `org-log-into-drawer' is
2702 set."
2703 :group 'org-todo
2704 :group 'org-progress
2705 :type 'boolean)
2707 (defcustom org-log-states-order-reversed t
2708 "Non-nil means the latest state note will be directly after heading.
2709 When nil, the state change notes will be ordered according to time.
2711 This option can also be set with on a per-file-basis with
2713 #+STARTUP: logstatesreversed
2714 #+STARTUP: nologstatesreversed"
2715 :group 'org-todo
2716 :group 'org-progress
2717 :type 'boolean)
2719 (defcustom org-todo-repeat-to-state nil
2720 "The TODO state to which a repeater should return the repeating task.
2721 By default this is the first task in a TODO sequence, or the previous state
2722 in a TODO_TYP set. But you can specify another task here.
2723 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2724 :group 'org-todo
2725 :version "24.1"
2726 :type '(choice (const :tag "Head of sequence" nil)
2727 (string :tag "Specific state")))
2729 (defcustom org-log-repeat 'time
2730 "Non-nil means record moving through the DONE state when triggering repeat.
2731 An auto-repeating task is immediately switched back to TODO when
2732 marked DONE. If you are not logging state changes (by adding \"@\"
2733 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2734 record a closing note, there will be no record of the task moving
2735 through DONE. This variable forces taking a note anyway.
2737 nil Don't force a record
2738 time Record a time stamp
2739 note Prompt for a note and add it with template `org-log-note-headings'
2741 This option can also be set with on a per-file-basis with
2743 #+STARTUP: nologrepeat
2744 #+STARTUP: logrepeat
2745 #+STARTUP: lognoterepeat
2747 You can have local logging settings for a subtree by setting the LOGGING
2748 property to one or more of these keywords."
2749 :group 'org-todo
2750 :group 'org-progress
2751 :type '(choice
2752 (const :tag "Don't force a record" nil)
2753 (const :tag "Force recording the DONE state" time)
2754 (const :tag "Force recording a note with the DONE state" note)))
2757 (defgroup org-priorities nil
2758 "Priorities in Org-mode."
2759 :tag "Org Priorities"
2760 :group 'org-todo)
2762 (defcustom org-enable-priority-commands t
2763 "Non-nil means priority commands are active.
2764 When nil, these commands will be disabled, so that you never accidentally
2765 set a priority."
2766 :group 'org-priorities
2767 :type 'boolean)
2769 (defcustom org-highest-priority ?A
2770 "The highest priority of TODO items. A character like ?A, ?B etc.
2771 Must have a smaller ASCII number than `org-lowest-priority'."
2772 :group 'org-priorities
2773 :type 'character)
2775 (defcustom org-lowest-priority ?C
2776 "The lowest priority of TODO items. A character like ?A, ?B etc.
2777 Must have a larger ASCII number than `org-highest-priority'."
2778 :group 'org-priorities
2779 :type 'character)
2781 (defcustom org-default-priority ?B
2782 "The default priority of TODO items.
2783 This is the priority an item gets if no explicit priority is given.
2784 When starting to cycle on an empty priority the first step in the cycle
2785 depends on `org-priority-start-cycle-with-default'. The resulting first
2786 step priority must not exceed the range from `org-highest-priority' to
2787 `org-lowest-priority' which means that `org-default-priority' has to be
2788 in this range exclusive or inclusive the range boundaries. Else the
2789 first step refuses to set the default and the second will fall back
2790 to (depending on the command used) the highest or lowest priority."
2791 :group 'org-priorities
2792 :type 'character)
2794 (defcustom org-priority-start-cycle-with-default t
2795 "Non-nil means start with default priority when starting to cycle.
2796 When this is nil, the first step in the cycle will be (depending on the
2797 command used) one higher or lower than the default priority.
2798 See also `org-default-priority'."
2799 :group 'org-priorities
2800 :type 'boolean)
2802 (defcustom org-get-priority-function nil
2803 "Function to extract the priority from a string.
2804 The string is normally the headline. If this is nil Org computes the
2805 priority from the priority cookie like [#A] in the headline. It returns
2806 an integer, increasing by 1000 for each priority level.
2807 The user can set a different function here, which should take a string
2808 as an argument and return the numeric priority."
2809 :group 'org-priorities
2810 :version "24.1"
2811 :type 'function)
2813 (defgroup org-time nil
2814 "Options concerning time stamps and deadlines in Org-mode."
2815 :tag "Org Time"
2816 :group 'org)
2818 (defcustom org-insert-labeled-timestamps-at-point nil
2819 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2820 When nil, these labeled time stamps are forces into the second line of an
2821 entry, just after the headline. When scheduling from the global TODO list,
2822 the time stamp will always be forced into the second line."
2823 :group 'org-time
2824 :type 'boolean)
2826 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2827 "Formats for `format-time-string' which are used for time stamps.
2828 It is not recommended to change this constant.")
2830 (defcustom org-time-stamp-rounding-minutes '(0 5)
2831 "Number of minutes to round time stamps to.
2832 These are two values, the first applies when first creating a time stamp.
2833 The second applies when changing it with the commands `S-up' and `S-down'.
2834 When changing the time stamp, this means that it will change in steps
2835 of N minutes, as given by the second value.
2837 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2838 numbers should be factors of 60, so for example 5, 10, 15.
2840 When this is larger than 1, you can still force an exact time stamp by using
2841 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2842 and by using a prefix arg to `S-up/down' to specify the exact number
2843 of minutes to shift."
2844 :group 'org-time
2845 :get #'(lambda (var) ; Make sure both elements are there
2846 (if (integerp (default-value var))
2847 (list (default-value var) 5)
2848 (default-value var)))
2849 :type '(list
2850 (integer :tag "when inserting times")
2851 (integer :tag "when modifying times")))
2853 ;; Normalize old customizations of this variable.
2854 (when (integerp org-time-stamp-rounding-minutes)
2855 (setq org-time-stamp-rounding-minutes
2856 (list org-time-stamp-rounding-minutes
2857 org-time-stamp-rounding-minutes)))
2859 (defcustom org-display-custom-times nil
2860 "Non-nil means overlay custom formats over all time stamps.
2861 The formats are defined through the variable `org-time-stamp-custom-formats'.
2862 To turn this on on a per-file basis, insert anywhere in the file:
2863 #+STARTUP: customtime"
2864 :group 'org-time
2865 :set 'set-default
2866 :type 'sexp)
2867 (make-variable-buffer-local 'org-display-custom-times)
2869 (defcustom org-time-stamp-custom-formats
2870 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2871 "Custom formats for time stamps. See `format-time-string' for the syntax.
2872 These are overlaid over the default ISO format if the variable
2873 `org-display-custom-times' is set. Time like %H:%M should be at the
2874 end of the second format. The custom formats are also honored by export
2875 commands, if custom time display is turned on at the time of export."
2876 :group 'org-time
2877 :type 'sexp)
2879 (defun org-time-stamp-format (&optional long inactive)
2880 "Get the right format for a time string."
2881 (let ((f (if long (cdr org-time-stamp-formats)
2882 (car org-time-stamp-formats))))
2883 (if inactive
2884 (concat "[" (substring f 1 -1) "]")
2885 f)))
2887 (defcustom org-time-clocksum-format
2888 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2889 "The format string used when creating CLOCKSUM lines.
2890 This is also used when Org mode generates a time duration.
2892 The value can be a single format string containing two
2893 %-sequences, which will be filled with the number of hours and
2894 minutes in that order.
2896 Alternatively, the value can be a plist associating any of the
2897 keys :years, :months, :weeks, :days, :hours or :minutes with
2898 format strings. The time duration is formatted using only the
2899 time components that are needed and concatenating the results.
2900 If a time unit in absent, it falls back to the next smallest
2901 unit.
2903 The keys :require-years, :require-months, :require-days,
2904 :require-weeks, :require-hours, :require-minutes are also
2905 meaningful. A non-nil value for these keys indicates that the
2906 corresponding time component should always be included, even if
2907 its value is 0.
2910 For example,
2912 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2913 :require-minutes t)
2915 means durations longer than a day will be expressed in days,
2916 hours and minutes, and durations less than a day will always be
2917 expressed in hours and minutes (even for durations less than an
2918 hour).
2920 The value
2922 \(:days \"%dd\" :minutes \"%dm\")
2924 means durations longer than a day will be expressed in days and
2925 minutes, and durations less than a day will be expressed entirely
2926 in minutes (even for durations longer than an hour)."
2927 :group 'org-time
2928 :group 'org-clock
2929 :version "24.4"
2930 :package-version '(Org . "8.0")
2931 :type '(choice (string :tag "Format string")
2932 (set :tag "Plist"
2933 (group :inline t (const :tag "Years" :years)
2934 (string :tag "Format string"))
2935 (group :inline t
2936 (const :tag "Always show years" :require-years)
2937 (const t))
2938 (group :inline t (const :tag "Months" :months)
2939 (string :tag "Format string"))
2940 (group :inline t
2941 (const :tag "Always show months" :require-months)
2942 (const t))
2943 (group :inline t (const :tag "Weeks" :weeks)
2944 (string :tag "Format string"))
2945 (group :inline t
2946 (const :tag "Always show weeks" :require-weeks)
2947 (const t))
2948 (group :inline t (const :tag "Days" :days)
2949 (string :tag "Format string"))
2950 (group :inline t
2951 (const :tag "Always show days" :require-days)
2952 (const t))
2953 (group :inline t (const :tag "Hours" :hours)
2954 (string :tag "Format string"))
2955 (group :inline t
2956 (const :tag "Always show hours" :require-hours)
2957 (const t))
2958 (group :inline t (const :tag "Minutes" :minutes)
2959 (string :tag "Format string"))
2960 (group :inline t
2961 (const :tag "Always show minutes" :require-minutes)
2962 (const t)))))
2964 (defcustom org-time-clocksum-use-fractional nil
2965 "When non-nil, \\[org-clock-display] uses fractional times.
2966 See `org-time-clocksum-format' for more on time clock formats."
2967 :group 'org-time
2968 :group 'org-clock
2969 :version "24.3"
2970 :type 'boolean)
2972 (defcustom org-time-clocksum-use-effort-durations nil
2973 "When non-nil, \\[org-clock-display] uses effort durations.
2974 E.g. by default, one day is considered to be a 8 hours effort,
2975 so a task that has been clocked for 16 hours will be displayed
2976 as during 2 days in the clock display or in the clocktable.
2978 See `org-effort-durations' on how to set effort durations
2979 and `org-time-clocksum-format' for more on time clock formats."
2980 :group 'org-time
2981 :group 'org-clock
2982 :version "24.4"
2983 :package-version '(Org . "8.0")
2984 :type 'boolean)
2986 (defcustom org-time-clocksum-fractional-format "%.2f"
2987 "The format string used when creating CLOCKSUM lines,
2988 or when Org mode generates a time duration, if
2989 `org-time-clocksum-use-fractional' is enabled.
2991 The value can be a single format string containing one
2992 %-sequence, which will be filled with the number of hours as
2993 a float.
2995 Alternatively, the value can be a plist associating any of the
2996 keys :years, :months, :weeks, :days, :hours or :minutes with
2997 a format string. The time duration is formatted using the
2998 largest time unit which gives a non-zero integer part. If all
2999 specified formats have zero integer part, the smallest time unit
3000 is used."
3001 :group 'org-time
3002 :type '(choice (string :tag "Format string")
3003 (set (group :inline t (const :tag "Years" :years)
3004 (string :tag "Format string"))
3005 (group :inline t (const :tag "Months" :months)
3006 (string :tag "Format string"))
3007 (group :inline t (const :tag "Weeks" :weeks)
3008 (string :tag "Format string"))
3009 (group :inline t (const :tag "Days" :days)
3010 (string :tag "Format string"))
3011 (group :inline t (const :tag "Hours" :hours)
3012 (string :tag "Format string"))
3013 (group :inline t (const :tag "Minutes" :minutes)
3014 (string :tag "Format string")))))
3016 (defcustom org-deadline-warning-days 14
3017 "Number of days before expiration during which a deadline becomes active.
3018 This variable governs the display in sparse trees and in the agenda.
3019 When 0 or negative, it means use this number (the absolute value of it)
3020 even if a deadline has a different individual lead time specified.
3022 Custom commands can set this variable in the options section."
3023 :group 'org-time
3024 :group 'org-agenda-daily/weekly
3025 :type 'integer)
3027 (defcustom org-scheduled-delay-days 0
3028 "Number of days before a scheduled item becomes active.
3029 This variable governs the display in sparse trees and in the agenda.
3030 The default value (i.e. 0) means: don't delay scheduled item.
3031 When negative, it means use this number (the absolute value of it)
3032 even if a scheduled item has a different individual delay time
3033 specified.
3035 Custom commands can set this variable in the options section."
3036 :group 'org-time
3037 :group 'org-agenda-daily/weekly
3038 :version "24.4"
3039 :package-version '(Org . "8.0")
3040 :type 'integer)
3042 (defcustom org-read-date-prefer-future t
3043 "Non-nil means assume future for incomplete date input from user.
3044 This affects the following situations:
3045 1. The user gives a month but not a year.
3046 For example, if it is April and you enter \"feb 2\", this will be read
3047 as Feb 2, *next* year. \"May 5\", however, will be this year.
3048 2. The user gives a day, but no month.
3049 For example, if today is the 15th, and you enter \"3\", Org-mode will
3050 read this as the third of *next* month. However, if you enter \"17\",
3051 it will be considered as *this* month.
3053 If you set this variable to the symbol `time', then also the following
3054 will work:
3056 3. If the user gives a time.
3057 If the time is before now, it will be interpreted as tomorrow.
3059 Currently none of this works for ISO week specifications.
3061 When this option is nil, the current day, month and year will always be
3062 used as defaults.
3064 See also `org-agenda-jump-prefer-future'."
3065 :group 'org-time
3066 :type '(choice
3067 (const :tag "Never" nil)
3068 (const :tag "Check month and day" t)
3069 (const :tag "Check month, day, and time" time)))
3071 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3072 "Should the agenda jump command prefer the future for incomplete dates?
3073 The default is to do the same as configured in `org-read-date-prefer-future'.
3074 But you can also set a deviating value here.
3075 This may t or nil, or the symbol `org-read-date-prefer-future'."
3076 :group 'org-agenda
3077 :group 'org-time
3078 :version "24.1"
3079 :type '(choice
3080 (const :tag "Use org-read-date-prefer-future"
3081 org-read-date-prefer-future)
3082 (const :tag "Never" nil)
3083 (const :tag "Always" t)))
3085 (defcustom org-read-date-force-compatible-dates t
3086 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3088 Depending on the system Emacs is running on, certain dates cannot
3089 be represented with the type used internally to represent time.
3090 Dates between 1970-1-1 and 2038-1-1 can always be represented
3091 correctly. Some systems allow for earlier dates, some for later,
3092 some for both. One way to find out it to insert any date into an
3093 Org buffer, putting the cursor on the year and hitting S-up and
3094 S-down to test the range.
3096 When this variable is set to t, the date/time prompt will not let
3097 you specify dates outside the 1970-2037 range, so it is certain that
3098 these dates will work in whatever version of Emacs you are
3099 running, and also that you can move a file from one Emacs implementation
3100 to another. WHenever Org is forcing the year for you, it will display
3101 a message and beep.
3103 When this variable is nil, Org will check if the date is
3104 representable in the specific Emacs implementation you are using.
3105 If not, it will force a year, usually the current year, and beep
3106 to remind you. Currently this setting is not recommended because
3107 the likelihood that you will open your Org files in an Emacs that
3108 has limited date range is not negligible.
3110 A workaround for this problem is to use diary sexp dates for time
3111 stamps outside of this range."
3112 :group 'org-time
3113 :version "24.1"
3114 :type 'boolean)
3116 (defcustom org-read-date-display-live t
3117 "Non-nil means display current interpretation of date prompt live.
3118 This display will be in an overlay, in the minibuffer."
3119 :group 'org-time
3120 :type 'boolean)
3122 (defcustom org-read-date-popup-calendar t
3123 "Non-nil means pop up a calendar when prompting for a date.
3124 In the calendar, the date can be selected with mouse-1. However, the
3125 minibuffer will also be active, and you can simply enter the date as well.
3126 When nil, only the minibuffer will be available."
3127 :group 'org-time
3128 :type 'boolean)
3129 (org-defvaralias 'org-popup-calendar-for-date-prompt
3130 'org-read-date-popup-calendar)
3132 (make-obsolete-variable
3133 'org-read-date-minibuffer-setup-hook
3134 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3135 (defcustom org-read-date-minibuffer-setup-hook nil
3136 "Hook to be used to set up keys for the date/time interface.
3137 Add key definitions to `minibuffer-local-map', which will be a
3138 temporary copy.
3140 WARNING: This option is obsolete, you should use
3141 `org-read-date-minibuffer-local-map' to set up keys."
3142 :group 'org-time
3143 :type 'hook)
3145 (defcustom org-extend-today-until 0
3146 "The hour when your day really ends. Must be an integer.
3147 This has influence for the following applications:
3148 - When switching the agenda to \"today\". It it is still earlier than
3149 the time given here, the day recognized as TODAY is actually yesterday.
3150 - When a date is read from the user and it is still before the time given
3151 here, the current date and time will be assumed to be yesterday, 23:59.
3152 Also, timestamps inserted in capture templates follow this rule.
3154 IMPORTANT: This is a feature whose implementation is and likely will
3155 remain incomplete. Really, it is only here because past midnight seems to
3156 be the favorite working time of John Wiegley :-)"
3157 :group 'org-time
3158 :type 'integer)
3160 (defcustom org-use-effective-time nil
3161 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3162 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3163 \"effective time\" of any timestamps between midnight and 8am will be
3164 23:59 of the previous day."
3165 :group 'org-time
3166 :version "24.1"
3167 :type 'boolean)
3169 (defcustom org-use-last-clock-out-time-as-effective-time nil
3170 "When non-nil, use the last clock out time for `org-todo'.
3171 Note that this option has precedence over the combined use of
3172 `org-use-effective-time' and `org-extend-today-until'."
3173 :group 'org-time
3174 :version "24.4"
3175 :package-version '(Org . "8.0")
3176 :type 'boolean)
3178 (defcustom org-edit-timestamp-down-means-later nil
3179 "Non-nil means S-down will increase the time in a time stamp.
3180 When nil, S-up will increase."
3181 :group 'org-time
3182 :type 'boolean)
3184 (defcustom org-calendar-follow-timestamp-change t
3185 "Non-nil means make the calendar window follow timestamp changes.
3186 When a timestamp is modified and the calendar window is visible, it will be
3187 moved to the new date."
3188 :group 'org-time
3189 :type 'boolean)
3191 (defgroup org-tags nil
3192 "Options concerning tags in Org-mode."
3193 :tag "Org Tags"
3194 :group 'org)
3196 (defcustom org-tag-alist nil
3197 "List of tags allowed in Org-mode files.
3198 When this list is nil, Org-mode will base TAG input on what is already in the
3199 buffer.
3200 The value of this variable is an alist, the car of each entry must be a
3201 keyword as a string, the cdr may be a character that is used to select
3202 that tag through the fast-tag-selection interface.
3203 See the manual for details."
3204 :group 'org-tags
3205 :type '(repeat
3206 (choice
3207 (cons (string :tag "Tag name")
3208 (character :tag "Access char"))
3209 (list :tag "Start radio group"
3210 (const :startgroup)
3211 (option (string :tag "Group description")))
3212 (list :tag "Group tags delimiter"
3213 (const :grouptags))
3214 (list :tag "End radio group"
3215 (const :endgroup)
3216 (option (string :tag "Group description")))
3217 (const :tag "New line" (:newline)))))
3219 (defcustom org-tag-persistent-alist nil
3220 "List of tags that will always appear in all Org-mode files.
3221 This is in addition to any in buffer settings or customizations
3222 of `org-tag-alist'.
3223 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3224 The value of this variable is an alist, the car of each entry must be a
3225 keyword as a string, the cdr may be a character that is used to select
3226 that tag through the fast-tag-selection interface.
3227 See the manual for details.
3228 To disable these tags on a per-file basis, insert anywhere in the file:
3229 #+STARTUP: noptag"
3230 :group 'org-tags
3231 :type '(repeat
3232 (choice
3233 (cons (string :tag "Tag name")
3234 (character :tag "Access char"))
3235 (const :tag "Start radio group" (:startgroup))
3236 (const :tag "Group tags delimiter" (:grouptags))
3237 (const :tag "End radio group" (:endgroup))
3238 (const :tag "New line" (:newline)))))
3240 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3241 "If non-nil, always offer completion for all tags of all agenda files.
3242 Instead of customizing this variable directly, you might want to
3243 set it locally for capture buffers, because there no list of
3244 tags in that file can be created dynamically (there are none).
3246 (add-hook 'org-capture-mode-hook
3247 (lambda ()
3248 (set (make-local-variable
3249 'org-complete-tags-always-offer-all-agenda-tags)
3250 t)))"
3251 :group 'org-tags
3252 :version "24.1"
3253 :type 'boolean)
3255 (defvar org-file-tags nil
3256 "List of tags that can be inherited by all entries in the file.
3257 The tags will be inherited if the variable `org-use-tag-inheritance'
3258 says they should be.
3259 This variable is populated from #+FILETAGS lines.")
3261 (defcustom org-use-fast-tag-selection 'auto
3262 "Non-nil means use fast tag selection scheme.
3263 This is a special interface to select and deselect tags with single keys.
3264 When nil, fast selection is never used.
3265 When the symbol `auto', fast selection is used if and only if selection
3266 characters for tags have been configured, either through the variable
3267 `org-tag-alist' or through a #+TAGS line in the buffer.
3268 When t, fast selection is always used and selection keys are assigned
3269 automatically if necessary."
3270 :group 'org-tags
3271 :type '(choice
3272 (const :tag "Always" t)
3273 (const :tag "Never" nil)
3274 (const :tag "When selection characters are configured" 'auto)))
3276 (defcustom org-fast-tag-selection-single-key nil
3277 "Non-nil means fast tag selection exits after first change.
3278 When nil, you have to press RET to exit it.
3279 During fast tag selection, you can toggle this flag with `C-c'.
3280 This variable can also have the value `expert'. In this case, the window
3281 displaying the tags menu is not even shown, until you press C-c again."
3282 :group 'org-tags
3283 :type '(choice
3284 (const :tag "No" nil)
3285 (const :tag "Yes" t)
3286 (const :tag "Expert" expert)))
3288 (defvar org-fast-tag-selection-include-todo nil
3289 "Non-nil means fast tags selection interface will also offer TODO states.
3290 This is an undocumented feature, you should not rely on it.")
3292 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3293 "The column to which tags should be indented in a headline.
3294 If this number is positive, it specifies the column. If it is negative,
3295 it means that the tags should be flushright to that column. For example,
3296 -80 works well for a normal 80 character screen.
3297 When 0, place tags directly after headline text, with only one space in
3298 between."
3299 :group 'org-tags
3300 :type 'integer)
3302 (defcustom org-auto-align-tags t
3303 "Non-nil keeps tags aligned when modifying headlines.
3304 Some operations (i.e. demoting) change the length of a headline and
3305 therefore shift the tags around. With this option turned on, after
3306 each such operation the tags are again aligned to `org-tags-column'."
3307 :group 'org-tags
3308 :type 'boolean)
3310 (defcustom org-use-tag-inheritance t
3311 "Non-nil means tags in levels apply also for sublevels.
3312 When nil, only the tags directly given in a specific line apply there.
3313 This may also be a list of tags that should be inherited, or a regexp that
3314 matches tags that should be inherited. Additional control is possible
3315 with the variable `org-tags-exclude-from-inheritance' which gives an
3316 explicit list of tags to be excluded from inheritance, even if the value of
3317 `org-use-tag-inheritance' would select it for inheritance.
3319 If this option is t, a match early-on in a tree can lead to a large
3320 number of matches in the subtree when constructing the agenda or creating
3321 a sparse tree. If you only want to see the first match in a tree during
3322 a search, check out the variable `org-tags-match-list-sublevels'."
3323 :group 'org-tags
3324 :type '(choice
3325 (const :tag "Not" nil)
3326 (const :tag "Always" t)
3327 (repeat :tag "Specific tags" (string :tag "Tag"))
3328 (regexp :tag "Tags matched by regexp")))
3330 (defcustom org-tags-exclude-from-inheritance nil
3331 "List of tags that should never be inherited.
3332 This is a way to exclude a few tags from inheritance. For way to do
3333 the opposite, to actively allow inheritance for selected tags,
3334 see the variable `org-use-tag-inheritance'."
3335 :group 'org-tags
3336 :type '(repeat (string :tag "Tag")))
3338 (defun org-tag-inherit-p (tag)
3339 "Check if TAG is one that should be inherited."
3340 (cond
3341 ((member tag org-tags-exclude-from-inheritance) nil)
3342 ((eq org-use-tag-inheritance t) t)
3343 ((not org-use-tag-inheritance) nil)
3344 ((stringp org-use-tag-inheritance)
3345 (string-match org-use-tag-inheritance tag))
3346 ((listp org-use-tag-inheritance)
3347 (member tag org-use-tag-inheritance))
3348 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3350 (defcustom org-tags-match-list-sublevels t
3351 "Non-nil means list also sublevels of headlines matching a search.
3352 This variable applies to tags/property searches, and also to stuck
3353 projects because this search is based on a tags match as well.
3355 When set to the symbol `indented', sublevels are indented with
3356 leading dots.
3358 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3359 the sublevels of a headline matching a tag search often also match
3360 the same search. Listing all of them can create very long lists.
3361 Setting this variable to nil causes subtrees of a match to be skipped.
3363 This variable is semi-obsolete and probably should always be true. It
3364 is better to limit inheritance to certain tags using the variables
3365 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3366 :group 'org-tags
3367 :type '(choice
3368 (const :tag "No, don't list them" nil)
3369 (const :tag "Yes, do list them" t)
3370 (const :tag "List them, indented with leading dots" indented)))
3372 (defcustom org-tags-sort-function nil
3373 "When set, tags are sorted using this function as a comparator."
3374 :group 'org-tags
3375 :type '(choice
3376 (const :tag "No sorting" nil)
3377 (const :tag "Alphabetical" string<)
3378 (const :tag "Reverse alphabetical" string>)
3379 (function :tag "Custom function" nil)))
3381 (defvar org-tags-history nil
3382 "History of minibuffer reads for tags.")
3383 (defvar org-last-tags-completion-table nil
3384 "The last used completion table for tags.")
3385 (defvar org-after-tags-change-hook nil
3386 "Hook that is run after the tags in a line have changed.")
3388 (defgroup org-properties nil
3389 "Options concerning properties in Org-mode."
3390 :tag "Org Properties"
3391 :group 'org)
3393 (defcustom org-property-format "%-10s %s"
3394 "How property key/value pairs should be formatted by `indent-line'.
3395 When `indent-line' hits a property definition, it will format the line
3396 according to this format, mainly to make sure that the values are
3397 lined-up with respect to each other."
3398 :group 'org-properties
3399 :type 'string)
3401 (defcustom org-properties-postprocess-alist nil
3402 "Alist of properties and functions to adjust inserted values.
3403 Elements of this alist must be of the form
3405 ([string] [function])
3407 where [string] must be a property name and [function] must be a
3408 lambda expression: this lambda expression must take one argument,
3409 the value to adjust, and return the new value as a string.
3411 For example, this element will allow the property \"Remaining\"
3412 to be updated wrt the relation between the \"Effort\" property
3413 and the clock summary:
3415 ((\"Remaining\" (lambda(value)
3416 (let ((clocksum (org-clock-sum-current-item))
3417 (effort (org-duration-string-to-minutes
3418 (org-entry-get (point) \"Effort\"))))
3419 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3420 :group 'org-properties
3421 :version "24.1"
3422 :type '(alist :key-type (string :tag "Property")
3423 :value-type (function :tag "Function")))
3425 (defcustom org-use-property-inheritance nil
3426 "Non-nil means properties apply also for sublevels.
3428 This setting is chiefly used during property searches. Turning it on can
3429 cause significant overhead when doing a search, which is why it is not
3430 on by default.
3432 When nil, only the properties directly given in the current entry count.
3433 When t, every property is inherited. The value may also be a list of
3434 properties that should have inheritance, or a regular expression matching
3435 properties that should be inherited.
3437 However, note that some special properties use inheritance under special
3438 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3439 and the properties ending in \"_ALL\" when they are used as descriptor
3440 for valid values of a property.
3442 Note for programmers:
3443 When querying an entry with `org-entry-get', you can control if inheritance
3444 should be used. By default, `org-entry-get' looks only at the local
3445 properties. You can request inheritance by setting the inherit argument
3446 to t (to force inheritance) or to `selective' (to respect the setting
3447 in this variable)."
3448 :group 'org-properties
3449 :type '(choice
3450 (const :tag "Not" nil)
3451 (const :tag "Always" t)
3452 (repeat :tag "Specific properties" (string :tag "Property"))
3453 (regexp :tag "Properties matched by regexp")))
3455 (defun org-property-inherit-p (property)
3456 "Check if PROPERTY is one that should be inherited."
3457 (cond
3458 ((eq org-use-property-inheritance t) t)
3459 ((not org-use-property-inheritance) nil)
3460 ((stringp org-use-property-inheritance)
3461 (string-match org-use-property-inheritance property))
3462 ((listp org-use-property-inheritance)
3463 (member property org-use-property-inheritance))
3464 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3466 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3467 "The default column format, if no other format has been defined.
3468 This variable can be set on the per-file basis by inserting a line
3470 #+COLUMNS: %25ITEM ....."
3471 :group 'org-properties
3472 :type 'string)
3474 (defcustom org-columns-ellipses ".."
3475 "The ellipses to be used when a field in column view is truncated.
3476 When this is the empty string, as many characters as possible are shown,
3477 but then there will be no visual indication that the field has been truncated.
3478 When this is a string of length N, the last N characters of a truncated
3479 field are replaced by this string. If the column is narrower than the
3480 ellipses string, only part of the ellipses string will be shown."
3481 :group 'org-properties
3482 :type 'string)
3484 (defcustom org-columns-modify-value-for-display-function nil
3485 "Function that modifies values for display in column view.
3486 For example, it can be used to cut out a certain part from a time stamp.
3487 The function must take 2 arguments:
3489 column-title The title of the column (*not* the property name)
3490 value The value that should be modified.
3492 The function should return the value that should be displayed,
3493 or nil if the normal value should be used."
3494 :group 'org-properties
3495 :type 'function)
3497 (defcustom org-effort-property "Effort"
3498 "The property that is being used to keep track of effort estimates.
3499 Effort estimates given in this property need to have the format H:MM."
3500 :group 'org-properties
3501 :group 'org-progress
3502 :type '(string :tag "Property"))
3504 (defconst org-global-properties-fixed
3505 '(("VISIBILITY_ALL" . "folded children content all")
3506 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3507 "List of property/value pairs that can be inherited by any entry.
3509 These are fixed values, for the preset properties. The user variable
3510 that can be used to add to this list is `org-global-properties'.
3512 The entries in this list are cons cells where the car is a property
3513 name and cdr is a string with the value. If the value represents
3514 multiple items like an \"_ALL\" property, separate the items by
3515 spaces.")
3517 (defcustom org-global-properties nil
3518 "List of property/value pairs that can be inherited by any entry.
3520 This list will be combined with the constant `org-global-properties-fixed'.
3522 The entries in this list are cons cells where the car is a property
3523 name and cdr is a string with the value.
3525 You can set buffer-local values for the same purpose in the variable
3526 `org-file-properties' this by adding lines like
3528 #+PROPERTY: NAME VALUE"
3529 :group 'org-properties
3530 :type '(repeat
3531 (cons (string :tag "Property")
3532 (string :tag "Value"))))
3534 (defvar org-file-properties nil
3535 "List of property/value pairs that can be inherited by any entry.
3536 Valid for the current buffer.
3537 This variable is populated from #+PROPERTY lines.")
3538 (make-variable-buffer-local 'org-file-properties)
3540 (defgroup org-agenda nil
3541 "Options concerning agenda views in Org-mode."
3542 :tag "Org Agenda"
3543 :group 'org)
3545 (defvar org-category nil
3546 "Variable used by org files to set a category for agenda display.
3547 Such files should use a file variable to set it, for example
3549 # -*- mode: org; org-category: \"ELisp\"
3551 or contain a special line
3553 #+CATEGORY: ELisp
3555 If the file does not specify a category, then file's base name
3556 is used instead.")
3557 (make-variable-buffer-local 'org-category)
3558 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3560 (defcustom org-agenda-files nil
3561 "The files to be used for agenda display.
3562 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3563 \\[org-remove-file]. You can also use customize to edit the list.
3565 If an entry is a directory, all files in that directory that are matched by
3566 `org-agenda-file-regexp' will be part of the file list.
3568 If the value of the variable is not a list but a single file name, then
3569 the list of agenda files is actually stored and maintained in that file, one
3570 agenda file per line. In this file paths can be given relative to
3571 `org-directory'. Tilde expansion and environment variable substitution
3572 are also made."
3573 :group 'org-agenda
3574 :type '(choice
3575 (repeat :tag "List of files and directories" file)
3576 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3578 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3579 "Regular expression to match files for `org-agenda-files'.
3580 If any element in the list in that variable contains a directory instead
3581 of a normal file, all files in that directory that are matched by this
3582 regular expression will be included."
3583 :group 'org-agenda
3584 :type 'regexp)
3586 (defcustom org-agenda-text-search-extra-files nil
3587 "List of extra files to be searched by text search commands.
3588 These files will be searched in addition to the agenda files by the
3589 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3590 Note that these files will only be searched for text search commands,
3591 not for the other agenda views like todo lists, tag searches or the weekly
3592 agenda. This variable is intended to list notes and possibly archive files
3593 that should also be searched by these two commands.
3594 In fact, if the first element in the list is the symbol `agenda-archives',
3595 then all archive files of all agenda files will be added to the search
3596 scope."
3597 :group 'org-agenda
3598 :type '(set :greedy t
3599 (const :tag "Agenda Archives" agenda-archives)
3600 (repeat :inline t (file))))
3602 (org-defvaralias 'org-agenda-multi-occur-extra-files
3603 'org-agenda-text-search-extra-files)
3605 (defcustom org-agenda-skip-unavailable-files nil
3606 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3607 A nil value means to remove them, after a query, from the list."
3608 :group 'org-agenda
3609 :type 'boolean)
3611 (defcustom org-calendar-to-agenda-key [?c]
3612 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3613 The command `org-calendar-goto-agenda' will be bound to this key. The
3614 default is the character `c' because then `c' can be used to switch back and
3615 forth between agenda and calendar."
3616 :group 'org-agenda
3617 :type 'sexp)
3619 (defcustom org-calendar-insert-diary-entry-key [?i]
3620 "The key to be installed in `calendar-mode-map' for adding diary entries.
3621 This option is irrelevant until `org-agenda-diary-file' has been configured
3622 to point to an Org-mode file. When that is the case, the command
3623 `org-agenda-diary-entry' will be bound to the key given here, by default
3624 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3625 if you want to continue doing this, you need to change this to a different
3626 key."
3627 :group 'org-agenda
3628 :type 'sexp)
3630 (defcustom org-agenda-diary-file 'diary-file
3631 "File to which to add new entries with the `i' key in agenda and calendar.
3632 When this is the symbol `diary-file', the functionality in the Emacs
3633 calendar will be used to add entries to the `diary-file'. But when this
3634 points to a file, `org-agenda-diary-entry' will be used instead."
3635 :group 'org-agenda
3636 :type '(choice
3637 (const :tag "The standard Emacs diary file" diary-file)
3638 (file :tag "Special Org file diary entries")))
3640 (eval-after-load "calendar"
3641 '(progn
3642 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3643 'org-calendar-goto-agenda)
3644 (add-hook 'calendar-mode-hook
3645 (lambda ()
3646 (unless (eq org-agenda-diary-file 'diary-file)
3647 (define-key calendar-mode-map
3648 org-calendar-insert-diary-entry-key
3649 'org-agenda-diary-entry))))))
3651 (defgroup org-latex nil
3652 "Options for embedding LaTeX code into Org-mode."
3653 :tag "Org LaTeX"
3654 :group 'org)
3656 (defcustom org-format-latex-options
3657 '(:foreground default :background default :scale 1.0
3658 :html-foreground "Black" :html-background "Transparent"
3659 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3660 "Options for creating images from LaTeX fragments.
3661 This is a property list with the following properties:
3662 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3663 `default' means use the foreground of the default face.
3664 `auto' means use the foreground from the text face.
3665 :background the background color, or \"Transparent\".
3666 `default' means use the background of the default face.
3667 `auto' means use the background from the text face.
3668 :scale a scaling factor for the size of the images, to get more pixels
3669 :html-foreground, :html-background, :html-scale
3670 the same numbers for HTML export.
3671 :matchers a list indicating which matchers should be used to
3672 find LaTeX fragments. Valid members of this list are:
3673 \"begin\" find environments
3674 \"$1\" find single characters surrounded by $.$
3675 \"$\" find math expressions surrounded by $...$
3676 \"$$\" find math expressions surrounded by $$....$$
3677 \"\\(\" find math expressions surrounded by \\(...\\)
3678 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3679 :group 'org-latex
3680 :type 'plist)
3682 (defcustom org-format-latex-signal-error t
3683 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3684 When nil, just push out a message."
3685 :group 'org-latex
3686 :version "24.1"
3687 :type 'boolean)
3689 (defcustom org-latex-to-mathml-jar-file nil
3690 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3691 Use this to specify additional executable file say a jar file.
3693 When using MathToWeb as the converter, specify the full-path to
3694 your mathtoweb.jar file."
3695 :group 'org-latex
3696 :version "24.1"
3697 :type '(choice
3698 (const :tag "None" nil)
3699 (file :tag "JAR file" :must-match t)))
3701 (defcustom org-latex-to-mathml-convert-command nil
3702 "Command to convert LaTeX fragments to MathML.
3703 Replace format-specifiers in the command as noted below and use
3704 `shell-command' to convert LaTeX to MathML.
3705 %j: Executable file in fully expanded form as specified by
3706 `org-latex-to-mathml-jar-file'.
3707 %I: Input LaTeX file in fully expanded form
3708 %o: Output MathML file
3709 This command is used by `org-create-math-formula'.
3711 When using MathToWeb as the converter, set this to
3712 \"java -jar %j -unicode -force -df %o %I\"."
3713 :group 'org-latex
3714 :version "24.1"
3715 :type '(choice
3716 (const :tag "None" nil)
3717 (string :tag "\nShell command")))
3719 (defcustom org-latex-create-formula-image-program 'dvipng
3720 "Program to convert LaTeX fragments with.
3722 dvipng Process the LaTeX fragments to dvi file, then convert
3723 dvi files to png files using dvipng.
3724 This will also include processing of non-math environments.
3725 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3726 to convert pdf files to png files"
3727 :group 'org-latex
3728 :version "24.1"
3729 :type '(choice
3730 (const :tag "dvipng" dvipng)
3731 (const :tag "imagemagick" imagemagick)))
3733 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3734 "Path to store latex preview images.
3735 A relative path here creates many directories relative to the
3736 processed org files paths. An absolute path puts all preview
3737 images at the same place."
3738 :group 'org-latex
3739 :version "24.3"
3740 :type 'string)
3742 (defun org-format-latex-mathml-available-p ()
3743 "Return t if `org-latex-to-mathml-convert-command' is usable."
3744 (save-match-data
3745 (when (and (boundp 'org-latex-to-mathml-convert-command)
3746 org-latex-to-mathml-convert-command)
3747 (let ((executable (car (split-string
3748 org-latex-to-mathml-convert-command))))
3749 (when (executable-find executable)
3750 (if (string-match
3751 "%j" org-latex-to-mathml-convert-command)
3752 (file-readable-p org-latex-to-mathml-jar-file)
3753 t))))))
3755 (defcustom org-format-latex-header "\\documentclass{article}
3756 \\usepackage[usenames]{color}
3757 \\usepackage{amsmath}
3758 \\usepackage[mathscr]{eucal}
3759 \\pagestyle{empty} % do not remove
3760 \[PACKAGES]
3761 \[DEFAULT-PACKAGES]
3762 % The settings below are copied from fullpage.sty
3763 \\setlength{\\textwidth}{\\paperwidth}
3764 \\addtolength{\\textwidth}{-3cm}
3765 \\setlength{\\oddsidemargin}{1.5cm}
3766 \\addtolength{\\oddsidemargin}{-2.54cm}
3767 \\setlength{\\evensidemargin}{\\oddsidemargin}
3768 \\setlength{\\textheight}{\\paperheight}
3769 \\addtolength{\\textheight}{-\\headheight}
3770 \\addtolength{\\textheight}{-\\headsep}
3771 \\addtolength{\\textheight}{-\\footskip}
3772 \\addtolength{\\textheight}{-3cm}
3773 \\setlength{\\topmargin}{1.5cm}
3774 \\addtolength{\\topmargin}{-2.54cm}"
3775 "The document header used for processing LaTeX fragments.
3776 It is imperative that this header make sure that no page number
3777 appears on the page. The package defined in the variables
3778 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3779 will either replace the placeholder \"[PACKAGES]\" in this
3780 header, or they will be appended."
3781 :group 'org-latex
3782 :type 'string)
3784 (defun org-set-packages-alist (var val)
3785 "Set the packages alist and make sure it has 3 elements per entry."
3786 (set var (mapcar (lambda (x)
3787 (if (and (consp x) (= (length x) 2))
3788 (list (car x) (nth 1 x) t)
3790 val)))
3792 (defun org-get-packages-alist (var)
3793 "Get the packages alist and make sure it has 3 elements per entry."
3794 (mapcar (lambda (x)
3795 (if (and (consp x) (= (length x) 2))
3796 (list (car x) (nth 1 x) t)
3798 (default-value var)))
3800 (defcustom org-latex-default-packages-alist
3801 '(("AUTO" "inputenc" t)
3802 ("T1" "fontenc" t)
3803 ("" "fixltx2e" nil)
3804 ("" "graphicx" t)
3805 ("" "longtable" nil)
3806 ("" "float" nil)
3807 ("" "wrapfig" nil)
3808 ("normalem" "ulem" t)
3809 ("" "textcomp" t)
3810 ("" "marvosym" t)
3811 ("" "wasysym" t)
3812 ("" "latexsym" t)
3813 ("" "amssymb" t)
3814 ("" "amstext" nil)
3815 ("" "hyperref" nil)
3816 "\\tolerance=1000")
3817 "Alist of default packages to be inserted in the header.
3819 Change this only if one of the packages here causes an
3820 incompatibility with another package you are using.
3822 The packages in this list are needed by one part or another of
3823 Org mode to function properly:
3825 - inputenc, fontenc: for basic font and character selection
3826 - amstext: for subscript and superscript
3827 - textcomp, marvosymb, wasysym, latexsym, amssym: for various
3828 symbols used for interpreting the entities in `org-entities'.
3829 You can skip some of these packages if you don't use any of the
3830 symbols in it.
3831 - ulem: for underline and strike-through
3832 - graphicx: for including images
3833 - float, wrapfig: for figure placement
3834 - longtable: for long tables
3835 - hyperref: for cross references
3837 Therefore you should not modify this variable unless you know
3838 what you are doing. The one reason to change it anyway is that
3839 you might be loading some other package that conflicts with one
3840 of the default packages. Each cell is of the format
3841 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
3842 the package also needs to be included when compiling LaTeX
3843 snippets into images for inclusion into non-LaTeX output."
3844 :group 'org-latex
3845 :group 'org-export-latex
3846 :set 'org-set-packages-alist
3847 :get 'org-get-packages-alist
3848 :version "24.1"
3849 :type '(repeat
3850 (choice
3851 (list :tag "options/package pair"
3852 (string :tag "options")
3853 (string :tag "package")
3854 (boolean :tag "Snippet"))
3855 (string :tag "A line of LaTeX"))))
3857 (defcustom org-latex-packages-alist nil
3858 "Alist of packages to be inserted in every LaTeX header.
3860 These will be inserted after `org-latex-default-packages-alist'.
3861 Each cell is of the format:
3863 \(\"options\" \"package\" snippet-flag)
3865 SNIPPET-FLAG, when t, indicates that this package is also needed
3866 when turning LaTeX snippets into images for inclusion into
3867 non-LaTeX output.
3869 Make sure that you only list packages here which:
3871 - you want in every file
3872 - do not conflict with the setup in `org-format-latex-header'.
3873 - do not conflict with the default packages in
3874 `org-latex-default-packages-alist'."
3875 :group 'org-latex
3876 :group 'org-export-latex
3877 :set 'org-set-packages-alist
3878 :get 'org-get-packages-alist
3879 :type '(repeat
3880 (choice
3881 (list :tag "options/package pair"
3882 (string :tag "options")
3883 (string :tag "package")
3884 (boolean :tag "Snippet"))
3885 (string :tag "A line of LaTeX"))))
3887 (defgroup org-appearance nil
3888 "Settings for Org-mode appearance."
3889 :tag "Org Appearance"
3890 :group 'org)
3892 (defcustom org-level-color-stars-only nil
3893 "Non-nil means fontify only the stars in each headline.
3894 When nil, the entire headline is fontified.
3895 Changing it requires restart of `font-lock-mode' to become effective
3896 also in regions already fontified."
3897 :group 'org-appearance
3898 :type 'boolean)
3900 (defcustom org-hide-leading-stars nil
3901 "Non-nil means hide the first N-1 stars in a headline.
3902 This works by using the face `org-hide' for these stars. This
3903 face is white for a light background, and black for a dark
3904 background. You may have to customize the face `org-hide' to
3905 make this work.
3906 Changing it requires restart of `font-lock-mode' to become effective
3907 also in regions already fontified.
3908 You may also set this on a per-file basis by adding one of the following
3909 lines to the buffer:
3911 #+STARTUP: hidestars
3912 #+STARTUP: showstars"
3913 :group 'org-appearance
3914 :type 'boolean)
3916 (defcustom org-hidden-keywords nil
3917 "List of symbols corresponding to keywords to be hidden the org buffer.
3918 For example, a value '(title) for this list will make the document's title
3919 appear in the buffer without the initial #+TITLE: keyword."
3920 :group 'org-appearance
3921 :version "24.1"
3922 :type '(set (const :tag "#+AUTHOR" author)
3923 (const :tag "#+DATE" date)
3924 (const :tag "#+EMAIL" email)
3925 (const :tag "#+TITLE" title)))
3927 (defcustom org-custom-properties nil
3928 "List of properties (as strings) with a special meaning.
3929 The default use of these custom properties is to let the user
3930 hide them with `org-toggle-custom-properties-visibility'."
3931 :group 'org-properties
3932 :group 'org-appearance
3933 :version "24.3"
3934 :type '(repeat (string :tag "Property Name")))
3936 (defcustom org-fontify-done-headline nil
3937 "Non-nil means change the face of a headline if it is marked DONE.
3938 Normally, only the TODO/DONE keyword indicates the state of a headline.
3939 When this is non-nil, the headline after the keyword is set to the
3940 `org-headline-done' as an additional indication."
3941 :group 'org-appearance
3942 :type 'boolean)
3944 (defcustom org-fontify-emphasized-text t
3945 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3946 Changing this variable requires a restart of Emacs to take effect."
3947 :group 'org-appearance
3948 :type 'boolean)
3950 (defcustom org-fontify-whole-heading-line nil
3951 "Non-nil means fontify the whole line for headings.
3952 This is useful when setting a background color for the
3953 org-level-* faces."
3954 :group 'org-appearance
3955 :type 'boolean)
3957 (defcustom org-highlight-latex-and-related nil
3958 "Non-nil means highlight LaTeX related syntax in the buffer.
3959 When non nil, the value should be a list containing any of the
3960 following symbols:
3961 `latex' Highlight LaTeX snippets and environments.
3962 `script' Highlight subscript and superscript.
3963 `entities' Highlight entities."
3964 :group 'org-appearance
3965 :version "24.4"
3966 :package-version '(Org . "8.0")
3967 :type '(choice
3968 (const :tag "No highlighting" nil)
3969 (set :greedy t :tag "Highlight"
3970 (const :tag "LaTeX snippets and environments" latex)
3971 (const :tag "Subscript and superscript" script)
3972 (const :tag "Entities" entities))))
3974 (defcustom org-hide-emphasis-markers nil
3975 "Non-nil mean font-lock should hide the emphasis marker characters."
3976 :group 'org-appearance
3977 :type 'boolean)
3979 (defcustom org-pretty-entities nil
3980 "Non-nil means show entities as UTF8 characters.
3981 When nil, the \\name form remains in the buffer."
3982 :group 'org-appearance
3983 :version "24.1"
3984 :type 'boolean)
3986 (defcustom org-pretty-entities-include-sub-superscripts t
3987 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3988 :group 'org-appearance
3989 :version "24.1"
3990 :type 'boolean)
3992 (defvar org-emph-re nil
3993 "Regular expression for matching emphasis.
3994 After a match, the match groups contain these elements:
3995 0 The match of the full regular expression, including the characters
3996 before and after the proper match
3997 1 The character before the proper match, or empty at beginning of line
3998 2 The proper match, including the leading and trailing markers
3999 3 The leading marker like * or /, indicating the type of highlighting
4000 4 The text between the emphasis markers, not including the markers
4001 5 The character after the match, empty at the end of a line")
4002 (defvar org-verbatim-re nil
4003 "Regular expression for matching verbatim text.")
4004 (defvar org-emphasis-regexp-components) ; defined just below
4005 (defvar org-emphasis-alist) ; defined just below
4006 (defun org-set-emph-re (var val)
4007 "Set variable and compute the emphasis regular expression."
4008 (set var val)
4009 (when (and (boundp 'org-emphasis-alist)
4010 (boundp 'org-emphasis-regexp-components)
4011 org-emphasis-alist org-emphasis-regexp-components)
4012 (let* ((e org-emphasis-regexp-components)
4013 (pre (car e))
4014 (post (nth 1 e))
4015 (border (nth 2 e))
4016 (body (nth 3 e))
4017 (nl (nth 4 e))
4018 (body1 (concat body "*?"))
4019 (markers (mapconcat 'car org-emphasis-alist ""))
4020 (vmarkers (mapconcat
4021 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4022 org-emphasis-alist "")))
4023 ;; make sure special characters appear at the right position in the class
4024 (if (string-match "\\^" markers)
4025 (setq markers (concat (replace-match "" t t markers) "^")))
4026 (if (string-match "-" markers)
4027 (setq markers (concat (replace-match "" t t markers) "-")))
4028 (if (string-match "\\^" vmarkers)
4029 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4030 (if (string-match "-" vmarkers)
4031 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4032 (if (> nl 0)
4033 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4034 (int-to-string nl) "\\}")))
4035 ;; Make the regexp
4036 (setq org-emph-re
4037 (concat "\\([" pre "]\\|^\\)"
4038 "\\("
4039 "\\([" markers "]\\)"
4040 "\\("
4041 "[^" border "]\\|"
4042 "[^" border "]"
4043 body1
4044 "[^" border "]"
4045 "\\)"
4046 "\\3\\)"
4047 "\\([" post "]\\|$\\)"))
4048 (setq org-verbatim-re
4049 (concat "\\([" pre "]\\|^\\)"
4050 "\\("
4051 "\\([" vmarkers "]\\)"
4052 "\\("
4053 "[^" border "]\\|"
4054 "[^" border "]"
4055 body1
4056 "[^" border "]"
4057 "\\)"
4058 "\\3\\)"
4059 "\\([" post "]\\|$\\)")))))
4061 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4062 ;; set this option proved cumbersome. See this message/thread:
4063 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4064 (defvar org-emphasis-regexp-components
4065 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4066 "Components used to build the regular expression for emphasis.
4067 This is a list with five entries. Terminology: In an emphasis string
4068 like \" *strong word* \", we call the initial space PREMATCH, the final
4069 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4070 and \"trong wor\" is the body. The different components in this variable
4071 specify what is allowed/forbidden in each part:
4073 pre Chars allowed as prematch. Beginning of line will be allowed too.
4074 post Chars allowed as postmatch. End of line will be allowed too.
4075 border The chars *forbidden* as border characters.
4076 body-regexp A regexp like \".\" to match a body character. Don't use
4077 non-shy groups here, and don't allow newline here.
4078 newline The maximum number of newlines allowed in an emphasis exp.
4080 You need to reload Org or to restart Emacs after customizing this.")
4082 (defcustom org-emphasis-alist
4083 `(("*" bold)
4084 ("/" italic)
4085 ("_" underline)
4086 ("=" org-code verbatim)
4087 ("~" org-verbatim verbatim)
4088 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4089 "Alist of characters and faces to emphasize text.
4090 Text starting and ending with a special character will be emphasized,
4091 for example *bold*, _underlined_ and /italic/. This variable sets the
4092 marker characters and the face to be used by font-lock for highlighting
4093 in Org-mode Emacs buffers.
4095 You need to reload Org or to restart Emacs after customizing this."
4096 :group 'org-appearance
4097 :set 'org-set-emph-re
4098 :version "24.4"
4099 :package-version '(Org . "8.0")
4100 :type '(repeat
4101 (list
4102 (string :tag "Marker character")
4103 (choice
4104 (face :tag "Font-lock-face")
4105 (plist :tag "Face property list"))
4106 (option (const verbatim)))))
4108 (defvar org-protecting-blocks
4109 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4110 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4111 This is needed for font-lock setup.")
4113 ;;; Miscellaneous options
4115 (defgroup org-completion nil
4116 "Completion in Org-mode."
4117 :tag "Org Completion"
4118 :group 'org)
4120 (defcustom org-completion-use-ido nil
4121 "Non-nil means use ido completion wherever possible.
4122 Note that `ido-mode' must be active for this variable to be relevant.
4123 If you decide to turn this variable on, you might well want to turn off
4124 `org-outline-path-complete-in-steps'.
4125 See also `org-completion-use-iswitchb'."
4126 :group 'org-completion
4127 :type 'boolean)
4129 (defcustom org-completion-use-iswitchb nil
4130 "Non-nil means use iswitchb completion wherever possible.
4131 Note that `iswitchb-mode' must be active for this variable to be relevant.
4132 If you decide to turn this variable on, you might well want to turn off
4133 `org-outline-path-complete-in-steps'.
4134 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4135 :group 'org-completion
4136 :type 'boolean)
4138 (defcustom org-completion-fallback-command 'hippie-expand
4139 "The expansion command called by \\[pcomplete] in normal context.
4140 Normal means, no org-mode-specific context."
4141 :group 'org-completion
4142 :type 'function)
4144 ;;; Functions and variables from their packages
4145 ;; Declared here to avoid compiler warnings
4147 ;; XEmacs only
4148 (defvar outline-mode-menu-heading)
4149 (defvar outline-mode-menu-show)
4150 (defvar outline-mode-menu-hide)
4151 (defvar zmacs-regions) ; XEmacs regions
4153 ;; Emacs only
4154 (defvar mark-active)
4156 ;; Various packages
4157 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4158 (declare-function calendar-forward-day "cal-move" (arg))
4159 (declare-function calendar-goto-date "cal-move" (date))
4160 (declare-function calendar-goto-today "cal-move" ())
4161 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4162 (defvar calc-embedded-close-formula)
4163 (defvar calc-embedded-open-formula)
4164 (declare-function cdlatex-tab "ext:cdlatex" ())
4165 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4166 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4167 (defvar font-lock-unfontify-region-function)
4168 (declare-function iswitchb-read-buffer "iswitchb"
4169 (prompt &optional default require-match start matches-set))
4170 (defvar iswitchb-temp-buflist)
4171 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4172 (defvar org-agenda-tags-todo-honor-ignore-options)
4173 (declare-function org-agenda-skip "org-agenda" ())
4174 (declare-function
4175 org-agenda-format-item "org-agenda"
4176 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4177 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4178 (declare-function org-agenda-change-all-lines "org-agenda"
4179 (newhead hdmarker &optional fixface just-this))
4180 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4181 (declare-function org-agenda-maybe-redo "org-agenda" ())
4182 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4183 (beg end))
4184 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4185 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4186 "org-agenda" (&optional end))
4187 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4188 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4189 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4190 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4191 (declare-function org-indent-mode "org-indent" (&optional arg))
4192 (declare-function parse-time-string "parse-time" (string))
4193 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4194 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4195 (defvar remember-data-file)
4196 (defvar texmathp-why)
4197 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4198 (declare-function table--at-cell-p "table" (position &optional object at-column))
4200 (defvar org-latex-regexps)
4202 ;;; Autoload and prepare some org modules
4204 ;; Some table stuff that needs to be defined here, because it is used
4205 ;; by the functions setting up org-mode or checking for table context.
4207 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4208 "Detect an org-type or table-type table.")
4209 (defconst org-table-line-regexp "^[ \t]*|"
4210 "Detect an org-type table line.")
4211 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4212 "Detect an org-type table line.")
4213 (defconst org-table-hline-regexp "^[ \t]*|-"
4214 "Detect an org-type table hline.")
4215 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4216 "Detect a table-type table hline.")
4217 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4218 "Detect the first line outside a table when searching from within it.
4219 This works for both table types.")
4221 ;; Autoload the functions in org-table.el that are needed by functions here.
4223 (eval-and-compile
4224 (org-autoload "org-table"
4225 '(org-table-begin org-table-blank-field org-table-end)))
4227 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
4228 "Detect a #+TBLFM line.")
4230 ;;;###autoload
4231 (defun turn-on-orgtbl ()
4232 "Unconditionally turn on `orgtbl-mode'."
4233 (require 'org-table)
4234 (orgtbl-mode 1))
4236 (defun org-at-table-p (&optional table-type)
4237 "Return t if the cursor is inside an org-type table.
4238 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4239 (if org-enable-table-editor
4240 (save-excursion
4241 (beginning-of-line 1)
4242 (looking-at (if table-type org-table-any-line-regexp
4243 org-table-line-regexp)))
4244 nil))
4245 (defsubst org-table-p () (org-at-table-p))
4247 (defun org-at-table.el-p ()
4248 "Return t if and only if we are at a table.el table."
4249 (and (org-at-table-p 'any)
4250 (save-excursion
4251 (goto-char (org-table-begin 'any))
4252 (looking-at org-table1-hline-regexp))))
4254 (defun org-table-recognize-table.el ()
4255 "If there is a table.el table nearby, recognize it and move into it."
4256 (if org-table-tab-recognizes-table.el
4257 (if (org-at-table.el-p)
4258 (progn
4259 (beginning-of-line 1)
4260 (if (looking-at org-table-dataline-regexp)
4262 (if (looking-at org-table1-hline-regexp)
4263 (progn
4264 (beginning-of-line 2)
4265 (if (looking-at org-table-any-border-regexp)
4266 (beginning-of-line -1)))))
4267 (if (re-search-forward "|" (org-table-end t) t)
4268 (progn
4269 (require 'table)
4270 (if (table--at-cell-p (point))
4272 (message "recognizing table.el table...")
4273 (table-recognize-table)
4274 (message "recognizing table.el table...done")))
4275 (error "This should not happen"))
4277 nil)
4278 nil))
4280 (defun org-at-table-hline-p ()
4281 "Return t if the cursor is inside a hline in a table."
4282 (if org-enable-table-editor
4283 (save-excursion
4284 (beginning-of-line 1)
4285 (looking-at org-table-hline-regexp))
4286 nil))
4288 (defvar org-table-clean-did-remove-column nil)
4289 (defun org-table-map-tables (function &optional quietly)
4290 "Apply FUNCTION to the start of all tables in the buffer."
4291 (save-excursion
4292 (save-restriction
4293 (widen)
4294 (goto-char (point-min))
4295 (while (re-search-forward org-table-any-line-regexp nil t)
4296 (unless quietly
4297 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4298 (beginning-of-line 1)
4299 (when (and (looking-at org-table-line-regexp)
4300 ;; Exclude tables in src/example/verbatim/clocktable blocks
4301 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4302 (save-excursion (funcall function))
4303 (or (looking-at org-table-line-regexp)
4304 (forward-char 1)))
4305 (re-search-forward org-table-any-border-regexp nil 1))))
4306 (unless quietly (message "Mapping tables: done")))
4308 ;; Declare and autoload functions from ox.el and al.
4310 (declare-function org-export-get-environment "ox"
4311 (&optional backend subtreep ext-plist))
4312 (declare-function org-latex-guess-inputenc "ox-latex" (header))
4314 ;; Declare and autoload functions from org-agenda.el
4316 (eval-and-compile
4317 (org-autoload "org-agenda"
4318 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4320 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4321 (declare-function org-clock-update-mode-line "org-clock" ())
4322 (declare-function org-resolve-clocks "org-clock"
4323 (&optional also-non-dangling-p prompt last-valid))
4325 (defun org-at-TBLFM-p (&optional pos)
4326 "Return t when point (or POS) is in #+TBLFM line."
4327 (save-excursion
4328 (let ((pos pos)))
4329 (goto-char (or pos (point)))
4330 (beginning-of-line 1)
4331 (looking-at org-TBLFM-regexp)))
4333 (defvar org-clock-start-time)
4334 (defvar org-clock-marker (make-marker)
4335 "Marker recording the last clock-in.")
4336 (defvar org-clock-hd-marker (make-marker)
4337 "Marker recording the last clock-in, but the headline position.")
4338 (defvar org-clock-heading ""
4339 "The heading of the current clock entry.")
4340 (defun org-clock-is-active ()
4341 "Return non-nil if clock is currently running.
4342 The return value is actually the clock marker."
4343 (marker-buffer org-clock-marker))
4345 (eval-and-compile
4346 (org-autoload "org-clock" '(org-clock-remove-overlays
4347 org-clock-update-time-maybe
4348 org-clocktable-shift)))
4350 (defun org-check-running-clock ()
4351 "Check if the current buffer contains the running clock.
4352 If yes, offer to stop it and to save the buffer with the changes."
4353 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4354 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4355 (buffer-name))))
4356 (org-clock-out)
4357 (when (y-or-n-p "Save changed buffer?")
4358 (save-buffer))))
4360 (defun org-clocktable-try-shift (dir n)
4361 "Check if this line starts a clock table, if yes, shift the time block."
4362 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4363 (org-clocktable-shift dir n)))
4365 ;;;###autoload
4366 (defun org-clock-persistence-insinuate ()
4367 "Set up hooks for clock persistence."
4368 (require 'org-clock)
4369 (add-hook 'org-mode-hook 'org-clock-load)
4370 (add-hook 'kill-emacs-hook 'org-clock-save))
4372 ;; Define the variable already here, to make sure we have it.
4373 (defvar org-indent-mode nil
4374 "Non-nil if Org-Indent mode is enabled.
4375 Use the command `org-indent-mode' to change this variable.")
4377 ;; Autoload archiving code
4378 ;; The stuff that is needed for cycling and tags has to be defined here.
4380 (defgroup org-archive nil
4381 "Options concerning archiving in Org-mode."
4382 :tag "Org Archive"
4383 :group 'org-structure)
4385 (defcustom org-archive-location "%s_archive::"
4386 "The location where subtrees should be archived.
4388 The value of this variable is a string, consisting of two parts,
4389 separated by a double-colon. The first part is a filename and
4390 the second part is a headline.
4392 When the filename is omitted, archiving happens in the same file.
4393 %s in the filename will be replaced by the current file
4394 name (without the directory part). Archiving to a different file
4395 is useful to keep archived entries from contributing to the
4396 Org-mode Agenda.
4398 The archived entries will be filed as subtrees of the specified
4399 headline. When the headline is omitted, the subtrees are simply
4400 filed away at the end of the file, as top-level entries. Also in
4401 the heading you can use %s to represent the file name, this can be
4402 useful when using the same archive for a number of different files.
4404 Here are a few examples:
4405 \"%s_archive::\"
4406 If the current file is Projects.org, archive in file
4407 Projects.org_archive, as top-level trees. This is the default.
4409 \"::* Archived Tasks\"
4410 Archive in the current file, under the top-level headline
4411 \"* Archived Tasks\".
4413 \"~/org/archive.org::\"
4414 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4416 \"~/org/archive.org::* From %s\"
4417 Archive in file ~/org/archive.org (absolute path), under headlines
4418 \"From FILENAME\" where file name is the current file name.
4420 \"~/org/datetree.org::datetree/* Finished Tasks\"
4421 The \"datetree/\" string is special, signifying to archive
4422 items to the datetree. Items are placed in either the CLOSED
4423 date of the item, or the current date if there is no CLOSED date.
4424 The heading will be a subentry to the current date. There doesn't
4425 need to be a heading, but there always needs to be a slash after
4426 datetree. For example, to store archived items directly in the
4427 datetree, use \"~/org/datetree.org::datetree/\".
4429 \"basement::** Finished Tasks\"
4430 Archive in file ./basement (relative path), as level 3 trees
4431 below the level 2 heading \"** Finished Tasks\".
4433 You may set this option on a per-file basis by adding to the buffer a
4434 line like
4436 #+ARCHIVE: basement::** Finished Tasks
4438 You may also define it locally for a subtree by setting an ARCHIVE property
4439 in the entry. If such a property is found in an entry, or anywhere up
4440 the hierarchy, it will be used."
4441 :group 'org-archive
4442 :type 'string)
4444 (defcustom org-archive-tag "ARCHIVE"
4445 "The tag that marks a subtree as archived.
4446 An archived subtree does not open during visibility cycling, and does
4447 not contribute to the agenda listings.
4448 After changing this, font-lock must be restarted in the relevant buffers to
4449 get the proper fontification."
4450 :group 'org-archive
4451 :group 'org-keywords
4452 :type 'string)
4454 (defcustom org-agenda-skip-archived-trees t
4455 "Non-nil means the agenda will skip any items located in archived trees.
4456 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4457 variable is no longer recommended, you should leave it at the value t.
4458 Instead, use the key `v' to cycle the archives-mode in the agenda."
4459 :group 'org-archive
4460 :group 'org-agenda-skip
4461 :type 'boolean)
4463 (defcustom org-columns-skip-archived-trees t
4464 "Non-nil means ignore archived trees when creating column view."
4465 :group 'org-archive
4466 :group 'org-properties
4467 :type 'boolean)
4469 (defcustom org-cycle-open-archived-trees nil
4470 "Non-nil means `org-cycle' will open archived trees.
4471 An archived tree is a tree marked with the tag ARCHIVE.
4472 When nil, archived trees will stay folded. You can still open them with
4473 normal outline commands like `show-all', but not with the cycling commands."
4474 :group 'org-archive
4475 :group 'org-cycle
4476 :type 'boolean)
4478 (defcustom org-sparse-tree-open-archived-trees nil
4479 "Non-nil means sparse tree construction shows matches in archived trees.
4480 When nil, matches in these trees are highlighted, but the trees are kept in
4481 collapsed state."
4482 :group 'org-archive
4483 :group 'org-sparse-trees
4484 :type 'boolean)
4486 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4487 "The default date type when building a sparse tree.
4488 When this is nil, a date is a scheduled or a deadline timestamp.
4489 Otherwise, these types are allowed:
4491 all: all timestamps
4492 active: only active timestamps (<...>)
4493 inactive: only inactive timestamps (<...)
4494 scheduled: only scheduled timestamps
4495 deadline: only deadline timestamps"
4496 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4497 (const :tag "All timestamps" all)
4498 (const :tag "Only active timestamps" active)
4499 (const :tag "Only inactive timestamps" inactive)
4500 (const :tag "Only scheduled timestamps" scheduled)
4501 (const :tag "Only deadline timestamps" deadline)
4502 (const :tag "Only closed timestamps" closed))
4503 :version "24.3"
4504 :group 'org-sparse-trees)
4506 (defun org-cycle-hide-archived-subtrees (state)
4507 "Re-hide all archived subtrees after a visibility state change."
4508 (when (and (not org-cycle-open-archived-trees)
4509 (not (memq state '(overview folded))))
4510 (save-excursion
4511 (let* ((globalp (memq state '(contents all)))
4512 (beg (if globalp (point-min) (point)))
4513 (end (if globalp (point-max) (org-end-of-subtree t))))
4514 (org-hide-archived-subtrees beg end)
4515 (goto-char beg)
4516 (if (looking-at (concat ".*:" org-archive-tag ":"))
4517 (message "%s" (substitute-command-keys
4518 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4520 (defun org-force-cycle-archived ()
4521 "Cycle subtree even if it is archived."
4522 (interactive)
4523 (setq this-command 'org-cycle)
4524 (let ((org-cycle-open-archived-trees t))
4525 (call-interactively 'org-cycle)))
4527 (defun org-hide-archived-subtrees (beg end)
4528 "Re-hide all archived subtrees after a visibility state change."
4529 (save-excursion
4530 (let* ((re (concat ":" org-archive-tag ":")))
4531 (goto-char beg)
4532 (while (re-search-forward re end t)
4533 (when (org-at-heading-p)
4534 (org-flag-subtree t)
4535 (org-end-of-subtree t))))))
4537 (declare-function outline-end-of-heading "outline" ())
4538 (declare-function outline-flag-region "outline" (from to flag))
4539 (defun org-flag-subtree (flag)
4540 (save-excursion
4541 (org-back-to-heading t)
4542 (outline-end-of-heading)
4543 (outline-flag-region (point)
4544 (progn (org-end-of-subtree t) (point))
4545 flag)))
4547 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4549 (eval-and-compile
4550 (org-autoload "org-archive"
4551 '(org-add-archive-files)))
4553 ;; Autoload Column View Code
4555 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4556 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4557 (declare-function org-columns-compute "org-colview" (property))
4559 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4560 '(org-columns-number-to-string
4561 org-columns-get-format-and-top-level
4562 org-columns-compute
4563 org-columns-remove-overlays))
4565 ;; Autoload ID code
4567 (declare-function org-id-store-link "org-id")
4568 (declare-function org-id-locations-load "org-id")
4569 (declare-function org-id-locations-save "org-id")
4570 (defvar org-id-track-globally)
4571 (org-autoload "org-id"
4572 '(org-id-new
4573 org-id-copy
4574 org-id-get-with-outline-path-completion
4575 org-id-get-with-outline-drilling))
4577 ;;; Variables for pre-computed regular expressions, all buffer local
4579 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4580 "Matches first line of a hidden block.")
4581 (make-variable-buffer-local 'org-drawer-regexp)
4582 (defvar org-todo-regexp nil
4583 "Matches any of the TODO state keywords.")
4584 (make-variable-buffer-local 'org-todo-regexp)
4585 (defvar org-not-done-regexp nil
4586 "Matches any of the TODO state keywords except the last one.")
4587 (make-variable-buffer-local 'org-not-done-regexp)
4588 (defvar org-not-done-heading-regexp nil
4589 "Matches a TODO headline that is not done.")
4590 (make-variable-buffer-local 'org-not-done-regexp)
4591 (defvar org-todo-line-regexp nil
4592 "Matches a headline and puts TODO state into group 2 if present.")
4593 (make-variable-buffer-local 'org-todo-line-regexp)
4594 (defvar org-complex-heading-regexp nil
4595 "Matches a headline and puts everything into groups:
4596 group 1: the stars
4597 group 2: The todo keyword, maybe
4598 group 3: Priority cookie
4599 group 4: True headline
4600 group 5: Tags")
4601 (make-variable-buffer-local 'org-complex-heading-regexp)
4602 (defvar org-complex-heading-regexp-format nil
4603 "Printf format to make regexp to match an exact headline.
4604 This regexp will match the headline of any node which has the
4605 exact headline text that is put into the format, but may have any
4606 TODO state, priority and tags.")
4607 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4608 (defvar org-todo-line-tags-regexp nil
4609 "Matches a headline and puts TODO state into group 2 if present.
4610 Also put tags into group 4 if tags are present.")
4611 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4612 (defvar org-ds-keyword-length 12
4613 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4614 (make-variable-buffer-local 'org-ds-keyword-length)
4615 (defvar org-deadline-regexp nil
4616 "Matches the DEADLINE keyword.")
4617 (make-variable-buffer-local 'org-deadline-regexp)
4618 (defvar org-deadline-time-regexp nil
4619 "Matches the DEADLINE keyword together with a time stamp.")
4620 (make-variable-buffer-local 'org-deadline-time-regexp)
4621 (defvar org-deadline-time-hour-regexp nil
4622 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4623 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4624 (defvar org-deadline-line-regexp nil
4625 "Matches the DEADLINE keyword and the rest of the line.")
4626 (make-variable-buffer-local 'org-deadline-line-regexp)
4627 (defvar org-scheduled-regexp nil
4628 "Matches the SCHEDULED keyword.")
4629 (make-variable-buffer-local 'org-scheduled-regexp)
4630 (defvar org-scheduled-time-regexp nil
4631 "Matches the SCHEDULED keyword together with a time stamp.")
4632 (make-variable-buffer-local 'org-scheduled-time-regexp)
4633 (defvar org-scheduled-time-hour-regexp nil
4634 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4635 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4636 (defvar org-closed-time-regexp nil
4637 "Matches the CLOSED keyword together with a time stamp.")
4638 (make-variable-buffer-local 'org-closed-time-regexp)
4640 (defvar org-keyword-time-regexp nil
4641 "Matches any of the 4 keywords, together with the time stamp.")
4642 (make-variable-buffer-local 'org-keyword-time-regexp)
4643 (defvar org-keyword-time-not-clock-regexp nil
4644 "Matches any of the 3 keywords, together with the time stamp.")
4645 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4646 (defvar org-maybe-keyword-time-regexp nil
4647 "Matches a timestamp, possibly preceded by a keyword.")
4648 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4649 (defvar org-all-time-keywords nil
4650 "List of time keywords.")
4651 (make-variable-buffer-local 'org-all-time-keywords)
4653 (defconst org-plain-time-of-day-regexp
4654 (concat
4655 "\\(\\<[012]?[0-9]"
4656 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4657 "\\(--?"
4658 "\\(\\<[012]?[0-9]"
4659 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4660 "\\)?")
4661 "Regular expression to match a plain time or time range.
4662 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4663 groups carry important information:
4664 0 the full match
4665 1 the first time, range or not
4666 8 the second time, if it is a range.")
4668 (defconst org-plain-time-extension-regexp
4669 (concat
4670 "\\(\\<[012]?[0-9]"
4671 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4672 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4673 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4674 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4675 groups carry important information:
4676 0 the full match
4677 7 hours of duration
4678 9 minutes of duration")
4680 (defconst org-stamp-time-of-day-regexp
4681 (concat
4682 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4683 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4684 "\\(--?"
4685 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4686 "Regular expression to match a timestamp time or time range.
4687 After a match, the following groups carry important information:
4688 0 the full match
4689 1 date plus weekday, for back referencing to make sure both times are on the same day
4690 2 the first time, range or not
4691 4 the second time, if it is a range.")
4693 (defconst org-startup-options
4694 '(("fold" org-startup-folded t)
4695 ("overview" org-startup-folded t)
4696 ("nofold" org-startup-folded nil)
4697 ("showall" org-startup-folded nil)
4698 ("showeverything" org-startup-folded showeverything)
4699 ("content" org-startup-folded content)
4700 ("indent" org-startup-indented t)
4701 ("noindent" org-startup-indented nil)
4702 ("hidestars" org-hide-leading-stars t)
4703 ("showstars" org-hide-leading-stars nil)
4704 ("odd" org-odd-levels-only t)
4705 ("oddeven" org-odd-levels-only nil)
4706 ("align" org-startup-align-all-tables t)
4707 ("noalign" org-startup-align-all-tables nil)
4708 ("inlineimages" org-startup-with-inline-images t)
4709 ("noinlineimages" org-startup-with-inline-images nil)
4710 ("latexpreview" org-startup-with-latex-preview t)
4711 ("nolatexpreview" org-startup-with-latex-preview nil)
4712 ("customtime" org-display-custom-times t)
4713 ("logdone" org-log-done time)
4714 ("lognotedone" org-log-done note)
4715 ("nologdone" org-log-done nil)
4716 ("lognoteclock-out" org-log-note-clock-out t)
4717 ("nolognoteclock-out" org-log-note-clock-out nil)
4718 ("logrepeat" org-log-repeat state)
4719 ("lognoterepeat" org-log-repeat note)
4720 ("logdrawer" org-log-into-drawer t)
4721 ("nologdrawer" org-log-into-drawer nil)
4722 ("logstatesreversed" org-log-states-order-reversed t)
4723 ("nologstatesreversed" org-log-states-order-reversed nil)
4724 ("nologrepeat" org-log-repeat nil)
4725 ("logreschedule" org-log-reschedule time)
4726 ("lognotereschedule" org-log-reschedule note)
4727 ("nologreschedule" org-log-reschedule nil)
4728 ("logredeadline" org-log-redeadline time)
4729 ("lognoteredeadline" org-log-redeadline note)
4730 ("nologredeadline" org-log-redeadline nil)
4731 ("logrefile" org-log-refile time)
4732 ("lognoterefile" org-log-refile note)
4733 ("nologrefile" org-log-refile nil)
4734 ("fninline" org-footnote-define-inline t)
4735 ("nofninline" org-footnote-define-inline nil)
4736 ("fnlocal" org-footnote-section nil)
4737 ("fnauto" org-footnote-auto-label t)
4738 ("fnprompt" org-footnote-auto-label nil)
4739 ("fnconfirm" org-footnote-auto-label confirm)
4740 ("fnplain" org-footnote-auto-label plain)
4741 ("fnadjust" org-footnote-auto-adjust t)
4742 ("nofnadjust" org-footnote-auto-adjust nil)
4743 ("constcgs" constants-unit-system cgs)
4744 ("constSI" constants-unit-system SI)
4745 ("noptag" org-tag-persistent-alist nil)
4746 ("hideblocks" org-hide-block-startup t)
4747 ("nohideblocks" org-hide-block-startup nil)
4748 ("beamer" org-startup-with-beamer-mode t)
4749 ("entitiespretty" org-pretty-entities t)
4750 ("entitiesplain" org-pretty-entities nil))
4751 "Variable associated with STARTUP options for org-mode.
4752 Each element is a list of three items: the startup options (as written
4753 in the #+STARTUP line), the corresponding variable, and the value to set
4754 this variable to if the option is found. An optional forth element PUSH
4755 means to push this value onto the list in the variable.")
4757 (defun org-update-property-plist (key val props)
4758 "Update PROPS with KEY and VAL."
4759 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4760 (key (if appending (substring key 0 (- (length key) 1)) key))
4761 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4762 (previous (cdr (assoc key props))))
4763 (if appending
4764 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4765 (cons (cons key val) remainder))))
4767 (defconst org-block-regexp
4768 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4769 "Regular expression for hiding blocks.")
4770 (defconst org-heading-keyword-regexp-format
4771 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4772 "Printf format for a regexp matching a headline with some keyword.
4773 This regexp will match the headline of any node which has the
4774 exact keyword that is put into the format. The keyword isn't in
4775 any group by default, but the stars and the body are.")
4776 (defconst org-heading-keyword-maybe-regexp-format
4777 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4778 "Printf format for a regexp matching a headline, possibly with some keyword.
4779 This regexp can match any headline with the specified keyword, or
4780 without a keyword. The keyword isn't in any group by default,
4781 but the stars and the body are.")
4783 (defcustom org-group-tags t
4784 "When non-nil (the default), use group tags.
4785 This can be turned on/off through `org-toggle-tags-groups'."
4786 :group 'org-tags
4787 :group 'org-startup
4788 :type 'boolean)
4790 (defun org-toggle-tags-groups ()
4791 "Toggle support for group tags.
4792 Support for group tags is controlled by the option
4793 `org-group-tags', which is non-nil by default."
4794 (interactive)
4795 (setq org-group-tags (not org-group-tags))
4796 (cond ((and (derived-mode-p 'org-agenda-mode)
4797 org-group-tags)
4798 (org-agenda-redo))
4799 ((derived-mode-p 'org-mode)
4800 (let ((org-inhibit-startup t)) (org-mode))))
4801 (message "Groups tags support has been turned %s"
4802 (if org-group-tags "on" "off")))
4804 (defun org-set-regexps-and-options-for-tags ()
4805 "Precompute regular expressions used for tags in the current buffer."
4806 (when (derived-mode-p 'org-mode)
4807 (org-set-local 'org-file-tags nil)
4808 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4809 (splitre "[ \t]+")
4810 (start 0)
4811 tags ftags key value)
4812 (save-excursion
4813 (save-restriction
4814 (widen)
4815 (goto-char (point-min))
4816 (while (re-search-forward re nil t)
4817 (setq key (upcase (org-match-string-no-properties 1))
4818 value (org-match-string-no-properties 2))
4819 (if (stringp value) (setq value (org-trim value)))
4820 (cond
4821 ((equal key "TAGS")
4822 (setq tags (append tags (if tags '("\\n") nil)
4823 (org-split-string value splitre))))
4824 ((equal key "FILETAGS")
4825 (when (string-match "\\S-" value)
4826 (setq ftags
4827 (append
4828 ftags
4829 (apply 'append
4830 (mapcar (lambda (x) (org-split-string x ":"))
4831 (org-split-string value)))))))))))
4832 ;; Process the file tags.
4833 (and ftags (org-set-local 'org-file-tags
4834 (mapcar 'org-add-prop-inherited ftags)))
4835 (org-set-local 'org-tag-groups-alist nil)
4836 ;; Process the tags.
4837 ;; FIXME
4838 (when tags
4839 (let (e tgs g)
4840 (while (setq e (pop tags))
4841 (cond
4842 ((equal e "{")
4843 (progn (push '(:startgroup) tgs)
4844 (when (equal (nth 1 tags) ":")
4845 (push (list (replace-regexp-in-string
4846 "(.+)$" "" (nth 0 tags)))
4847 org-tag-groups-alist)
4848 (setq g 0))))
4849 ((equal e ":") (push '(:grouptags) tgs))
4850 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4851 ((equal e "\\n") (push '(:newline) tgs))
4852 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4853 (push (cons (match-string 1 e)
4854 (string-to-char (match-string 2 e))) tgs)
4855 (if (and g (> g 0))
4856 (setcar org-tag-groups-alist
4857 (append (car org-tag-groups-alist)
4858 (list (match-string 1 e)))))
4859 (if g (setq g (1+ g))))
4860 (t (push (list e) tgs)
4861 (if (and g (> g 0))
4862 (setcar org-tag-groups-alist
4863 (append (car org-tag-groups-alist) (list e))))
4864 (if g (setq g (1+ g))))))
4865 (org-set-local 'org-tag-alist nil)
4866 (while (setq e (pop tgs))
4867 (or (and (stringp (car e))
4868 (assoc (car e) org-tag-alist))
4869 (push e org-tag-alist)))
4870 ;; Return a list with tag variables
4871 (list org-file-tags org-tag-alist org-tag-groups-alist))))))
4873 (defun org-set-regexps-and-options ()
4874 "Precompute regular expressions used in the current buffer."
4875 (when (derived-mode-p 'org-mode)
4876 (org-set-local 'org-todo-kwd-alist nil)
4877 (org-set-local 'org-todo-key-alist nil)
4878 (org-set-local 'org-todo-key-trigger nil)
4879 (org-set-local 'org-todo-keywords-1 nil)
4880 (org-set-local 'org-done-keywords nil)
4881 (org-set-local 'org-todo-heads nil)
4882 (org-set-local 'org-todo-sets nil)
4883 (org-set-local 'org-todo-log-states nil)
4884 (org-set-local 'org-file-properties nil)
4885 (let ((re (org-make-options-regexp
4886 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
4887 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4888 "SETUPFILE" "OPTIONS")
4889 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4890 (splitre "[ \t]+")
4891 (scripts org-use-sub-superscripts)
4892 kwds kws0 kwsa key log value cat arch const links hw dws
4893 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
4894 (start 0))
4895 (save-excursion
4896 (save-restriction
4897 (widen)
4898 (goto-char (point-min))
4899 (while
4900 (or (and
4901 ext-setup-or-nil
4902 (let (ret)
4903 (with-temp-buffer
4904 (insert ext-setup-or-nil)
4905 (let ((major-mode 'org-mode))
4906 (setq ret (save-match-data
4907 (org-set-regexps-and-options-for-tags)))))
4908 ;; Append setupfile tags to existing tags
4909 (setq org-file-tags
4910 (delq nil (append org-file-tags (nth 0 ret)))
4911 org-tag-alist
4912 (delq nil (append org-tag-alist (nth 1 ret)))
4913 org-tag-groups-alist
4914 (delq nil (append org-tag-groups-alist (nth 2 ret))))))
4915 (and ext-setup-or-nil
4916 (string-match re ext-setup-or-nil start)
4917 (setq start (match-end 0)))
4918 (and (setq ext-setup-or-nil nil start 0)
4919 (re-search-forward re nil t)))
4920 (setq key (upcase (match-string 1 ext-setup-or-nil))
4921 value (org-match-string-no-properties 2 ext-setup-or-nil))
4922 (if (stringp value) (setq value (org-trim value)))
4923 (cond
4924 ((equal key "CATEGORY")
4925 (setq cat value))
4926 ((member key '("SEQ_TODO" "TODO"))
4927 (push (cons 'sequence (org-split-string value splitre)) kwds))
4928 ((equal key "TYP_TODO")
4929 (push (cons 'type (org-split-string value splitre)) kwds))
4930 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4931 ;; general TODO-like setup
4932 (push (cons (intern (downcase (match-string 1 key)))
4933 (org-split-string value splitre)) kwds))
4934 ((equal key "COLUMNS")
4935 (org-set-local 'org-columns-default-format value))
4936 ((equal key "LINK")
4937 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4938 (push (cons (match-string 1 value)
4939 (org-trim (match-string 2 value)))
4940 links)))
4941 ((equal key "PRIORITIES")
4942 (setq prio (org-split-string value " +")))
4943 ((equal key "PROPERTY")
4944 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4945 (setq props (org-update-property-plist (match-string 1 value)
4946 (match-string 2 value)
4947 props))))
4948 ((equal key "DRAWERS")
4949 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4950 ((equal key "CONSTANTS")
4951 (org-table-set-constants))
4952 ((equal key "STARTUP")
4953 (let ((opts (org-split-string value splitre))
4954 l var val)
4955 (while (setq l (pop opts))
4956 (when (setq l (assoc l org-startup-options))
4957 (setq var (nth 1 l) val (nth 2 l))
4958 (if (not (nth 3 l))
4959 (set (make-local-variable var) val)
4960 (if (not (listp (symbol-value var)))
4961 (set (make-local-variable var) nil))
4962 (set (make-local-variable var) (symbol-value var))
4963 (add-to-list var val))))))
4964 ((equal key "ARCHIVE")
4965 (setq arch value)
4966 (remove-text-properties 0 (length arch)
4967 '(face t fontified t) arch))
4968 ((equal key "OPTIONS")
4969 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4970 (setq scripts (read (match-string 2 value)))))
4971 ((and (equal key "SETUPFILE")
4972 ;; Prevent checking in Gnus messages
4973 (not buffer-read-only))
4974 (setq setup-contents (org-file-contents
4975 (expand-file-name
4976 (org-remove-double-quotes value))
4977 'noerror))
4978 (if (not ext-setup-or-nil)
4979 (setq ext-setup-or-nil setup-contents start 0)
4980 (setq ext-setup-or-nil
4981 (concat (substring ext-setup-or-nil 0 start)
4982 "\n" setup-contents "\n"
4983 (substring ext-setup-or-nil start)))))))
4984 ;; search for property blocks
4985 (goto-char (point-min))
4986 (while (re-search-forward org-block-regexp nil t)
4987 (when (equal "PROPERTY" (upcase (match-string 1)))
4988 (setq value (replace-regexp-in-string
4989 "[\n\r]" " " (match-string 4)))
4990 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4991 (setq props (org-update-property-plist (match-string 1 value)
4992 (match-string 2 value)
4993 props)))))))
4994 (org-set-local 'org-use-sub-superscripts scripts)
4995 (when cat
4996 (org-set-local 'org-category (intern cat))
4997 (push (cons "CATEGORY" cat) props))
4998 (when prio
4999 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
5000 (setq prio (mapcar 'string-to-char prio))
5001 (org-set-local 'org-highest-priority (nth 0 prio))
5002 (org-set-local 'org-lowest-priority (nth 1 prio))
5003 (org-set-local 'org-default-priority (nth 2 prio)))
5004 (and props (org-set-local 'org-file-properties (nreverse props)))
5005 (and drawers (org-set-local 'org-drawers drawers))
5006 (and arch (org-set-local 'org-archive-location arch))
5007 (and links (setq org-link-abbrev-alist-local (nreverse links)))
5008 ;; Process the TODO keywords
5009 (unless kwds
5010 ;; Use the global values as if they had been given locally.
5011 (setq kwds (default-value 'org-todo-keywords))
5012 (if (stringp (car kwds))
5013 (setq kwds (list (cons org-todo-interpretation
5014 (default-value 'org-todo-keywords)))))
5015 (setq kwds (reverse kwds)))
5016 (setq kwds (nreverse kwds))
5017 (let (inter kws kw)
5018 (while (setq kws (pop kwds))
5019 (let ((kws (or
5020 (run-hook-with-args-until-success
5021 'org-todo-setup-filter-hook kws)
5022 kws)))
5023 (setq inter (pop kws) sep (member "|" kws)
5024 kws0 (delete "|" (copy-sequence kws))
5025 kwsa nil
5026 kws1 (mapcar
5027 (lambda (x)
5028 ;; 1 2
5029 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
5030 (progn
5031 (setq kw (match-string 1 x)
5032 key (and (match-end 2) (match-string 2 x))
5033 log (org-extract-log-state-settings x))
5034 (push (cons kw (and key (string-to-char key))) kwsa)
5035 (and log (push log org-todo-log-states))
5037 (error "Invalid TODO keyword %s" x)))
5038 kws0)
5039 kwsa (if kwsa (append '((:startgroup))
5040 (nreverse kwsa)
5041 '((:endgroup))))
5042 hw (car kws1)
5043 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
5044 tail (list inter hw (car dws) (org-last dws))))
5045 (add-to-list 'org-todo-heads hw 'append)
5046 (push kws1 org-todo-sets)
5047 (setq org-done-keywords (append org-done-keywords dws nil))
5048 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
5049 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
5050 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
5051 (setq org-todo-sets (nreverse org-todo-sets)
5052 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5053 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
5054 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
5055 ;; Compute the regular expressions and other local variables.
5056 ;; Using `org-outline-regexp-bol' would complicate them much,
5057 ;; because of the fixed white space at the end of that string.
5058 (if (not org-done-keywords)
5059 (setq org-done-keywords (and org-todo-keywords-1
5060 (list (org-last org-todo-keywords-1)))))
5061 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5062 (length org-scheduled-string)
5063 (length org-clock-string)
5064 (length org-closed-string)))
5065 org-drawer-regexp
5066 (concat "^[ \t]*:\\("
5067 (mapconcat 'regexp-quote org-drawers "\\|")
5068 "\\):[ \t]*$")
5069 org-not-done-keywords
5070 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5071 org-todo-regexp
5072 (concat "\\("
5073 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5074 "\\)")
5075 org-not-done-regexp
5076 (concat "\\("
5077 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5078 "\\)")
5079 org-not-done-heading-regexp
5080 (format org-heading-keyword-regexp-format org-not-done-regexp)
5081 org-todo-line-regexp
5082 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5083 org-complex-heading-regexp
5084 (concat "^\\(\\*+\\)"
5085 "\\(?: +" org-todo-regexp "\\)?"
5086 "\\(?: +\\(\\[#.\\]\\)\\)?"
5087 "\\(?: +\\(.*?\\)\\)??"
5088 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5089 "[ \t]*$")
5090 org-complex-heading-regexp-format
5091 (concat "^\\(\\*+\\)"
5092 "\\(?: +" org-todo-regexp "\\)?"
5093 "\\(?: +\\(\\[#.\\]\\)\\)?"
5094 "\\(?: +"
5095 ;; Stats cookies can be stuck to body.
5096 "\\(?:\\[[0-9%%/]+\\] *\\)?"
5097 "\\(%s\\)"
5098 "\\(?: *\\[[0-9%%/]+\\]\\)?"
5099 "\\)"
5100 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5101 "[ \t]*$")
5102 org-todo-line-tags-regexp
5103 (concat "^\\(\\*+\\)"
5104 "\\(?: +" org-todo-regexp "\\)?"
5105 "\\(?: +\\(.*?\\)\\)??"
5106 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5107 "[ \t]*$")
5108 org-deadline-regexp (concat "\\<" org-deadline-string)
5109 org-deadline-time-regexp
5110 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5111 org-deadline-time-hour-regexp
5112 (concat "\\<" org-deadline-string
5113 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5114 org-deadline-line-regexp
5115 (concat "\\<\\(" org-deadline-string "\\).*")
5116 org-scheduled-regexp
5117 (concat "\\<" org-scheduled-string)
5118 org-scheduled-time-regexp
5119 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5120 org-scheduled-time-hour-regexp
5121 (concat "\\<" org-scheduled-string
5122 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5123 org-closed-time-regexp
5124 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5125 org-keyword-time-regexp
5126 (concat "\\<\\(" org-scheduled-string
5127 "\\|" org-deadline-string
5128 "\\|" org-closed-string
5129 "\\|" org-clock-string "\\)"
5130 " *[[<]\\([^]>]+\\)[]>]")
5131 org-keyword-time-not-clock-regexp
5132 (concat "\\<\\(" org-scheduled-string
5133 "\\|" org-deadline-string
5134 "\\|" org-closed-string
5135 "\\)"
5136 " *[[<]\\([^]>]+\\)[]>]")
5137 org-maybe-keyword-time-regexp
5138 (concat "\\(\\<\\(" org-scheduled-string
5139 "\\|" org-deadline-string
5140 "\\|" org-closed-string
5141 "\\|" org-clock-string "\\)\\)?"
5142 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5143 org-all-time-keywords
5144 (mapcar (lambda (w) (substring w 0 -1))
5145 (list org-scheduled-string org-deadline-string
5146 org-clock-string org-closed-string)))
5147 (org-compute-latex-and-related-regexp)
5148 (org-set-font-lock-defaults))))
5150 (defun org-file-contents (file &optional noerror)
5151 "Return the contents of FILE, as a string."
5152 (if (or (not file)
5153 (not (file-readable-p file)))
5154 (if noerror
5155 (message "Cannot read file \"%s\"" file)
5156 (error "Cannot read file \"%s\"" file))
5157 (with-temp-buffer
5158 (insert-file-contents file)
5159 (buffer-string))))
5161 (defun org-extract-log-state-settings (x)
5162 "Extract the log state setting from a TODO keyword string.
5163 This will extract info from a string like \"WAIT(w@/!)\"."
5164 (let (kw key log1 log2)
5165 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5166 (setq kw (match-string 1 x)
5167 key (and (match-end 2) (match-string 2 x))
5168 log1 (and (match-end 3) (match-string 3 x))
5169 log2 (and (match-end 4) (match-string 4 x)))
5170 (and (or log1 log2)
5171 (list kw
5172 (and log1 (if (equal log1 "!") 'time 'note))
5173 (and log2 (if (equal log2 "!") 'time 'note)))))))
5175 (defun org-remove-keyword-keys (list)
5176 "Remove a pair of parenthesis at the end of each string in LIST."
5177 (mapcar (lambda (x)
5178 (if (string-match "(.*)$" x)
5179 (substring x 0 (match-beginning 0))
5181 list))
5183 (defun org-assign-fast-keys (alist)
5184 "Assign fast keys to a keyword-key alist.
5185 Respect keys that are already there."
5186 (let (new e (alt ?0))
5187 (while (setq e (pop alist))
5188 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5189 (cdr e)) ;; Key already assigned.
5190 (push e new)
5191 (let ((clist (string-to-list (downcase (car e))))
5192 (used (append new alist)))
5193 (when (= (car clist) ?@)
5194 (pop clist))
5195 (while (and clist (rassoc (car clist) used))
5196 (pop clist))
5197 (unless clist
5198 (while (rassoc alt used)
5199 (incf alt)))
5200 (push (cons (car e) (or (car clist) alt)) new))))
5201 (nreverse new)))
5203 ;;; Some variables used in various places
5205 (defvar org-window-configuration nil
5206 "Used in various places to store a window configuration.")
5207 (defvar org-selected-window nil
5208 "Used in various places to store a window configuration.")
5209 (defvar org-finish-function nil
5210 "Function to be called when `C-c C-c' is used.
5211 This is for getting out of special buffers like capture.")
5214 ;; FIXME: Occasionally check by commenting these, to make sure
5215 ;; no other functions uses these, forgetting to let-bind them.
5216 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5217 (defvar org-last-state)
5218 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5220 ;; Defined somewhere in this file, but used before definition.
5221 (defvar org-entities) ;; defined in org-entities.el
5222 (defvar org-struct-menu)
5223 (defvar org-org-menu)
5224 (defvar org-tbl-menu)
5226 ;;;; Define the Org-mode
5228 ;; We use a before-change function to check if a table might need
5229 ;; an update.
5230 (defvar org-table-may-need-update t
5231 "Indicates that a table might need an update.
5232 This variable is set by `org-before-change-function'.
5233 `org-table-align' sets it back to nil.")
5234 (defun org-before-change-function (beg end)
5235 "Every change indicates that a table might need an update."
5236 (setq org-table-may-need-update t))
5237 (defvar org-mode-map)
5238 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5239 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5240 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5241 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5242 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5243 (defvar org-table-buffer-is-an nil)
5245 (defvar bidi-paragraph-direction)
5246 (defvar buffer-face-mode-face)
5248 (require 'outline)
5249 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5250 (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"))
5251 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5253 ;; Other stuff we need.
5254 (require 'time-date)
5255 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5256 (require 'easymenu)
5257 (require 'overlay)
5259 ;; (require 'org-macs) moved higher up in the file before it is first used
5260 (require 'org-entities)
5261 ;; (require 'org-compat) moved higher up in the file before it is first used
5262 (require 'org-faces)
5263 (require 'org-list)
5264 (require 'org-pcomplete)
5265 (require 'org-src)
5266 (require 'org-footnote)
5267 (require 'org-macro)
5269 ;; babel
5270 (require 'ob)
5272 ;;;###autoload
5273 (define-derived-mode org-mode outline-mode "Org"
5274 "Outline-based notes management and organizer, alias
5275 \"Carsten's outline-mode for keeping track of everything.\"
5277 Org-mode develops organizational tasks around a NOTES file which
5278 contains information about projects as plain text. Org-mode is
5279 implemented on top of outline-mode, which is ideal to keep the content
5280 of large files well structured. It supports ToDo items, deadlines and
5281 time stamps, which magically appear in the diary listing of the Emacs
5282 calendar. Tables are easily created with a built-in table editor.
5283 Plain text URL-like links connect to websites, emails (VM), Usenet
5284 messages (Gnus), BBDB entries, and any files related to the project.
5285 For printing and sharing of notes, an Org-mode file (or a part of it)
5286 can be exported as a structured ASCII or HTML file.
5288 The following commands are available:
5290 \\{org-mode-map}"
5292 ;; Get rid of Outline menus, they are not needed
5293 ;; Need to do this here because define-derived-mode sets up
5294 ;; the keymap so late. Still, it is a waste to call this each time
5295 ;; we switch another buffer into org-mode.
5296 (if (featurep 'xemacs)
5297 (when (boundp 'outline-mode-menu-heading)
5298 ;; Assume this is Greg's port, it uses easymenu
5299 (easy-menu-remove outline-mode-menu-heading)
5300 (easy-menu-remove outline-mode-menu-show)
5301 (easy-menu-remove outline-mode-menu-hide))
5302 (define-key org-mode-map [menu-bar headings] 'undefined)
5303 (define-key org-mode-map [menu-bar hide] 'undefined)
5304 (define-key org-mode-map [menu-bar show] 'undefined))
5306 (org-load-modules-maybe)
5307 (easy-menu-add org-org-menu)
5308 (easy-menu-add org-tbl-menu)
5309 (org-install-agenda-files-menu)
5310 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5311 (add-to-invisibility-spec '(org-cwidth))
5312 (add-to-invisibility-spec '(org-hide-block . t))
5313 (when (featurep 'xemacs)
5314 (org-set-local 'line-move-ignore-invisible t))
5315 (org-set-local 'outline-regexp org-outline-regexp)
5316 (org-set-local 'outline-level 'org-outline-level)
5317 (setq bidi-paragraph-direction 'left-to-right)
5318 ;; FIXME Circumvent a bug in outline.el (Emacs <24.4)
5319 (set (make-local-variable 'paragraph-start) "\f\\|[ \t]*$\\|\\*+ ")
5320 (when (and org-ellipsis
5321 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5322 (fboundp 'make-glyph-code))
5323 (unless org-display-table
5324 (setq org-display-table (make-display-table)))
5325 (set-display-table-slot
5326 org-display-table 4
5327 (vconcat (mapcar
5328 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5329 org-ellipsis)))
5330 (if (stringp org-ellipsis) org-ellipsis "..."))))
5331 (setq buffer-display-table org-display-table))
5332 (org-set-regexps-and-options-for-tags)
5333 (org-set-regexps-and-options)
5334 (when (and org-tag-faces (not org-tags-special-faces-re))
5335 ;; tag faces set outside customize.... force initialization.
5336 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5337 ;; Calc embedded
5338 (org-set-local 'calc-embedded-open-mode "# ")
5339 ;; Modify a few syntax entries
5340 (modify-syntax-entry ?@ "w")
5341 (modify-syntax-entry ?\" "\"")
5342 (if org-startup-truncated (setq truncate-lines t))
5343 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5344 (org-set-local 'font-lock-unfontify-region-function
5345 'org-unfontify-region)
5346 ;; Activate before-change-function
5347 (org-set-local 'org-table-may-need-update t)
5348 (org-add-hook 'before-change-functions 'org-before-change-function nil
5349 'local)
5350 ;; Check for running clock before killing a buffer
5351 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5352 ;; Initialize macros templates.
5353 (org-macro-initialize-templates)
5354 ;; Initialize radio targets.
5355 (org-update-radio-target-regexp)
5356 ;; Indentation.
5357 (org-set-local 'indent-line-function 'org-indent-line)
5358 (org-set-local 'indent-region-function 'org-indent-region)
5359 ;; Filling and auto-filling.
5360 (org-setup-filling)
5361 ;; Comments.
5362 (org-setup-comments-handling)
5363 ;; Beginning/end of defun
5364 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5365 (org-set-local 'end-of-defun-function 'org-forward-element)
5366 ;; Next error for sparse trees
5367 (org-set-local 'next-error-function 'org-occur-next-match)
5368 ;; Make sure dependence stuff works reliably, even for users who set it
5369 ;; too late :-(
5370 (if org-enforce-todo-dependencies
5371 (add-hook 'org-blocker-hook
5372 'org-block-todo-from-children-or-siblings-or-parent)
5373 (remove-hook 'org-blocker-hook
5374 'org-block-todo-from-children-or-siblings-or-parent))
5375 (if org-enforce-todo-checkbox-dependencies
5376 (add-hook 'org-blocker-hook
5377 'org-block-todo-from-checkboxes)
5378 (remove-hook 'org-blocker-hook
5379 'org-block-todo-from-checkboxes))
5381 ;; Align options lines
5382 (org-set-local
5383 'align-mode-rules-list
5384 '((org-in-buffer-settings
5385 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5386 (modes . '(org-mode)))))
5388 ;; Imenu
5389 (org-set-local 'imenu-create-index-function
5390 'org-imenu-get-tree)
5392 ;; Make isearch reveal context
5393 (if (or (featurep 'xemacs)
5394 (not (boundp 'outline-isearch-open-invisible-function)))
5395 ;; Emacs 21 and XEmacs make use of the hook
5396 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5397 ;; Emacs 22 deals with this through a special variable
5398 (org-set-local 'outline-isearch-open-invisible-function
5399 (lambda (&rest ignore) (org-show-context 'isearch)))
5400 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5402 ;; Setup the pcomplete hooks
5403 (set (make-local-variable 'pcomplete-command-completion-function)
5404 'org-pcomplete-initial)
5405 (set (make-local-variable 'pcomplete-command-name-function)
5406 'org-command-at-point)
5407 (set (make-local-variable 'pcomplete-default-completion-function)
5408 'ignore)
5409 (set (make-local-variable 'pcomplete-parse-arguments-function)
5410 'org-parse-arguments)
5411 (set (make-local-variable 'pcomplete-termination-string) "")
5412 (when (>= emacs-major-version 23)
5413 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5415 ;; If empty file that did not turn on org-mode automatically, make it to.
5416 (if (and org-insert-mode-line-in-empty-file
5417 (org-called-interactively-p 'any)
5418 (= (point-min) (point-max)))
5419 (insert "# -*- mode: org -*-\n\n"))
5420 (unless org-inhibit-startup
5421 (org-unmodified
5422 (and org-startup-with-beamer-mode (org-beamer-mode))
5423 (when org-startup-align-all-tables
5424 (org-table-map-tables 'org-table-align 'quietly))
5425 (when org-startup-with-inline-images
5426 (org-display-inline-images))
5427 (when org-startup-with-latex-preview
5428 (org-preview-latex-fragment))
5429 (unless org-inhibit-startup-visibility-stuff
5430 (org-set-startup-visibility))))
5431 ;; Try to set org-hide correctly
5432 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5434 ;; Update `customize-package-emacs-version-alist'
5435 (add-to-list 'customize-package-emacs-version-alist
5436 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5437 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5438 ("8.0" . "24.4")))
5440 (defvar org-mode-transpose-word-syntax-table
5441 (let ((st (make-syntax-table)))
5442 (mapc (lambda(c) (modify-syntax-entry
5443 (string-to-char (car c)) "w p" st))
5444 org-emphasis-alist)
5445 st))
5447 (when (fboundp 'abbrev-table-put)
5448 (abbrev-table-put org-mode-abbrev-table
5449 :parents (list text-mode-abbrev-table)))
5451 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5453 (defsubst org-fix-ellipsis-at-bol ()
5454 (save-excursion (goto-char (window-start)) (recenter 0)))
5456 (defun org-find-invisible-foreground ()
5457 (let ((candidates (remove
5458 "unspecified-bg"
5459 (nconc
5460 (list (face-background 'default)
5461 (face-background 'org-default))
5462 (mapcar
5463 (lambda (alist)
5464 (when (boundp alist)
5465 (cdr (assoc 'background-color (symbol-value alist)))))
5466 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5467 (list (face-foreground 'org-hide))))))
5468 (car (remove nil candidates))))
5470 (defun org-current-time (&optional rounding-minutes past)
5471 "Current time, possibly rounded to ROUNDING-MINUTES.
5472 When ROUNDING-MINUTES is not an integer, fall back on the car of
5473 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5474 the rounding returns a past time."
5475 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5476 (car org-time-stamp-rounding-minutes)))
5477 (time (decode-time)) res)
5478 (if (< r 1)
5479 (current-time)
5480 (setq res
5481 (apply 'encode-time
5482 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5483 (nthcdr 2 time))))
5484 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5485 (seconds-to-time (- (org-float-time res) (* r 60)))
5486 res))))
5488 (defun org-today ()
5489 "Return today date, considering `org-extend-today-until'."
5490 (time-to-days
5491 (time-subtract (current-time)
5492 (list 0 (* 3600 org-extend-today-until) 0))))
5494 ;;;; Font-Lock stuff, including the activators
5496 (defvar org-mouse-map (make-sparse-keymap))
5497 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5498 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5499 (when org-mouse-1-follows-link
5500 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5501 (when org-tab-follows-link
5502 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5503 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5505 (require 'font-lock)
5507 (defconst org-non-link-chars "]\t\n\r<>")
5508 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5509 "shell" "elisp" "doi" "message"))
5510 (defvar org-link-types-re nil
5511 "Matches a link that has a url-like prefix like \"http:\"")
5512 (defvar org-link-re-with-space nil
5513 "Matches a link with spaces, optional angular brackets around it.")
5514 (defvar org-link-re-with-space2 nil
5515 "Matches a link with spaces, optional angular brackets around it.")
5516 (defvar org-link-re-with-space3 nil
5517 "Matches a link with spaces, only for internal part in bracket links.")
5518 (defvar org-angle-link-re nil
5519 "Matches link with angular brackets, spaces are allowed.")
5520 (defvar org-plain-link-re nil
5521 "Matches plain link, without spaces.")
5522 (defvar org-bracket-link-regexp nil
5523 "Matches a link in double brackets.")
5524 (defvar org-bracket-link-analytic-regexp nil
5525 "Regular expression used to analyze links.
5526 Here is what the match groups contain after a match:
5527 1: http:
5528 2: http
5529 3: path
5530 4: [desc]
5531 5: desc")
5532 (defvar org-bracket-link-analytic-regexp++ nil
5533 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5534 (defvar org-any-link-re nil
5535 "Regular expression matching any link.")
5537 (defconst org-match-sexp-depth 3
5538 "Number of stacked braces for sub/superscript matching.")
5540 (defun org-create-multibrace-regexp (left right n)
5541 "Create a regular expression which will match a balanced sexp.
5542 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5543 as single character strings.
5544 The regexp returned will match the entire expression including the
5545 delimiters. It will also define a single group which contains the
5546 match except for the outermost delimiters. The maximum depth of
5547 stacked delimiters is N. Escaping delimiters is not possible."
5548 (let* ((nothing (concat "[^" left right "]*?"))
5549 (or "\\|")
5550 (re nothing)
5551 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5552 (while (> n 1)
5553 (setq n (1- n)
5554 re (concat re or next)
5555 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5556 (concat left "\\(" re "\\)" right)))
5558 (defvar org-match-substring-regexp
5559 (concat
5560 "\\(\\S-\\)\\([_^]\\)\\("
5561 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5562 "\\|"
5563 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5564 "\\|"
5565 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5566 "The regular expression matching a sub- or superscript.")
5568 (defvar org-match-substring-with-braces-regexp
5569 (concat
5570 "\\(\\S-\\)\\([_^]\\)\\("
5571 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5572 "\\)")
5573 "The regular expression matching a sub- or superscript, forcing braces.")
5575 (defun org-make-link-regexps ()
5576 "Update the link regular expressions.
5577 This should be called after the variable `org-link-types' has changed."
5578 (setq org-link-types-re
5579 (concat
5580 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5581 org-link-re-with-space
5582 (concat
5583 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5584 "\\([^" org-non-link-chars " ]"
5585 "[^" org-non-link-chars "]*"
5586 "[^" org-non-link-chars " ]\\)>?")
5587 org-link-re-with-space2
5588 (concat
5589 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5590 "\\([^" org-non-link-chars " ]"
5591 "[^\t\n\r]*"
5592 "[^" org-non-link-chars " ]\\)>?")
5593 org-link-re-with-space3
5594 (concat
5595 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5596 "\\([^" org-non-link-chars " ]"
5597 "[^\t\n\r]*\\)")
5598 org-angle-link-re
5599 (concat
5600 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5601 "\\([^" org-non-link-chars " ]"
5602 "[^" org-non-link-chars "]*"
5603 "\\)>")
5604 org-plain-link-re
5605 (concat
5606 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5607 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5608 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5609 org-bracket-link-regexp
5610 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5611 org-bracket-link-analytic-regexp
5612 (concat
5613 "\\[\\["
5614 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5615 "\\([^]]+\\)"
5616 "\\]"
5617 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5618 "\\]")
5619 org-bracket-link-analytic-regexp++
5620 (concat
5621 "\\[\\["
5622 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5623 "\\([^]]+\\)"
5624 "\\]"
5625 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5626 "\\]")
5627 org-any-link-re
5628 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5629 org-angle-link-re "\\)\\|\\("
5630 org-plain-link-re "\\)")))
5632 (org-make-link-regexps)
5634 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5635 "Regular expression for fast time stamp matching.")
5636 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5637 "Regular expression for fast time stamp matching.")
5638 (defconst org-ts-regexp0
5639 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5640 "Regular expression matching time strings for analysis.
5641 This one does not require the space after the date, so it can be used
5642 on a string that terminates immediately after the date.")
5643 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5644 "Regular expression matching time strings for analysis.")
5645 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5646 "Regular expression matching time stamps, with groups.")
5647 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5648 "Regular expression matching time stamps (also [..]), with groups.")
5649 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5650 "Regular expression matching a time stamp range.")
5651 (defconst org-tr-regexp-both
5652 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5653 "Regular expression matching a time stamp range.")
5654 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5655 org-ts-regexp "\\)?")
5656 "Regular expression matching a time stamp or time stamp range.")
5657 (defconst org-tsr-regexp-both
5658 (concat org-ts-regexp-both "\\(--?-?"
5659 org-ts-regexp-both "\\)?")
5660 "Regular expression matching a time stamp or time stamp range.
5661 The time stamps may be either active or inactive.")
5663 (defvar org-emph-face nil)
5665 (defun org-do-emphasis-faces (limit)
5666 "Run through the buffer and add overlays to emphasized strings."
5667 (let (rtn a)
5668 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5669 (if (not (= (char-after (match-beginning 3))
5670 (char-after (match-beginning 4))))
5671 (progn
5672 (setq rtn t)
5673 (setq a (assoc (match-string 3) org-emphasis-alist))
5674 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5675 'face
5676 (nth 1 a))
5677 (and (nth 4 a)
5678 (org-remove-flyspell-overlays-in
5679 (match-beginning 0) (match-end 0)))
5680 (add-text-properties (match-beginning 2) (match-end 2)
5681 '(font-lock-multiline t org-emphasis t))
5682 (when org-hide-emphasis-markers
5683 (add-text-properties (match-end 4) (match-beginning 5)
5684 '(invisible org-link))
5685 (add-text-properties (match-beginning 3) (match-end 3)
5686 '(invisible org-link)))))
5687 (backward-char 1))
5688 rtn))
5690 (defun org-emphasize (&optional char)
5691 "Insert or change an emphasis, i.e. a font like bold or italic.
5692 If there is an active region, change that region to a new emphasis.
5693 If there is no region, just insert the marker characters and position
5694 the cursor between them.
5695 CHAR should be the marker character. If it is a space, it means to
5696 remove the emphasis of the selected region.
5697 If CHAR is not given (for example in an interactive call) it will be
5698 prompted for."
5699 (interactive)
5700 (let ((erc org-emphasis-regexp-components)
5701 (prompt "")
5702 (string "") beg end move c s)
5703 (if (org-region-active-p)
5704 (setq beg (region-beginning) end (region-end)
5705 string (buffer-substring beg end))
5706 (setq move t))
5708 (unless char
5709 (message "Emphasis marker or tag: [%s]"
5710 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5711 (setq char (read-char-exclusive)))
5712 (if (equal char ?\ )
5713 (setq s "" move nil)
5714 (unless (assoc (char-to-string char) org-emphasis-alist)
5715 (user-error "No such emphasis marker: \"%c\"" char))
5716 (setq s (char-to-string char)))
5717 (while (and (> (length string) 1)
5718 (equal (substring string 0 1) (substring string -1))
5719 (assoc (substring string 0 1) org-emphasis-alist))
5720 (setq string (substring string 1 -1)))
5721 (setq string (concat s string s))
5722 (if beg (delete-region beg end))
5723 (unless (or (bolp)
5724 (string-match (concat "[" (nth 0 erc) "\n]")
5725 (char-to-string (char-before (point)))))
5726 (insert " "))
5727 (unless (or (eobp)
5728 (string-match (concat "[" (nth 1 erc) "\n]")
5729 (char-to-string (char-after (point)))))
5730 (insert " ") (backward-char 1))
5731 (insert string)
5732 (and move (backward-char 1))))
5734 (defconst org-nonsticky-props
5735 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5737 (defsubst org-rear-nonsticky-at (pos)
5738 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5740 (defun org-activate-plain-links (limit)
5741 "Run through the buffer and add overlays to links."
5742 (let (f hl)
5743 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5744 (not (org-in-src-block-p)))
5745 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5746 (setq f (get-text-property (match-beginning 0) 'face))
5747 (setq hl (org-match-string-no-properties 0))
5748 (if (or (eq f 'org-tag)
5749 (and (listp f) (memq 'org-tag f)))
5751 (add-text-properties (match-beginning 0) (match-end 0)
5752 (list 'mouse-face 'highlight
5753 'face 'org-link
5754 'htmlize-link `(:uri ,hl)
5755 'keymap org-mouse-map))
5756 (org-rear-nonsticky-at (match-end 0)))
5757 t)))
5759 (defun org-activate-code (limit)
5760 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5761 (progn
5762 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5763 (remove-text-properties (match-beginning 0) (match-end 0)
5764 '(display t invisible t intangible t))
5765 t)))
5767 (defcustom org-src-fontify-natively nil
5768 "When non-nil, fontify code in code blocks."
5769 :type 'boolean
5770 :version "24.1"
5771 :group 'org-appearance
5772 :group 'org-babel)
5774 (defcustom org-allow-promoting-top-level-subtree nil
5775 "When non-nil, allow promoting a top level subtree.
5776 The leading star of the top level headline will be replaced
5777 by a #."
5778 :type 'boolean
5779 :version "24.1"
5780 :group 'org-appearance)
5782 (defun org-fontify-meta-lines-and-blocks (limit)
5783 (condition-case nil
5784 (org-fontify-meta-lines-and-blocks-1 limit)
5785 (error (message "org-mode fontification error"))))
5787 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5788 "Fontify #+ lines and blocks."
5789 (let ((case-fold-search t))
5790 (if (re-search-forward
5791 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5792 limit t)
5793 (let ((beg (match-beginning 0))
5794 (block-start (match-end 0))
5795 (block-end nil)
5796 (lang (match-string 7))
5797 (beg1 (line-beginning-position 2))
5798 (dc1 (downcase (match-string 2)))
5799 (dc3 (downcase (match-string 3)))
5800 end end1 quoting block-type ovl)
5801 (cond
5802 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5803 ;; a single line of backend-specific content
5804 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5805 (remove-text-properties (match-beginning 0) (match-end 0)
5806 '(display t invisible t intangible t))
5807 (add-text-properties (match-beginning 1) (match-end 3)
5808 '(font-lock-fontified t face org-meta-line))
5809 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5810 '(font-lock-fontified t face org-block))
5811 ; for backend-specific code
5813 ((and (match-end 4) (equal dc3 "+begin"))
5814 ;; Truly a block
5815 (setq block-type (downcase (match-string 5))
5816 quoting (member block-type org-protecting-blocks))
5817 (when (re-search-forward
5818 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5819 nil t) ;; on purpose, we look further than LIMIT
5820 (setq end (min (point-max) (match-end 0))
5821 end1 (min (point-max) (1- (match-beginning 0))))
5822 (setq block-end (match-beginning 0))
5823 (when quoting
5824 (remove-text-properties beg end
5825 '(display t invisible t intangible t)))
5826 (add-text-properties
5827 beg end
5828 '(font-lock-fontified t font-lock-multiline t))
5829 (add-text-properties beg beg1 '(face org-meta-line))
5830 (add-text-properties end1 (min (point-max) (1+ end))
5831 '(face org-meta-line)) ; for end_src
5832 (cond
5833 ((and lang (not (string= lang "")) org-src-fontify-natively)
5834 (org-src-font-lock-fontify-block lang block-start block-end)
5835 ;; remove old background overlays
5836 (mapc (lambda (ov)
5837 (if (eq (overlay-get ov 'face) 'org-block-background)
5838 (delete-overlay ov)))
5839 (overlays-at (/ (+ beg1 block-end) 2)))
5840 ;; add a background overlay
5841 (setq ovl (make-overlay beg1 block-end))
5842 (overlay-put ovl 'face 'org-block-background)
5843 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5844 (quoting
5845 (add-text-properties beg1 (min (point-max) (1+ end1))
5846 '(face org-block))) ; end of source block
5847 ((not org-fontify-quote-and-verse-blocks))
5848 ((string= block-type "quote")
5849 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5850 ((string= block-type "verse")
5851 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5852 (add-text-properties beg beg1 '(face org-block-begin-line))
5853 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5854 '(face org-block-end-line))
5856 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5857 (add-text-properties
5858 beg (match-end 3)
5859 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5860 '(font-lock-fontified t invisible t)
5861 '(font-lock-fontified t face org-document-info-keyword)))
5862 (add-text-properties
5863 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5864 (if (string-equal dc1 "+title:")
5865 '(font-lock-fontified t face org-document-title)
5866 '(font-lock-fontified t face org-document-info))))
5867 ((or (equal dc1 "+results")
5868 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5869 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5870 "+call:" "+header:" "+headers:" "+name:"))
5871 (and (match-end 4) (equal dc3 "+attr")))
5872 (add-text-properties
5873 beg (match-end 0)
5874 '(font-lock-fontified t face org-meta-line))
5876 ((member dc3 '(" " ""))
5877 (add-text-properties
5878 beg (match-end 0)
5879 '(font-lock-fontified t face font-lock-comment-face)))
5880 ((not (member (char-after beg) '(?\ ?\t)))
5881 ;; just any other in-buffer setting, but not indented
5882 (add-text-properties
5883 beg (match-end 0)
5884 '(font-lock-fontified t face org-meta-line))
5886 (t nil))))))
5888 (defun org-activate-angle-links (limit)
5889 "Run through the buffer and add overlays to links."
5890 (if (and (re-search-forward org-angle-link-re limit t)
5891 (not (org-in-src-block-p)))
5892 (progn
5893 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5894 (add-text-properties (match-beginning 0) (match-end 0)
5895 (list 'mouse-face 'highlight
5896 'keymap org-mouse-map))
5897 (org-rear-nonsticky-at (match-end 0))
5898 t)))
5900 (defun org-activate-footnote-links (limit)
5901 "Run through the buffer and add overlays to footnotes."
5902 (let ((fn (org-footnote-next-reference-or-definition limit)))
5903 (when fn
5904 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5905 (org-remove-flyspell-overlays-in beg end)
5906 (add-text-properties beg end
5907 (list 'mouse-face 'highlight
5908 'keymap org-mouse-map
5909 'help-echo
5910 (if (= (point-at-bol) beg)
5911 "Footnote definition"
5912 "Footnote reference")
5913 'font-lock-fontified t
5914 'font-lock-multiline t
5915 'face 'org-footnote))))))
5917 (defun org-activate-bracket-links (limit)
5918 "Run through the buffer and add overlays to bracketed links."
5919 (if (and (re-search-forward org-bracket-link-regexp limit t)
5920 (not (org-in-src-block-p)))
5921 (let* ((hl (org-match-string-no-properties 1))
5922 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
5923 (ip (org-maybe-intangible
5924 (list 'invisible 'org-link
5925 'keymap org-mouse-map 'mouse-face 'highlight
5926 'font-lock-multiline t 'help-echo help
5927 'htmlize-link `(:uri ,hl))))
5928 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5929 'font-lock-multiline t 'help-echo help
5930 'htmlize-link `(:uri ,hl))))
5931 ;; We need to remove the invisible property here. Table narrowing
5932 ;; may have made some of this invisible.
5933 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5934 (remove-text-properties (match-beginning 0) (match-end 0)
5935 '(invisible nil))
5936 (if (match-end 3)
5937 (progn
5938 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5939 (org-rear-nonsticky-at (match-beginning 3))
5940 (add-text-properties (match-beginning 3) (match-end 3) vp)
5941 (org-rear-nonsticky-at (match-end 3))
5942 (add-text-properties (match-end 3) (match-end 0) ip)
5943 (org-rear-nonsticky-at (match-end 0)))
5944 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5945 (org-rear-nonsticky-at (match-beginning 1))
5946 (add-text-properties (match-beginning 1) (match-end 1) vp)
5947 (org-rear-nonsticky-at (match-end 1))
5948 (add-text-properties (match-end 1) (match-end 0) ip)
5949 (org-rear-nonsticky-at (match-end 0)))
5950 t)))
5952 (defun org-activate-dates (limit)
5953 "Run through the buffer and add overlays to dates."
5954 (if (and (re-search-forward org-tsr-regexp-both limit t)
5955 (not (equal (char-before (match-beginning 0)) 91)))
5956 (progn
5957 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5958 (add-text-properties (match-beginning 0) (match-end 0)
5959 (list 'mouse-face 'highlight
5960 'keymap org-mouse-map))
5961 (org-rear-nonsticky-at (match-end 0))
5962 (when org-display-custom-times
5963 (if (match-end 3)
5964 (org-display-custom-time (match-beginning 3) (match-end 3)))
5965 (org-display-custom-time (match-beginning 1) (match-end 1)))
5966 t)))
5968 (defvar org-target-link-regexp nil
5969 "Regular expression matching radio targets in plain text.")
5970 (make-variable-buffer-local 'org-target-link-regexp)
5971 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5972 "Regular expression matching a link target.")
5973 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5974 "Regular expression matching a radio target.")
5975 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5976 "Regular expression matching any target.")
5978 (defun org-activate-target-links (limit)
5979 "Run through the buffer and add overlays to target matches."
5980 (when org-target-link-regexp
5981 (let ((case-fold-search t))
5982 (if (re-search-forward org-target-link-regexp limit t)
5983 (progn
5984 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5985 (add-text-properties (match-beginning 0) (match-end 0)
5986 (list 'mouse-face 'highlight
5987 'keymap org-mouse-map
5988 'help-echo "Radio target link"
5989 'org-linked-text t))
5990 (org-rear-nonsticky-at (match-end 0))
5991 t)))))
5993 (defun org-update-radio-target-regexp ()
5994 "Find all radio targets in this file and update the regular expression."
5995 (interactive)
5996 (when (memq 'radio org-activate-links)
5997 (setq org-target-link-regexp
5998 (org-make-target-link-regexp (org-all-targets 'radio)))
5999 (org-restart-font-lock)))
6001 (defun org-hide-wide-columns (limit)
6002 (let (s e)
6003 (setq s (text-property-any (point) (or limit (point-max))
6004 'org-cwidth t))
6005 (when s
6006 (setq e (next-single-property-change s 'org-cwidth))
6007 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6008 (goto-char e)
6009 t)))
6011 (defvar org-latex-and-related-regexp nil
6012 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6013 (defvar org-match-substring-regexp)
6014 (defvar org-match-substring-with-braces-regexp)
6016 (defun org-compute-latex-and-related-regexp ()
6017 "Compute regular expression for LaTeX, entities and sub/superscript.
6018 Result depends on variable `org-highlight-latex-and-related'."
6019 (org-set-local
6020 'org-latex-and-related-regexp
6021 (let* ((re-sub
6022 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6023 ((eq org-use-sub-superscripts '{})
6024 (list org-match-substring-with-braces-regexp))
6025 (org-use-sub-superscripts (list org-match-substring-regexp))))
6026 (re-latex
6027 (when (memq 'latex org-highlight-latex-and-related)
6028 (let ((matchers (plist-get org-format-latex-options :matchers)))
6029 (delq nil
6030 (mapcar (lambda (x)
6031 (and (member (car x) matchers) (nth 1 x)))
6032 org-latex-regexps)))))
6033 (re-entities
6034 (when (memq 'entities org-highlight-latex-and-related)
6035 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6036 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6038 (defun org-do-latex-and-related (limit)
6039 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6040 LIMIT bounds the search for syntax to highlight. Stop at first
6041 highlighted object, if any. Return t if some highlighting was
6042 done, nil otherwise."
6043 (when (org-string-nw-p org-latex-and-related-regexp)
6044 (catch 'found
6045 (while (re-search-forward org-latex-and-related-regexp limit t)
6046 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6047 'face))
6048 '(org-code org-verbatim underline))
6049 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6050 '(?_ ?^))
6052 0)))
6053 (font-lock-prepend-text-property
6054 (+ offset (match-beginning 0)) (match-end 0)
6055 'face 'org-latex-and-related)
6056 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6057 '(font-lock-multiline t)))
6058 (throw 'found t)))
6059 nil)))
6061 (defun org-restart-font-lock ()
6062 "Restart `font-lock-mode', to force refontification."
6063 (when (and (boundp 'font-lock-mode) font-lock-mode)
6064 (font-lock-mode -1)
6065 (font-lock-mode 1)))
6067 (defun org-all-targets (&optional radio)
6068 "Return a list of all targets in this file.
6069 When optional argument RADIO is non-nil, only find radio
6070 targets."
6071 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
6072 (save-excursion
6073 (goto-char (point-min))
6074 (while (re-search-forward re nil t)
6075 ;; Make sure point is really within the object.
6076 (backward-char)
6077 (let ((obj (org-element-context)))
6078 (when (memq (org-element-type obj) '(radio-target target))
6079 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
6080 rtn)))
6082 (defun org-make-target-link-regexp (targets)
6083 "Make regular expression matching all strings in TARGETS.
6084 The regular expression finds the targets also if there is a line break
6085 between words."
6086 (and targets
6087 (concat
6088 "\\<\\("
6089 (mapconcat
6090 (lambda (x)
6091 (setq x (regexp-quote x))
6092 (while (string-match " +" x)
6093 (setq x (replace-match "\\s-+" t t x)))
6095 targets
6096 "\\|")
6097 "\\)\\>")))
6099 (defun org-activate-tags (limit)
6100 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6101 (progn
6102 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6103 (add-text-properties (match-beginning 1) (match-end 1)
6104 (list 'mouse-face 'highlight
6105 'keymap org-mouse-map))
6106 (org-rear-nonsticky-at (match-end 1))
6107 t)))
6109 (defun org-outline-level ()
6110 "Compute the outline level of the heading at point.
6111 If this is called at a normal headline, the level is the number of stars.
6112 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6113 (save-excursion
6114 (if (not (condition-case nil
6115 (org-back-to-heading t)
6116 (error nil)))
6118 (looking-at org-outline-regexp)
6119 (1- (- (match-end 0) (match-beginning 0))))))
6121 (defvar org-font-lock-keywords nil)
6123 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
6124 "Regular expression matching a property line.")
6126 (defvar org-font-lock-hook nil
6127 "Functions to be called for special font lock stuff.")
6129 (defvar org-font-lock-set-keywords-hook nil
6130 "Functions that can manipulate `org-font-lock-extra-keywords'.
6131 This is called after `org-font-lock-extra-keywords' is defined, but before
6132 it is installed to be used by font lock. This can be useful if something
6133 needs to be inserted at a specific position in the font-lock sequence.")
6135 (defun org-font-lock-hook (limit)
6136 "Run `org-font-lock-hook' within LIMIT."
6137 (run-hook-with-args 'org-font-lock-hook limit))
6139 (defun org-set-font-lock-defaults ()
6140 "Set font lock defaults for the current buffer."
6141 (let* ((em org-fontify-emphasized-text)
6142 (lk org-activate-links)
6143 (org-font-lock-extra-keywords
6144 (list
6145 ;; Call the hook
6146 '(org-font-lock-hook)
6147 ;; Headlines
6148 `(,(if org-fontify-whole-heading-line
6149 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6150 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6151 (1 (org-get-level-face 1))
6152 (2 (org-get-level-face 2))
6153 (3 (org-get-level-face 3)))
6154 ;; Table lines
6155 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6156 (1 'org-table t))
6157 ;; Table internals
6158 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6159 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6160 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6161 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6162 ;; Drawers
6163 (list org-drawer-regexp '(0 'org-special-keyword t))
6164 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
6165 ;; Properties
6166 (list org-property-re
6167 '(1 'org-special-keyword t)
6168 '(3 'org-property-value t))
6169 ;; Links
6170 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6171 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6172 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6173 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6174 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6175 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6176 (if (memq 'footnote lk) '(org-activate-footnote-links))
6177 ;; Targets.
6178 (list org-any-target-regexp '(0 'org-target t))
6179 ;; Diary sexps.
6180 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6181 ;; Macro
6182 '("{{{.+}}}" (0 'org-macro t))
6183 '(org-hide-wide-columns (0 nil append))
6184 ;; TODO keyword
6185 (list (format org-heading-keyword-regexp-format
6186 org-todo-regexp)
6187 '(2 (org-get-todo-face 2) t))
6188 ;; DONE
6189 (if org-fontify-done-headline
6190 (list (format org-heading-keyword-regexp-format
6191 (concat
6192 "\\(?:"
6193 (mapconcat 'regexp-quote org-done-keywords "\\|")
6194 "\\)"))
6195 '(2 'org-headline-done t))
6196 nil)
6197 ;; Priorities
6198 '(org-font-lock-add-priority-faces)
6199 ;; Tags
6200 '(org-font-lock-add-tag-faces)
6201 ;; Tags groups
6202 (if (and org-group-tags org-tag-groups-alist)
6203 (list (concat org-outline-regexp-bol ".+\\(:"
6204 (regexp-opt (mapcar 'car org-tag-groups-alist))
6205 ":\\).*$")
6206 '(1 'org-tag-group prepend)))
6207 ;; Special keywords
6208 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6209 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6210 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6211 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6212 ;; Emphasis
6213 (if em
6214 (if (featurep 'xemacs)
6215 '(org-do-emphasis-faces (0 nil append))
6216 '(org-do-emphasis-faces)))
6217 ;; Checkboxes
6218 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6219 1 'org-checkbox prepend)
6220 (if (cdr (assq 'checkbox org-list-automatic-rules))
6221 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6222 (0 (org-get-checkbox-statistics-face) t)))
6223 ;; Description list items
6224 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6225 1 'org-list-dt prepend)
6226 ;; ARCHIVEd headings
6227 (list (concat
6228 org-outline-regexp-bol
6229 "\\(.*:" org-archive-tag ":.*\\)")
6230 '(1 'org-archived prepend))
6231 ;; Specials
6232 '(org-do-latex-and-related)
6233 '(org-fontify-entities)
6234 '(org-raise-scripts)
6235 ;; Code
6236 '(org-activate-code (1 'org-code t))
6237 ;; COMMENT
6238 (list (format org-heading-keyword-regexp-format
6239 (concat "\\("
6240 org-comment-string "\\|" org-quote-string
6241 "\\)"))
6242 '(2 'org-special-keyword t))
6243 ;; Blocks and meta lines
6244 '(org-fontify-meta-lines-and-blocks))))
6245 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6246 (run-hooks 'org-font-lock-set-keywords-hook)
6247 ;; Now set the full font-lock-keywords
6248 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6249 (org-set-local 'font-lock-defaults
6250 '(org-font-lock-keywords t nil nil backward-paragraph))
6251 (kill-local-variable 'font-lock-keywords) nil))
6253 (defun org-toggle-pretty-entities ()
6254 "Toggle the composition display of entities as UTF8 characters."
6255 (interactive)
6256 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6257 (org-restart-font-lock)
6258 (if org-pretty-entities
6259 (message "Entities are now displayed as UTF8 characters")
6260 (save-restriction
6261 (widen)
6262 (org-decompose-region (point-min) (point-max))
6263 (message "Entities are now displayed as plain text"))))
6265 (defvar org-custom-properties-overlays nil
6266 "List of overlays used for custom properties.")
6267 (make-variable-buffer-local 'org-custom-properties-overlays)
6269 (defun org-toggle-custom-properties-visibility ()
6270 "Display or hide properties in `org-custom-properties'."
6271 (interactive)
6272 (if org-custom-properties-overlays
6273 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6274 (setq org-custom-properties-overlays nil))
6275 (unless (not org-custom-properties)
6276 (save-excursion
6277 (save-restriction
6278 (widen)
6279 (goto-char (point-min))
6280 (while (re-search-forward org-property-re nil t)
6281 (mapc (lambda(p)
6282 (when (equal p (substring (match-string 1) 1 -1))
6283 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6284 (overlay-put o 'invisible t)
6285 (overlay-put o 'org-custom-property t)
6286 (push o org-custom-properties-overlays))))
6287 org-custom-properties)))))))
6289 (defun org-fontify-entities (limit)
6290 "Find an entity to fontify."
6291 (let (ee)
6292 (when org-pretty-entities
6293 (catch 'match
6294 (while (re-search-forward
6295 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6296 limit t)
6297 (if (and (not (org-in-indented-comment-line))
6298 (setq ee (org-entity-get (match-string 1)))
6299 (= (length (nth 6 ee)) 1))
6300 (let*
6301 ((end (if (equal (match-string 2) "{}")
6302 (match-end 2)
6303 (match-end 1))))
6304 (add-text-properties
6305 (match-beginning 0) end
6306 (list 'font-lock-fontified t))
6307 (compose-region (match-beginning 0) end
6308 (nth 6 ee) nil)
6309 (backward-char 1)
6310 (throw 'match t))))
6311 nil))))
6313 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6314 "Fontify string S like in Org-mode."
6315 (with-temp-buffer
6316 (insert s)
6317 (let ((org-odd-levels-only odd-levels))
6318 (org-mode)
6319 (font-lock-fontify-buffer)
6320 (buffer-string))))
6322 (defvar org-m nil)
6323 (defvar org-l nil)
6324 (defvar org-f nil)
6325 (defun org-get-level-face (n)
6326 "Get the right face for match N in font-lock matching of headlines."
6327 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6328 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6329 (if org-cycle-level-faces
6330 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6331 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6332 (cond
6333 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6334 ((eq n 2) org-f)
6335 (t (if org-level-color-stars-only nil org-f))))
6338 (defun org-get-todo-face (kwd)
6339 "Get the right face for a TODO keyword KWD.
6340 If KWD is a number, get the corresponding match group."
6341 (if (numberp kwd) (setq kwd (match-string kwd)))
6342 (or (org-face-from-face-or-color
6343 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6344 (and (member kwd org-done-keywords) 'org-done)
6345 'org-todo))
6347 (defun org-face-from-face-or-color (context inherit face-or-color)
6348 "Create a face list that inherits INHERIT, but sets the foreground color.
6349 When FACE-OR-COLOR is not a string, just return it."
6350 (if (stringp face-or-color)
6351 (list :inherit inherit
6352 (cdr (assoc context org-faces-easy-properties))
6353 face-or-color)
6354 face-or-color))
6356 (defun org-font-lock-add-tag-faces (limit)
6357 "Add the special tag faces."
6358 (when (and org-tag-faces org-tags-special-faces-re)
6359 (while (re-search-forward org-tags-special-faces-re limit t)
6360 (add-text-properties (match-beginning 1) (match-end 1)
6361 (list 'face (org-get-tag-face 1)
6362 'font-lock-fontified t))
6363 (backward-char 1))))
6365 (defun org-font-lock-add-priority-faces (limit)
6366 "Add the special priority faces."
6367 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6368 (when (save-match-data (org-at-heading-p))
6369 (add-text-properties
6370 (match-beginning 0) (match-end 0)
6371 (list 'face (or (org-face-from-face-or-color
6372 'priority 'org-priority
6373 (cdr (assoc (char-after (match-beginning 1))
6374 org-priority-faces)))
6375 'org-priority)
6376 'font-lock-fontified t)))))
6378 (defun org-get-tag-face (kwd)
6379 "Get the right face for a TODO keyword KWD.
6380 If KWD is a number, get the corresponding match group."
6381 (if (numberp kwd) (setq kwd (match-string kwd)))
6382 (or (org-face-from-face-or-color
6383 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6384 'org-tag))
6386 (defun org-unfontify-region (beg end &optional maybe_loudly)
6387 "Remove fontification and activation overlays from links."
6388 (font-lock-default-unfontify-region beg end)
6389 (let* ((buffer-undo-list t)
6390 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6391 (inhibit-modification-hooks t)
6392 deactivate-mark buffer-file-name buffer-file-truename)
6393 (org-decompose-region beg end)
6394 (remove-text-properties beg end
6395 '(mouse-face t keymap t org-linked-text t
6396 invisible t intangible t
6397 org-no-flyspell t org-emphasis t))
6398 (org-remove-font-lock-display-properties beg end)))
6400 (defconst org-script-display '(((raise -0.3) (height 0.7))
6401 ((raise 0.3) (height 0.7))
6402 ((raise -0.5))
6403 ((raise 0.5)))
6404 "Display properties for showing superscripts and subscripts.")
6406 (defun org-remove-font-lock-display-properties (beg end)
6407 "Remove specific display properties that have been added by font lock.
6408 The will remove the raise properties that are used to show superscripts
6409 and subscripts."
6410 (let (next prop)
6411 (while (< beg end)
6412 (setq next (next-single-property-change beg 'display nil end)
6413 prop (get-text-property beg 'display))
6414 (if (member prop org-script-display)
6415 (put-text-property beg next 'display nil))
6416 (setq beg next))))
6418 (defun org-raise-scripts (limit)
6419 "Add raise properties to sub/superscripts."
6420 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6421 (if (re-search-forward
6422 (if (eq org-use-sub-superscripts t)
6423 org-match-substring-regexp
6424 org-match-substring-with-braces-regexp)
6425 limit t)
6426 (let* ((pos (point)) table-p comment-p
6427 (mpos (match-beginning 3))
6428 (emph-p (get-text-property mpos 'org-emphasis))
6429 (link-p (get-text-property mpos 'mouse-face))
6430 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6431 (goto-char (point-at-bol))
6432 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6433 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6434 (goto-char pos)
6435 ;; Handle a_b^c
6436 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6437 (if (or comment-p emph-p link-p keyw-p)
6439 (put-text-property (match-beginning 3) (match-end 0)
6440 'display
6441 (if (equal (char-after (match-beginning 2)) ?^)
6442 (nth (if table-p 3 1) org-script-display)
6443 (nth (if table-p 2 0) org-script-display)))
6444 (add-text-properties (match-beginning 2) (match-end 2)
6445 (list 'invisible t
6446 'org-dwidth t 'org-dwidth-n 1))
6447 (if (and (eq (char-after (match-beginning 3)) ?{)
6448 (eq (char-before (match-end 3)) ?}))
6449 (progn
6450 (add-text-properties
6451 (match-beginning 3) (1+ (match-beginning 3))
6452 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6453 (add-text-properties
6454 (1- (match-end 3)) (match-end 3)
6455 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6456 t)))))
6458 ;;;; Visibility cycling, including org-goto and indirect buffer
6460 ;;; Cycling
6462 (defvar org-cycle-global-status nil)
6463 (make-variable-buffer-local 'org-cycle-global-status)
6464 (put 'org-cycle-global-status 'org-state t)
6465 (defvar org-cycle-subtree-status nil)
6466 (make-variable-buffer-local 'org-cycle-subtree-status)
6467 (put 'org-cycle-subtree-status 'org-state t)
6469 (defvar org-inlinetask-min-level)
6471 ;;;###autoload
6472 (defun org-cycle (&optional arg)
6473 "TAB-action and visibility cycling for Org-mode.
6475 This is the command invoked in Org-mode by the TAB key. Its main purpose
6476 is outline visibility cycling, but it also invokes other actions
6477 in special contexts.
6479 - When this function is called with a prefix argument, rotate the entire
6480 buffer through 3 states (global cycling)
6481 1. OVERVIEW: Show only top-level headlines.
6482 2. CONTENTS: Show all headlines of all levels, but no body text.
6483 3. SHOW ALL: Show everything.
6484 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6485 determined by the variable `org-startup-folded', and by any VISIBILITY
6486 properties in the buffer.
6487 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6488 including any drawers.
6490 - When inside a table, re-align the table and move to the next field.
6492 - When point is at the beginning of a headline, rotate the subtree started
6493 by this line through 3 different states (local cycling)
6494 1. FOLDED: Only the main headline is shown.
6495 2. CHILDREN: The main headline and the direct children are shown.
6496 From this state, you can move to one of the children
6497 and zoom in further.
6498 3. SUBTREE: Show the entire subtree, including body text.
6499 If there is no subtree, switch directly from CHILDREN to FOLDED.
6501 - When point is at the beginning of an empty headline and the variable
6502 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6503 of the headline by demoting and promoting it to likely levels. This
6504 speeds up creation document structure by pressing TAB once or several
6505 times right after creating a new headline.
6507 - When there is a numeric prefix, go up to a heading with level ARG, do
6508 a `show-subtree' and return to the previous cursor position. If ARG
6509 is negative, go up that many levels.
6511 - When point is not at the beginning of a headline, execute the global
6512 binding for TAB, which is re-indenting the line. See the option
6513 `org-cycle-emulate-tab' for details.
6515 - Special case: if point is at the beginning of the buffer and there is
6516 no headline in line 1, this function will act as if called with prefix arg
6517 (C-u TAB, same as S-TAB) also when called without prefix arg.
6518 But only if also the variable `org-cycle-global-at-bob' is t."
6519 (interactive "P")
6520 (org-load-modules-maybe)
6521 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6522 (and org-cycle-level-after-item/entry-creation
6523 (or (org-cycle-level)
6524 (org-cycle-item-indentation))))
6525 (let* (message-log-max ; Don't populate the *Messages* buffer
6526 (limit-level
6527 (or org-cycle-max-level
6528 (and (boundp 'org-inlinetask-min-level)
6529 org-inlinetask-min-level
6530 (1- org-inlinetask-min-level))))
6531 (nstars (and limit-level
6532 (if org-odd-levels-only
6533 (and limit-level (1- (* limit-level 2)))
6534 limit-level)))
6535 (org-outline-regexp
6536 (if (not (derived-mode-p 'org-mode))
6537 outline-regexp
6538 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6539 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6540 (not (looking-at org-outline-regexp))))
6541 (org-cycle-hook
6542 (if bob-special
6543 (delq 'org-optimize-window-after-visibility-change
6544 (copy-sequence org-cycle-hook))
6545 org-cycle-hook))
6546 (pos (point)))
6548 (if (or bob-special (equal arg '(4)))
6549 ;; special case: use global cycling
6550 (setq arg t))
6552 (cond
6554 ((equal arg '(16))
6555 (setq last-command 'dummy)
6556 (org-set-startup-visibility)
6557 (message "Startup visibility, plus VISIBILITY properties"))
6559 ((equal arg '(64))
6560 (show-all)
6561 (message "Entire buffer visible, including drawers"))
6563 ;; Table: enter it or move to the next field.
6564 ((org-at-table-p 'any)
6565 (if (org-at-table.el-p)
6566 (message "Use C-c ' to edit table.el tables")
6567 (if arg (org-table-edit-field t)
6568 (org-table-justify-field-maybe)
6569 (call-interactively 'org-table-next-field))))
6571 ((run-hook-with-args-until-success
6572 'org-tab-after-check-for-table-hook))
6574 ;; Global cycling: delegate to `org-cycle-internal-global'.
6575 ((eq arg t) (org-cycle-internal-global))
6577 ;; Drawers: delegate to `org-flag-drawer'.
6578 ((and org-drawers org-drawer-regexp
6579 (save-excursion
6580 (beginning-of-line 1)
6581 (looking-at org-drawer-regexp)))
6582 (org-flag-drawer ; toggle block visibility
6583 (not (get-char-property (match-end 0) 'invisible))))
6585 ;; Show-subtree, ARG levels up from here.
6586 ((integerp arg)
6587 (save-excursion
6588 (org-back-to-heading)
6589 (outline-up-heading (if (< arg 0) (- arg)
6590 (- (funcall outline-level) arg)))
6591 (org-show-subtree)))
6593 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6594 ((and (featurep 'org-inlinetask)
6595 (org-inlinetask-at-task-p)
6596 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6597 (org-inlinetask-toggle-visibility))
6599 ((org-try-cdlatex-tab))
6601 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6602 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6603 (save-excursion (beginning-of-line 1)
6604 (looking-at org-outline-regexp)))
6605 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6606 (org-cycle-internal-local))
6608 ;; From there: TAB emulation and template completion.
6609 (buffer-read-only (org-back-to-heading))
6611 ((run-hook-with-args-until-success
6612 'org-tab-after-check-for-cycling-hook))
6614 ((org-try-structure-completion))
6616 ((run-hook-with-args-until-success
6617 'org-tab-before-tab-emulation-hook))
6619 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6620 (or (not (bolp))
6621 (not (looking-at org-outline-regexp))))
6622 (call-interactively (global-key-binding "\t")))
6624 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6625 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6626 (or (and (eq org-cycle-emulate-tab 'white)
6627 (= (match-end 0) (point-at-eol)))
6628 (and (eq org-cycle-emulate-tab 'whitestart)
6629 (>= (match-end 0) pos))))
6631 (eq org-cycle-emulate-tab t))
6632 (call-interactively (global-key-binding "\t")))
6634 (t (save-excursion
6635 (org-back-to-heading)
6636 (org-cycle)))))))
6638 (defun org-cycle-internal-global ()
6639 "Do the global cycling action."
6640 ;; Hack to avoid display of messages for .org attachments in Gnus
6641 (let (message-log-max ; Don't populate the *Messages* buffer
6642 (ga (string-match "\\*fontification" (buffer-name))))
6643 (cond
6644 ((and (eq last-command this-command)
6645 (eq org-cycle-global-status 'overview))
6646 ;; We just created the overview - now do table of contents
6647 ;; This can be slow in very large buffers, so indicate action
6648 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6649 (unless ga (message "CONTENTS..."))
6650 (org-content)
6651 (unless ga (message "CONTENTS...done"))
6652 (setq org-cycle-global-status 'contents)
6653 (run-hook-with-args 'org-cycle-hook 'contents))
6655 ((and (eq last-command this-command)
6656 (eq org-cycle-global-status 'contents))
6657 ;; We just showed the table of contents - now show everything
6658 (run-hook-with-args 'org-pre-cycle-hook 'all)
6659 (show-all)
6660 (unless ga (message "SHOW ALL"))
6661 (setq org-cycle-global-status 'all)
6662 (run-hook-with-args 'org-cycle-hook 'all))
6665 ;; Default action: go to overview
6666 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6667 (org-overview)
6668 (unless ga (message "OVERVIEW"))
6669 (setq org-cycle-global-status 'overview)
6670 (run-hook-with-args 'org-cycle-hook 'overview)))))
6672 (defun org-cycle-internal-local ()
6673 "Do the local cycling action."
6674 (let (message-log-max ; Don't populate the *Messages* buffer
6675 (goal-column 0) eoh eol eos has-children children-skipped struct)
6676 ;; First, determine end of headline (EOH), end of subtree or item
6677 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6678 (save-excursion
6679 (if (org-at-item-p)
6680 (progn
6681 (beginning-of-line)
6682 (setq struct (org-list-struct))
6683 (setq eoh (point-at-eol))
6684 (setq eos (org-list-get-item-end-before-blank (point) struct))
6685 (setq has-children (org-list-has-child-p (point) struct)))
6686 (org-back-to-heading)
6687 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6688 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6689 (setq has-children
6690 (or (save-excursion
6691 (let ((level (funcall outline-level)))
6692 (outline-next-heading)
6693 (and (org-at-heading-p t)
6694 (> (funcall outline-level) level))))
6695 (save-excursion
6696 (org-list-search-forward (org-item-beginning-re) eos t)))))
6697 ;; Determine end invisible part of buffer (EOL)
6698 (beginning-of-line 2)
6699 ;; XEmacs doesn't have `next-single-char-property-change'
6700 (if (featurep 'xemacs)
6701 (while (and (not (eobp)) ;; this is like `next-line'
6702 (get-char-property (1- (point)) 'invisible))
6703 (beginning-of-line 2))
6704 (while (and (not (eobp)) ;; this is like `next-line'
6705 (get-char-property (1- (point)) 'invisible))
6706 (goto-char (next-single-char-property-change (point) 'invisible))
6707 (and (eolp) (beginning-of-line 2))))
6708 (setq eol (point)))
6709 ;; Find out what to do next and set `this-command'
6710 (cond
6711 ((= eos eoh)
6712 ;; Nothing is hidden behind this heading
6713 (unless (org-before-first-heading-p)
6714 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6715 (message "EMPTY ENTRY")
6716 (setq org-cycle-subtree-status nil)
6717 (save-excursion
6718 (goto-char eos)
6719 (outline-next-heading)
6720 (if (outline-invisible-p) (org-flag-heading nil))))
6721 ((and (or (>= eol eos)
6722 (not (string-match "\\S-" (buffer-substring eol eos))))
6723 (or has-children
6724 (not (setq children-skipped
6725 org-cycle-skip-children-state-if-no-children))))
6726 ;; Entire subtree is hidden in one line: children view
6727 (unless (org-before-first-heading-p)
6728 (run-hook-with-args 'org-pre-cycle-hook 'children))
6729 (if (org-at-item-p)
6730 (org-list-set-item-visibility (point-at-bol) struct 'children)
6731 (org-show-entry)
6732 (org-with-limited-levels (show-children))
6733 ;; FIXME: This slows down the func way too much.
6734 ;; How keep drawers hidden in subtree anyway?
6735 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6736 ;; (org-cycle-hide-drawers 'subtree))
6738 ;; Fold every list in subtree to top-level items.
6739 (when (eq org-cycle-include-plain-lists 'integrate)
6740 (save-excursion
6741 (org-back-to-heading)
6742 (while (org-list-search-forward (org-item-beginning-re) eos t)
6743 (beginning-of-line 1)
6744 (let* ((struct (org-list-struct))
6745 (prevs (org-list-prevs-alist struct))
6746 (end (org-list-get-bottom-point struct)))
6747 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6748 (org-list-get-all-items (point) struct prevs))
6749 (goto-char (if (< end eos) end eos)))))))
6750 (message "CHILDREN")
6751 (save-excursion
6752 (goto-char eos)
6753 (outline-next-heading)
6754 (if (outline-invisible-p) (org-flag-heading nil)))
6755 (setq org-cycle-subtree-status 'children)
6756 (unless (org-before-first-heading-p)
6757 (run-hook-with-args 'org-cycle-hook 'children)))
6758 ((or children-skipped
6759 (and (eq last-command this-command)
6760 (eq org-cycle-subtree-status 'children)))
6761 ;; We just showed the children, or no children are there,
6762 ;; now show everything.
6763 (unless (org-before-first-heading-p)
6764 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6765 (outline-flag-region eoh eos nil)
6766 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6767 (setq org-cycle-subtree-status 'subtree)
6768 (unless (org-before-first-heading-p)
6769 (run-hook-with-args 'org-cycle-hook 'subtree)))
6771 ;; Default action: hide the subtree.
6772 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6773 (outline-flag-region eoh eos t)
6774 (message "FOLDED")
6775 (setq org-cycle-subtree-status 'folded)
6776 (unless (org-before-first-heading-p)
6777 (run-hook-with-args 'org-cycle-hook 'folded))))))
6779 ;;;###autoload
6780 (defun org-global-cycle (&optional arg)
6781 "Cycle the global visibility. For details see `org-cycle'.
6782 With \\[universal-argument] prefix arg, switch to startup visibility.
6783 With a numeric prefix, show all headlines up to that level."
6784 (interactive "P")
6785 (let ((org-cycle-include-plain-lists
6786 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6787 (cond
6788 ((integerp arg)
6789 (show-all)
6790 (hide-sublevels arg)
6791 (setq org-cycle-global-status 'contents))
6792 ((equal arg '(4))
6793 (org-set-startup-visibility)
6794 (message "Startup visibility, plus VISIBILITY properties."))
6796 (org-cycle '(4))))))
6798 (defun org-set-startup-visibility ()
6799 "Set the visibility required by startup options and properties."
6800 (cond
6801 ((eq org-startup-folded t)
6802 (org-cycle '(4)))
6803 ((eq org-startup-folded 'content)
6804 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6805 (org-cycle '(4)) (org-cycle '(4)))))
6806 (unless (eq org-startup-folded 'showeverything)
6807 (if org-hide-block-startup (org-hide-block-all))
6808 (org-set-visibility-according-to-property 'no-cleanup)
6809 (org-cycle-hide-archived-subtrees 'all)
6810 (org-cycle-hide-drawers 'all)
6811 (org-cycle-show-empty-lines t)))
6813 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6814 "Switch subtree visibilities according to :VISIBILITY: property."
6815 (interactive)
6816 (let (org-show-entry-below state)
6817 (save-excursion
6818 (goto-char (point-min))
6819 (while (re-search-forward
6820 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6821 nil t)
6822 (setq state (match-string 1))
6823 (save-excursion
6824 (org-back-to-heading t)
6825 (hide-subtree)
6826 (org-reveal)
6827 (cond
6828 ((equal state '("fold" "folded"))
6829 (hide-subtree))
6830 ((equal state "children")
6831 (org-show-hidden-entry)
6832 (show-children))
6833 ((equal state "content")
6834 (save-excursion
6835 (save-restriction
6836 (org-narrow-to-subtree)
6837 (org-content))))
6838 ((member state '("all" "showall"))
6839 (show-subtree)))))
6840 (unless no-cleanup
6841 (org-cycle-hide-archived-subtrees 'all)
6842 (org-cycle-hide-drawers 'all)
6843 (org-cycle-show-empty-lines 'all)))))
6845 ;; This function uses outline-regexp instead of the more fundamental
6846 ;; org-outline-regexp so that org-cycle-global works outside of Org
6847 ;; buffers, where outline-regexp is needed.
6848 (defun org-overview ()
6849 "Switch to overview mode, showing only top-level headlines.
6850 Really, this shows all headlines with level equal or greater than the level
6851 of the first headline in the buffer. This is important, because if the
6852 first headline is not level one, then (hide-sublevels 1) gives confusing
6853 results."
6854 (interactive)
6855 (let ((l (org-current-line))
6856 (level (save-excursion
6857 (goto-char (point-min))
6858 (if (re-search-forward (concat "^" outline-regexp) nil t)
6859 (progn
6860 (goto-char (match-beginning 0))
6861 (funcall outline-level))))))
6862 (and level (hide-sublevels level))
6863 (recenter '(4))
6864 (org-goto-line l)))
6866 (defun org-content (&optional arg)
6867 "Show all headlines in the buffer, like a table of contents.
6868 With numerical argument N, show content up to level N."
6869 (interactive "P")
6870 (save-excursion
6871 ;; Visit all headings and show their offspring
6872 (and (integerp arg) (org-overview))
6873 (goto-char (point-max))
6874 (catch 'exit
6875 (while (and (progn (condition-case nil
6876 (outline-previous-visible-heading 1)
6877 (error (goto-char (point-min))))
6879 (looking-at org-outline-regexp))
6880 (if (integerp arg)
6881 (show-children (1- arg))
6882 (show-branches))
6883 (if (bobp) (throw 'exit nil))))))
6886 (defun org-optimize-window-after-visibility-change (state)
6887 "Adjust the window after a change in outline visibility.
6888 This function is the default value of the hook `org-cycle-hook'."
6889 (when (get-buffer-window (current-buffer))
6890 (cond
6891 ((eq state 'content) nil)
6892 ((eq state 'all) nil)
6893 ((eq state 'folded) nil)
6894 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6895 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6897 (defun org-remove-empty-overlays-at (pos)
6898 "Remove outline overlays that do not contain non-white stuff."
6899 (mapc
6900 (lambda (o)
6901 (and (eq 'outline (overlay-get o 'invisible))
6902 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6903 (overlay-end o))))
6904 (delete-overlay o)))
6905 (overlays-at pos)))
6907 (defun org-clean-visibility-after-subtree-move ()
6908 "Fix visibility issues after moving a subtree."
6909 ;; First, find a reasonable region to look at:
6910 ;; Start two siblings above, end three below
6911 (let* ((beg (save-excursion
6912 (and (org-get-last-sibling)
6913 (org-get-last-sibling))
6914 (point)))
6915 (end (save-excursion
6916 (and (org-get-next-sibling)
6917 (org-get-next-sibling)
6918 (org-get-next-sibling))
6919 (if (org-at-heading-p)
6920 (point-at-eol)
6921 (point))))
6922 (level (looking-at "\\*+"))
6923 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6924 (save-excursion
6925 (save-restriction
6926 (narrow-to-region beg end)
6927 (when re
6928 ;; Properly fold already folded siblings
6929 (goto-char (point-min))
6930 (while (re-search-forward re nil t)
6931 (if (and (not (outline-invisible-p))
6932 (save-excursion
6933 (goto-char (point-at-eol)) (outline-invisible-p)))
6934 (hide-entry))))
6935 (org-cycle-show-empty-lines 'overview)
6936 (org-cycle-hide-drawers 'overview)))))
6938 (defun org-cycle-show-empty-lines (state)
6939 "Show empty lines above all visible headlines.
6940 The region to be covered depends on STATE when called through
6941 `org-cycle-hook'. Lisp program can use t for STATE to get the
6942 entire buffer covered. Note that an empty line is only shown if there
6943 are at least `org-cycle-separator-lines' empty lines before the headline."
6944 (when (not (= org-cycle-separator-lines 0))
6945 (save-excursion
6946 (let* ((n (abs org-cycle-separator-lines))
6947 (re (cond
6948 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6949 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6950 (t (let ((ns (number-to-string (- n 2))))
6951 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6952 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6953 beg end b e)
6954 (cond
6955 ((memq state '(overview contents t))
6956 (setq beg (point-min) end (point-max)))
6957 ((memq state '(children folded))
6958 (setq beg (point) end (progn (org-end-of-subtree t t)
6959 (beginning-of-line 2)
6960 (point)))))
6961 (when beg
6962 (goto-char beg)
6963 (while (re-search-forward re end t)
6964 (unless (get-char-property (match-end 1) 'invisible)
6965 (setq e (match-end 1))
6966 (if (< org-cycle-separator-lines 0)
6967 (setq b (save-excursion
6968 (goto-char (match-beginning 0))
6969 (org-back-over-empty-lines)
6970 (if (save-excursion
6971 (goto-char (max (point-min) (1- (point))))
6972 (org-at-heading-p))
6973 (1- (point))
6974 (point))))
6975 (setq b (match-beginning 1)))
6976 (outline-flag-region b e nil)))))))
6977 ;; Never hide empty lines at the end of the file.
6978 (save-excursion
6979 (goto-char (point-max))
6980 (outline-previous-heading)
6981 (outline-end-of-heading)
6982 (if (and (looking-at "[ \t\n]+")
6983 (= (match-end 0) (point-max)))
6984 (outline-flag-region (point) (match-end 0) nil))))
6986 (defun org-show-empty-lines-in-parent ()
6987 "Move to the parent and re-show empty lines before visible headlines."
6988 (save-excursion
6989 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6990 (org-cycle-show-empty-lines context))))
6992 (defun org-files-list ()
6993 "Return `org-agenda-files' list, plus all open org-mode files.
6994 This is useful for operations that need to scan all of a user's
6995 open and agenda-wise Org files."
6996 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6997 (dolist (buf (buffer-list))
6998 (with-current-buffer buf
6999 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7000 (let ((file (expand-file-name (buffer-file-name))))
7001 (unless (member file files)
7002 (push file files))))))
7003 files))
7005 (defsubst org-entry-beginning-position ()
7006 "Return the beginning position of the current entry."
7007 (save-excursion (outline-back-to-heading t) (point)))
7009 (defsubst org-entry-end-position ()
7010 "Return the end position of the current entry."
7011 (save-excursion (outline-next-heading) (point)))
7013 (defun org-cycle-hide-drawers (state)
7014 "Re-hide all drawers after a visibility state change."
7015 (when (and (derived-mode-p 'org-mode)
7016 (not (memq state '(overview folded contents))))
7017 (save-excursion
7018 (let* ((globalp (memq state '(contents all)))
7019 (beg (if globalp (point-min) (point)))
7020 (end (if globalp (point-max)
7021 (if (eq state 'children)
7022 (save-excursion (outline-next-heading) (point))
7023 (org-end-of-subtree t)))))
7024 (goto-char beg)
7025 (while (re-search-forward org-drawer-regexp end t)
7026 (org-flag-drawer t))))))
7028 (defun org-cycle-hide-inline-tasks (state)
7029 "Re-hide inline task when switching to 'contents visibility state."
7030 (when (and (eq state 'contents)
7031 (boundp 'org-inlinetask-min-level)
7032 org-inlinetask-min-level)
7033 (hide-sublevels (1- org-inlinetask-min-level))))
7035 (defun org-flag-drawer (flag)
7036 "When FLAG is non-nil, hide the drawer we are within.
7037 Otherwise make it visible."
7038 (save-excursion
7039 (beginning-of-line 1)
7040 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
7041 (let ((b (match-end 0)))
7042 (if (re-search-forward
7043 "^[ \t]*:END:"
7044 (save-excursion (outline-next-heading) (point)) t)
7045 (outline-flag-region b (point-at-eol) flag)
7046 (user-error ":END: line missing at position %s" b))))))
7048 (defun org-subtree-end-visible-p ()
7049 "Is the end of the current subtree visible?"
7050 (pos-visible-in-window-p
7051 (save-excursion (org-end-of-subtree t) (point))))
7053 (defun org-first-headline-recenter (&optional N)
7054 "Move cursor to the first headline and recenter the headline.
7055 Optional argument N means put the headline into the Nth line of the window."
7056 (goto-char (point-min))
7057 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7058 (beginning-of-line)
7059 (recenter (prefix-numeric-value N))))
7061 ;;; Saving and restoring visibility
7063 (defun org-outline-overlay-data (&optional use-markers)
7064 "Return a list of the locations of all outline overlays.
7065 These are overlays with the `invisible' property value `outline'.
7066 The return value is a list of cons cells, with start and stop
7067 positions for each overlay.
7068 If USE-MARKERS is set, return the positions as markers."
7069 (let (beg end)
7070 (save-excursion
7071 (save-restriction
7072 (widen)
7073 (delq nil
7074 (mapcar (lambda (o)
7075 (when (eq (overlay-get o 'invisible) 'outline)
7076 (setq beg (overlay-start o)
7077 end (overlay-end o))
7078 (and beg end (> end beg)
7079 (if use-markers
7080 (cons (move-marker (make-marker) beg)
7081 (move-marker (make-marker) end))
7082 (cons beg end)))))
7083 (overlays-in (point-min) (point-max))))))))
7085 (defun org-set-outline-overlay-data (data)
7086 "Create visibility overlays for all positions in DATA.
7087 DATA should have been made by `org-outline-overlay-data'."
7088 (let (o)
7089 (save-excursion
7090 (save-restriction
7091 (widen)
7092 (show-all)
7093 (mapc (lambda (c)
7094 (outline-flag-region (car c) (cdr c) t))
7095 data)))))
7097 ;;; Folding of blocks
7099 (defvar org-hide-block-overlays nil
7100 "Overlays hiding blocks.")
7101 (make-variable-buffer-local 'org-hide-block-overlays)
7103 (defun org-block-map (function &optional start end)
7104 "Call FUNCTION at the head of all source blocks in the current buffer.
7105 Optional arguments START and END can be used to limit the range."
7106 (let ((start (or start (point-min)))
7107 (end (or end (point-max))))
7108 (save-excursion
7109 (goto-char start)
7110 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7111 (save-excursion
7112 (save-match-data
7113 (goto-char (match-beginning 0))
7114 (funcall function)))))))
7116 (defun org-hide-block-toggle-all ()
7117 "Toggle the visibility of all blocks in the current buffer."
7118 (org-block-map #'org-hide-block-toggle))
7120 (defun org-hide-block-all ()
7121 "Fold all blocks in the current buffer."
7122 (interactive)
7123 (org-show-block-all)
7124 (org-block-map #'org-hide-block-toggle-maybe))
7126 (defun org-show-block-all ()
7127 "Unfold all blocks in the current buffer."
7128 (interactive)
7129 (mapc 'delete-overlay org-hide-block-overlays)
7130 (setq org-hide-block-overlays nil))
7132 (defun org-hide-block-toggle-maybe ()
7133 "Toggle visibility of block at point."
7134 (interactive)
7135 (let ((case-fold-search t))
7136 (if (save-excursion
7137 (beginning-of-line 1)
7138 (looking-at org-block-regexp))
7139 (progn (org-hide-block-toggle)
7140 t) ;; to signal that we took action
7141 nil))) ;; to signal that we did not
7143 (defun org-hide-block-toggle (&optional force)
7144 "Toggle the visibility of the current block."
7145 (interactive)
7146 (save-excursion
7147 (beginning-of-line)
7148 (if (re-search-forward org-block-regexp nil t)
7149 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7150 (end (match-end 0)) ;; end of entire body
7152 (if (memq t (mapcar (lambda (overlay)
7153 (eq (overlay-get overlay 'invisible)
7154 'org-hide-block))
7155 (overlays-at start)))
7156 (if (or (not force) (eq force 'off))
7157 (mapc (lambda (ov)
7158 (when (member ov org-hide-block-overlays)
7159 (setq org-hide-block-overlays
7160 (delq ov org-hide-block-overlays)))
7161 (when (eq (overlay-get ov 'invisible)
7162 'org-hide-block)
7163 (delete-overlay ov)))
7164 (overlays-at start)))
7165 (setq ov (make-overlay start end))
7166 (overlay-put ov 'invisible 'org-hide-block)
7167 ;; make the block accessible to isearch
7168 (overlay-put
7169 ov 'isearch-open-invisible
7170 (lambda (ov)
7171 (when (member ov org-hide-block-overlays)
7172 (setq org-hide-block-overlays
7173 (delq ov org-hide-block-overlays)))
7174 (when (eq (overlay-get ov 'invisible)
7175 'org-hide-block)
7176 (delete-overlay ov))))
7177 (push ov org-hide-block-overlays)))
7178 (user-error "Not looking at a source block"))))
7180 ;; org-tab-after-check-for-cycling-hook
7181 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7182 ;; Remove overlays when changing major mode
7183 (add-hook 'org-mode-hook
7184 (lambda () (org-add-hook 'change-major-mode-hook
7185 'org-show-block-all 'append 'local)))
7187 ;;; Org-goto
7189 (defvar org-goto-window-configuration nil)
7190 (defvar org-goto-marker nil)
7191 (defvar org-goto-map)
7192 (defun org-goto-map ()
7193 "Set the keymap `org-goto'."
7194 (setq org-goto-map
7195 (let ((map (make-sparse-keymap)))
7196 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7197 mouse-drag-region universal-argument org-occur))
7198 cmd)
7199 (while (setq cmd (pop cmds))
7200 (substitute-key-definition cmd cmd map global-map)))
7201 (suppress-keymap map)
7202 (org-defkey map "\C-m" 'org-goto-ret)
7203 (org-defkey map [(return)] 'org-goto-ret)
7204 (org-defkey map [(left)] 'org-goto-left)
7205 (org-defkey map [(right)] 'org-goto-right)
7206 (org-defkey map [(control ?g)] 'org-goto-quit)
7207 (org-defkey map "\C-i" 'org-cycle)
7208 (org-defkey map [(tab)] 'org-cycle)
7209 (org-defkey map [(down)] 'outline-next-visible-heading)
7210 (org-defkey map [(up)] 'outline-previous-visible-heading)
7211 (if org-goto-auto-isearch
7212 (if (fboundp 'define-key-after)
7213 (define-key-after map [t] 'org-goto-local-auto-isearch)
7214 nil)
7215 (org-defkey map "q" 'org-goto-quit)
7216 (org-defkey map "n" 'outline-next-visible-heading)
7217 (org-defkey map "p" 'outline-previous-visible-heading)
7218 (org-defkey map "f" 'outline-forward-same-level)
7219 (org-defkey map "b" 'outline-backward-same-level)
7220 (org-defkey map "u" 'outline-up-heading))
7221 (org-defkey map "/" 'org-occur)
7222 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7223 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7224 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7225 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7226 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7227 map)))
7229 (defconst org-goto-help
7230 "Browse buffer copy, to find location or copy text.%s
7231 RET=jump to location C-g=quit and return to previous location
7232 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7234 (defvar org-goto-start-pos) ; dynamically scoped parameter
7236 (defun org-goto (&optional alternative-interface)
7237 "Look up a different location in the current file, keeping current visibility.
7239 When you want look-up or go to a different location in a
7240 document, the fastest way is often to fold the entire buffer and
7241 then dive into the tree. This method has the disadvantage, that
7242 the previous location will be folded, which may not be what you
7243 want.
7245 This command works around this by showing a copy of the current
7246 buffer in an indirect buffer, in overview mode. You can dive
7247 into the tree in that copy, use org-occur and incremental search
7248 to find a location. When pressing RET or `Q', the command
7249 returns to the original buffer in which the visibility is still
7250 unchanged. After RET it will also jump to the location selected
7251 in the indirect buffer and expose the headline hierarchy above.
7253 With a prefix argument, use the alternative interface: e.g. if
7254 `org-goto-interface' is 'outline use 'outline-path-completion."
7255 (interactive "P")
7256 (org-goto-map)
7257 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7258 (org-refile-use-outline-path t)
7259 (org-refile-target-verify-function nil)
7260 (interface
7261 (if (not alternative-interface)
7262 org-goto-interface
7263 (if (eq org-goto-interface 'outline)
7264 'outline-path-completion
7265 'outline)))
7266 (org-goto-start-pos (point))
7267 (selected-point
7268 (if (eq interface 'outline)
7269 (car (org-get-location (current-buffer) org-goto-help))
7270 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7271 (org-refile-check-position pa)
7272 (nth 3 pa)))))
7273 (if selected-point
7274 (progn
7275 (org-mark-ring-push org-goto-start-pos)
7276 (goto-char selected-point)
7277 (if (or (outline-invisible-p) (org-invisible-p2))
7278 (org-show-context 'org-goto)))
7279 (message "Quit"))))
7281 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7282 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7283 (defvar org-goto-local-auto-isearch-map) ; defined below
7285 (defun org-get-location (buf help)
7286 "Let the user select a location in the Org-mode buffer BUF.
7287 This function uses a recursive edit. It returns the selected position
7288 or nil."
7289 (org-no-popups
7290 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7291 (isearch-hide-immediately nil)
7292 (isearch-search-fun-function
7293 (lambda () 'org-goto-local-search-headings))
7294 (org-goto-selected-point org-goto-exit-command))
7295 (save-excursion
7296 (save-window-excursion
7297 (delete-other-windows)
7298 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7299 (org-pop-to-buffer-same-window
7300 (condition-case nil
7301 (make-indirect-buffer (current-buffer) "*org-goto*")
7302 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7303 (with-output-to-temp-buffer "*Org Help*"
7304 (princ (format help (if org-goto-auto-isearch
7305 " Just type for auto-isearch."
7306 " n/p/f/b/u to navigate, q to quit."))))
7307 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7308 (setq buffer-read-only nil)
7309 (let ((org-startup-truncated t)
7310 (org-startup-folded nil)
7311 (org-startup-align-all-tables nil))
7312 (org-mode)
7313 (org-overview))
7314 (setq buffer-read-only t)
7315 (if (and (boundp 'org-goto-start-pos)
7316 (integer-or-marker-p org-goto-start-pos))
7317 (let ((org-show-hierarchy-above t)
7318 (org-show-siblings t)
7319 (org-show-following-heading t))
7320 (goto-char org-goto-start-pos)
7321 (and (outline-invisible-p) (org-show-context)))
7322 (goto-char (point-min)))
7323 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7324 (message "Select location and press RET")
7325 (use-local-map org-goto-map)
7326 (recursive-edit)))
7327 (kill-buffer "*org-goto*")
7328 (cons org-goto-selected-point org-goto-exit-command))))
7330 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7331 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7332 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7333 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7335 (defun org-goto-local-search-headings (string bound noerror)
7336 "Search and make sure that any matches are in headlines."
7337 (catch 'return
7338 (while (if isearch-forward
7339 (search-forward string bound noerror)
7340 (search-backward string bound noerror))
7341 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7342 (and (member :headline context)
7343 (not (member :tags context))))
7344 (throw 'return (point))))))
7346 (defun org-goto-local-auto-isearch ()
7347 "Start isearch."
7348 (interactive)
7349 (goto-char (point-min))
7350 (let ((keys (this-command-keys)))
7351 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7352 (isearch-mode t)
7353 (isearch-process-search-char (string-to-char keys)))))
7355 (defun org-goto-ret (&optional arg)
7356 "Finish `org-goto' by going to the new location."
7357 (interactive "P")
7358 (setq org-goto-selected-point (point)
7359 org-goto-exit-command 'return)
7360 (throw 'exit nil))
7362 (defun org-goto-left ()
7363 "Finish `org-goto' by going to the new location."
7364 (interactive)
7365 (if (org-at-heading-p)
7366 (progn
7367 (beginning-of-line 1)
7368 (setq org-goto-selected-point (point)
7369 org-goto-exit-command 'left)
7370 (throw 'exit nil))
7371 (user-error "Not on a heading")))
7373 (defun org-goto-right ()
7374 "Finish `org-goto' by going to the new location."
7375 (interactive)
7376 (if (org-at-heading-p)
7377 (progn
7378 (setq org-goto-selected-point (point)
7379 org-goto-exit-command 'right)
7380 (throw 'exit nil))
7381 (user-error "Not on a heading")))
7383 (defun org-goto-quit ()
7384 "Finish `org-goto' without cursor motion."
7385 (interactive)
7386 (setq org-goto-selected-point nil)
7387 (setq org-goto-exit-command 'quit)
7388 (throw 'exit nil))
7390 ;;; Indirect buffer display of subtrees
7392 (defvar org-indirect-dedicated-frame nil
7393 "This is the frame being used for indirect tree display.")
7394 (defvar org-last-indirect-buffer nil)
7396 (defun org-tree-to-indirect-buffer (&optional arg)
7397 "Create indirect buffer and narrow it to current subtree.
7398 With a numerical prefix ARG, go up to this level and then take that tree.
7399 If ARG is negative, go up that many levels.
7401 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7402 indirect buffer previously made with this command, to avoid proliferation of
7403 indirect buffers. However, when you call the command with a \
7404 \\[universal-argument] prefix, or
7405 when `org-indirect-buffer-display' is `new-frame', the last buffer
7406 is kept so that you can work with several indirect buffers at the same time.
7407 If `org-indirect-buffer-display' is `dedicated-frame', the \
7408 \\[universal-argument] prefix also
7409 requests that a new frame be made for the new buffer, so that the dedicated
7410 frame is not changed."
7411 (interactive "P")
7412 (let ((cbuf (current-buffer))
7413 (cwin (selected-window))
7414 (pos (point))
7415 beg end level heading ibuf)
7416 (save-excursion
7417 (org-back-to-heading t)
7418 (when (numberp arg)
7419 (setq level (org-outline-level))
7420 (if (< arg 0) (setq arg (+ level arg)))
7421 (while (> (setq level (org-outline-level)) arg)
7422 (org-up-heading-safe)))
7423 (setq beg (point)
7424 heading (org-get-heading))
7425 (org-end-of-subtree t t)
7426 (if (org-at-heading-p) (backward-char 1))
7427 (setq end (point)))
7428 (if (and (buffer-live-p org-last-indirect-buffer)
7429 (not (eq org-indirect-buffer-display 'new-frame))
7430 (not arg))
7431 (kill-buffer org-last-indirect-buffer))
7432 (setq ibuf (org-get-indirect-buffer cbuf)
7433 org-last-indirect-buffer ibuf)
7434 (cond
7435 ((or (eq org-indirect-buffer-display 'new-frame)
7436 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7437 (select-frame (make-frame))
7438 (delete-other-windows)
7439 (org-pop-to-buffer-same-window ibuf)
7440 (org-set-frame-title heading))
7441 ((eq org-indirect-buffer-display 'dedicated-frame)
7442 (raise-frame
7443 (select-frame (or (and org-indirect-dedicated-frame
7444 (frame-live-p org-indirect-dedicated-frame)
7445 org-indirect-dedicated-frame)
7446 (setq org-indirect-dedicated-frame (make-frame)))))
7447 (delete-other-windows)
7448 (org-pop-to-buffer-same-window ibuf)
7449 (org-set-frame-title (concat "Indirect: " heading)))
7450 ((eq org-indirect-buffer-display 'current-window)
7451 (org-pop-to-buffer-same-window ibuf))
7452 ((eq org-indirect-buffer-display 'other-window)
7453 (pop-to-buffer ibuf))
7454 (t (error "Invalid value")))
7455 (if (featurep 'xemacs)
7456 (save-excursion (org-mode) (turn-on-font-lock)))
7457 (narrow-to-region beg end)
7458 (show-all)
7459 (goto-char pos)
7460 (run-hook-with-args 'org-cycle-hook 'all)
7461 (and (window-live-p cwin) (select-window cwin))))
7463 (defun org-get-indirect-buffer (&optional buffer)
7464 (setq buffer (or buffer (current-buffer)))
7465 (let ((n 1) (base (buffer-name buffer)) bname)
7466 (while (buffer-live-p
7467 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7468 (setq n (1+ n)))
7469 (condition-case nil
7470 (make-indirect-buffer buffer bname 'clone)
7471 (error (make-indirect-buffer buffer bname)))))
7473 (defun org-set-frame-title (title)
7474 "Set the title of the current frame to the string TITLE."
7475 ;; FIXME: how to name a single frame in XEmacs???
7476 (unless (featurep 'xemacs)
7477 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7479 ;;;; Structure editing
7481 ;;; Inserting headlines
7483 (defun org-previous-line-empty-p (&optional next)
7484 "Is the previous line a blank line?
7485 When NEXT is non-nil, check the next line instead."
7486 (save-excursion
7487 (and (not (bobp))
7488 (or (beginning-of-line (if next 2 0)) t)
7489 (save-match-data
7490 (looking-at "[ \t]*$")))))
7492 (defun org-insert-heading (&optional arg invisible-ok)
7493 "Insert a new heading or item with same depth at point.
7494 If point is in a plain list and ARG is nil, create a new list item.
7495 With one universal prefix argument, insert a heading even in lists.
7496 With two universal prefix arguments, insert the heading at the end
7497 of the parent subtree.
7499 If point is at the beginning of a headline, insert a sibling before
7500 the current headline. If point is not at the beginning, split the line
7501 and create a new headline with the text in the current line after point
7502 \(see `org-M-RET-may-split-line' on how to modify this behavior).
7504 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7505 This is important for non-interactive uses of the command."
7506 (interactive "P")
7507 (if (org-called-interactively-p 'any) (org-reveal))
7508 (cond
7509 ((or (= (buffer-size) 0)
7510 (and (not (save-excursion
7511 (and (ignore-errors (org-back-to-heading invisible-ok))
7512 (org-at-heading-p))))
7513 (or arg (not (org-in-item-p)))))
7514 (insert
7515 (if (org-previous-line-empty-p) "" "\n")
7516 (if (org-in-src-block-p) ",* " "* "))
7517 (run-hooks 'org-insert-heading-hook))
7518 ((or arg
7519 (and (not (org-in-item-p)) org-insert-heading-respect-content)
7520 (not (org-insert-item
7521 (save-excursion
7522 (beginning-of-line)
7523 (looking-at org-list-full-item-re)
7524 (match-string 3)))))
7525 (let (begn endn)
7526 (when (org-buffer-narrowed-p)
7527 (setq begn (point-min) endn (point-max))
7528 (widen))
7529 (let* ((empty-line-p nil)
7530 (eops (equal arg '(16))) ; insert at end of parent subtree
7531 (org-insert-heading-respect-content
7532 (or (not (null arg)) org-insert-heading-respect-content))
7533 (level nil)
7534 (on-heading (org-at-heading-p))
7535 ;; Get a level to fall back on
7536 (fix-level
7537 (save-excursion
7538 (org-back-to-heading t)
7539 (looking-at org-outline-regexp)
7540 (make-string (1- (length (match-string 0))) ?*)))
7541 (on-empty-line
7542 (save-excursion (beginning-of-line 1) (looking-at "^\\s-*$")))
7543 (head (save-excursion
7544 (condition-case nil
7545 (progn
7546 (org-back-to-heading invisible-ok)
7547 (when (and (not on-heading)
7548 (featurep 'org-inlinetask)
7549 (integerp org-inlinetask-min-level)
7550 (>= (length (match-string 0))
7551 org-inlinetask-min-level))
7552 ;; Find a heading level before the inline task
7553 (while (and (setq level (org-up-heading-safe))
7554 (>= level org-inlinetask-min-level)))
7555 (if (org-at-heading-p)
7556 (org-back-to-heading invisible-ok)
7557 (error "This should not happen")))
7558 (unless (and (save-excursion
7559 (save-match-data
7560 (org-backward-heading-same-level 1 invisible-ok))
7561 (= (point) (match-beginning 0)))
7562 (not (org-previous-line-empty-p t)))
7563 (setq empty-line-p (org-previous-line-empty-p)))
7564 (match-string 0))
7565 (error (or fix-level "* ")))))
7566 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7567 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7568 pos hide-previous previous-pos)
7569 (if ;; At the beginning of a heading, open a new line for insertion
7570 (and (bolp) (org-at-heading-p)
7571 (not eops)
7572 (or (bobp)
7573 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7574 (open-line (if blank 2 1))
7575 (save-excursion
7576 (setq previous-pos (point-at-bol))
7577 (end-of-line)
7578 (setq hide-previous (outline-invisible-p)))
7579 (and org-insert-heading-respect-content
7580 (save-excursion
7581 (while (outline-invisible-p)
7582 (org-show-subtree)
7583 (org-up-heading-safe))))
7584 (let ((split
7585 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7586 (save-excursion
7587 (let ((p (point)))
7588 (goto-char (point-at-bol))
7589 (and (looking-at org-complex-heading-regexp)
7590 (match-beginning 4)
7591 (> p (match-beginning 4)))))))
7592 tags pos)
7593 (cond
7594 ;; Insert a new line, possibly at end of parent subtree
7595 ((and (not arg) (not on-heading) (not on-empty-line)
7596 (not (save-excursion
7597 (beginning-of-line 1)
7598 (or (looking-at org-list-full-item-re)
7599 ;; Don't convert :end: lines to headline
7600 (looking-at "^\\s-*:end:")
7601 (looking-at "^\\s-*#\\+end_?")))))
7602 (beginning-of-line 1))
7603 (org-insert-heading-respect-content
7604 (if (not eops)
7605 (progn
7606 (org-end-of-subtree nil t)
7607 (and (looking-at "^\\*") (backward-char 1))
7608 (while (and (not (bobp))
7609 ;; Don't delete spaces in empty headlines
7610 (not (looking-back org-outline-regexp))
7611 (member (char-before) '(?\ ?\t ?\n)))
7612 (backward-delete-char 1)))
7613 (let ((p (point)))
7614 (org-up-heading-safe)
7615 (if (= p (point))
7616 (goto-char (point-max))
7617 (org-end-of-subtree nil t))))
7618 (when (featurep 'org-inlinetask)
7619 (while (and (not (eobp))
7620 (looking-at "\\(\\*+\\)[ \t]+")
7621 (>= (length (match-string 1))
7622 org-inlinetask-min-level))
7623 (org-end-of-subtree nil t)))
7624 (or (bolp) (newline))
7625 (or (org-previous-line-empty-p)
7626 (and blank (newline)))
7627 (if (or empty-line-p eops) (open-line 1)))
7628 ;; Insert a headling containing text after point
7629 ((org-at-heading-p)
7630 (when hide-previous
7631 (show-children)
7632 (org-show-entry))
7633 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7634 (setq tags (and (match-end 2) (match-string 2)))
7635 (and (match-end 1)
7636 (delete-region (match-beginning 1) (match-end 1)))
7637 (setq pos (point-at-bol))
7638 (or split (end-of-line 1))
7639 (delete-horizontal-space)
7640 (if (string-match "\\`\\*+\\'"
7641 (buffer-substring (point-at-bol) (point)))
7642 (insert " "))
7643 (newline (if blank 2 1))
7644 (when tags
7645 (save-excursion
7646 (goto-char pos)
7647 (end-of-line 1)
7648 (insert " " tags)
7649 (org-set-tags nil 'align))))
7651 (or split (end-of-line 1))
7652 (newline (cond ((and blank (not on-empty-line)) 2)
7653 (blank 1)
7654 (on-empty-line 0) (t 1)))))))
7655 (insert head) (just-one-space)
7656 (setq pos (point))
7657 (end-of-line 1)
7658 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7659 (when (and org-insert-heading-respect-content hide-previous)
7660 (save-excursion
7661 (goto-char previous-pos)
7662 (hide-subtree)))
7663 (when (and begn endn)
7664 (narrow-to-region (min (point) begn) (max (point) endn)))
7665 (run-hooks 'org-insert-heading-hook))))))
7667 (defun org-get-heading (&optional no-tags no-todo)
7668 "Return the heading of the current entry, without the stars.
7669 When NO-TAGS is non-nil, don't include tags.
7670 When NO-TODO is non-nil, don't include TODO keywords."
7671 (save-excursion
7672 (org-back-to-heading t)
7673 (cond
7674 ((and no-tags no-todo)
7675 (looking-at org-complex-heading-regexp)
7676 (match-string 4))
7677 (no-tags
7678 (looking-at (concat org-outline-regexp
7679 "\\(.*?\\)"
7680 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7681 (match-string 1))
7682 (no-todo
7683 (looking-at org-todo-line-regexp)
7684 (match-string 3))
7685 (t (looking-at org-heading-regexp)
7686 (match-string 2)))))
7688 (defvar orgstruct-mode) ; defined below
7690 (defun org-heading-components ()
7691 "Return the components of the current heading.
7692 This is a list with the following elements:
7693 - the level as an integer
7694 - the reduced level, different if `org-odd-levels-only' is set.
7695 - the TODO keyword, or nil
7696 - the priority character, like ?A, or nil if no priority is given
7697 - the headline text itself, or the tags string if no headline text
7698 - the tags string, or nil."
7699 (save-excursion
7700 (org-back-to-heading t)
7701 (if (let (case-fold-search)
7702 (looking-at
7703 (if orgstruct-mode
7704 org-heading-regexp
7705 org-complex-heading-regexp)))
7706 (if orgstruct-mode
7707 (list (length (match-string 1))
7708 (org-reduced-level (length (match-string 1)))
7711 (match-string 2)
7712 nil)
7713 (list (length (match-string 1))
7714 (org-reduced-level (length (match-string 1)))
7715 (org-match-string-no-properties 2)
7716 (and (match-end 3) (aref (match-string 3) 2))
7717 (org-match-string-no-properties 4)
7718 (org-match-string-no-properties 5))))))
7720 (defun org-get-entry ()
7721 "Get the entry text, after heading, entire subtree."
7722 (save-excursion
7723 (org-back-to-heading t)
7724 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7726 (defun org-insert-heading-after-current ()
7727 "Insert a new heading with same level as current, after current subtree."
7728 (interactive)
7729 (org-back-to-heading)
7730 (org-insert-heading)
7731 (org-move-subtree-down)
7732 (end-of-line 1))
7734 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7735 "Insert heading with `org-insert-heading-respect-content' set to t."
7736 (interactive "P")
7737 (let ((org-insert-heading-respect-content t))
7738 (org-insert-heading arg invisible-ok)))
7740 (defun org-insert-todo-heading-respect-content (&optional force-state)
7741 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7742 (interactive "P")
7743 (let ((org-insert-heading-respect-content t))
7744 (org-insert-todo-heading force-state t)))
7746 (defun org-insert-todo-heading (arg &optional force-heading)
7747 "Insert a new heading with the same level and TODO state as current heading.
7748 If the heading has no TODO state, or if the state is DONE, use the first
7749 state (TODO by default). Also one prefix arg, force first state. With two
7750 prefix args, force inserting at the end of the parent subtree."
7751 (interactive "P")
7752 (when (or force-heading (not (org-insert-item 'checkbox)))
7753 (org-insert-heading (or (and (equal arg '(16)) '(16))
7754 force-heading))
7755 (save-excursion
7756 (org-back-to-heading)
7757 (outline-previous-heading)
7758 (looking-at org-todo-line-regexp))
7759 (let*
7760 ((new-mark-x
7761 (if (or arg
7762 (not (match-beginning 2))
7763 (member (match-string 2) org-done-keywords))
7764 (car org-todo-keywords-1)
7765 (match-string 2)))
7766 (new-mark
7768 (run-hook-with-args-until-success
7769 'org-todo-get-default-hook new-mark-x nil)
7770 new-mark-x)))
7771 (beginning-of-line 1)
7772 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7773 (if org-treat-insert-todo-heading-as-state-change
7774 (org-todo new-mark)
7775 (insert new-mark " "))))
7776 (when org-provide-todo-statistics
7777 (org-update-parent-todo-statistics))))
7779 (defun org-insert-subheading (arg)
7780 "Insert a new subheading and demote it.
7781 Works for outline headings and for plain lists alike."
7782 (interactive "P")
7783 (org-insert-heading arg)
7784 (cond
7785 ((org-at-heading-p) (org-do-demote))
7786 ((org-at-item-p) (org-indent-item))))
7788 (defun org-insert-todo-subheading (arg)
7789 "Insert a new subheading with TODO keyword or checkbox and demote it.
7790 Works for outline headings and for plain lists alike."
7791 (interactive "P")
7792 (org-insert-todo-heading arg)
7793 (cond
7794 ((org-at-heading-p) (org-do-demote))
7795 ((org-at-item-p) (org-indent-item))))
7797 ;;; Promotion and Demotion
7799 (defvar org-after-demote-entry-hook nil
7800 "Hook run after an entry has been demoted.
7801 The cursor will be at the beginning of the entry.
7802 When a subtree is being demoted, the hook will be called for each node.")
7804 (defvar org-after-promote-entry-hook nil
7805 "Hook run after an entry has been promoted.
7806 The cursor will be at the beginning of the entry.
7807 When a subtree is being promoted, the hook will be called for each node.")
7809 (defun org-promote-subtree ()
7810 "Promote the entire subtree.
7811 See also `org-promote'."
7812 (interactive)
7813 (save-excursion
7814 (org-with-limited-levels (org-map-tree 'org-promote)))
7815 (org-fix-position-after-promote))
7817 (defun org-demote-subtree ()
7818 "Demote the entire subtree. See `org-demote'.
7819 See also `org-promote'."
7820 (interactive)
7821 (save-excursion
7822 (org-with-limited-levels (org-map-tree 'org-demote)))
7823 (org-fix-position-after-promote))
7826 (defun org-do-promote ()
7827 "Promote the current heading higher up the tree.
7828 If the region is active in `transient-mark-mode', promote all headings
7829 in the region."
7830 (interactive)
7831 (save-excursion
7832 (if (org-region-active-p)
7833 (org-map-region 'org-promote (region-beginning) (region-end))
7834 (org-promote)))
7835 (org-fix-position-after-promote))
7837 (defun org-do-demote ()
7838 "Demote the current heading lower down the tree.
7839 If the region is active in `transient-mark-mode', demote all headings
7840 in the region."
7841 (interactive)
7842 (save-excursion
7843 (if (org-region-active-p)
7844 (org-map-region 'org-demote (region-beginning) (region-end))
7845 (org-demote)))
7846 (org-fix-position-after-promote))
7848 (defun org-fix-position-after-promote ()
7849 "Make sure that after pro/demotion cursor position is right."
7850 (let ((pos (point)))
7851 (when (save-excursion
7852 (beginning-of-line 1)
7853 (looking-at org-todo-line-regexp)
7854 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7855 (cond ((eobp) (insert " "))
7856 ((eolp) (insert " "))
7857 ((equal (char-after) ?\ ) (forward-char 1))))))
7859 (defun org-current-level ()
7860 "Return the level of the current entry, or nil if before the first headline.
7861 The level is the number of stars at the beginning of the headline."
7862 (save-excursion
7863 (org-with-limited-levels
7864 (if (ignore-errors (org-back-to-heading t))
7865 (funcall outline-level)))))
7867 (defun org-get-previous-line-level ()
7868 "Return the outline depth of the last headline before the current line.
7869 Returns 0 for the first headline in the buffer, and nil if before the
7870 first headline."
7871 (let ((current-level (org-current-level))
7872 (prev-level (when (> (line-number-at-pos) 1)
7873 (save-excursion
7874 (beginning-of-line 0)
7875 (org-current-level)))))
7876 (cond ((null current-level) nil) ; Before first headline
7877 ((null prev-level) 0) ; At first headline
7878 (prev-level))))
7880 (defun org-reduced-level (l)
7881 "Compute the effective level of a heading.
7882 This takes into account the setting of `org-odd-levels-only'."
7883 (cond
7884 ((zerop l) 0)
7885 (org-odd-levels-only (1+ (floor (/ l 2))))
7886 (t l)))
7888 (defun org-level-increment ()
7889 "Return the number of stars that will be added or removed at a
7890 time to headlines when structure editing, based on the value of
7891 `org-odd-levels-only'."
7892 (if org-odd-levels-only 2 1))
7894 (defun org-get-valid-level (level &optional change)
7895 "Rectify a level change under the influence of `org-odd-levels-only'
7896 LEVEL is a current level, CHANGE is by how much the level should be
7897 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7898 even level numbers will become the next higher odd number."
7899 (if org-odd-levels-only
7900 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7901 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7902 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7903 (max 1 (+ level (or change 0)))))
7905 (if (boundp 'define-obsolete-function-alias)
7906 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7907 (define-obsolete-function-alias 'org-get-legal-level
7908 'org-get-valid-level)
7909 (define-obsolete-function-alias 'org-get-legal-level
7910 'org-get-valid-level "23.1")))
7912 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7913 ;; ̀org-with-limited-levels'
7914 (defun org-promote ()
7915 "Promote the current heading higher up the tree.
7916 If the region is active in `transient-mark-mode', promote all headings
7917 in the region."
7918 (org-back-to-heading t)
7919 (let* ((level (save-match-data (funcall outline-level)))
7920 (after-change-functions (remove 'flyspell-after-change-function
7921 after-change-functions))
7922 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7923 (diff (abs (- level (length up-head) -1))))
7924 (cond ((and (= level 1) org-called-with-limited-levels
7925 org-allow-promoting-top-level-subtree)
7926 (replace-match "# " nil t))
7927 ((= level 1)
7928 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
7929 (t (replace-match up-head nil t)))
7930 ;; Fixup tag positioning
7931 (unless (= level 1)
7932 (and org-auto-align-tags (org-set-tags nil t))
7933 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7934 (run-hooks 'org-after-promote-entry-hook)))
7936 (defun org-demote ()
7937 "Demote the current heading lower down the tree.
7938 If the region is active in `transient-mark-mode', demote all headings
7939 in the region."
7940 (org-back-to-heading t)
7941 (let* ((level (save-match-data (funcall outline-level)))
7942 (after-change-functions (remove 'flyspell-after-change-function
7943 after-change-functions))
7944 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7945 (diff (abs (- level (length down-head) -1))))
7946 (replace-match down-head nil t)
7947 ;; Fixup tag positioning
7948 (and org-auto-align-tags (org-set-tags nil t))
7949 (if org-adapt-indentation (org-fixup-indentation diff))
7950 (run-hooks 'org-after-demote-entry-hook)))
7952 (defun org-cycle-level ()
7953 "Cycle the level of an empty headline through possible states.
7954 This goes first to child, then to parent, level, then up the hierarchy.
7955 After top level, it switches back to sibling level."
7956 (interactive)
7957 (let ((org-adapt-indentation nil))
7958 (when (org-point-at-end-of-empty-headline)
7959 (setq this-command 'org-cycle-level) ; Only needed for caching
7960 (let ((cur-level (org-current-level))
7961 (prev-level (org-get-previous-line-level)))
7962 (cond
7963 ;; If first headline in file, promote to top-level.
7964 ((= prev-level 0)
7965 (loop repeat (/ (- cur-level 1) (org-level-increment))
7966 do (org-do-promote)))
7967 ;; If same level as prev, demote one.
7968 ((= prev-level cur-level)
7969 (org-do-demote))
7970 ;; If parent is top-level, promote to top level if not already.
7971 ((= prev-level 1)
7972 (loop repeat (/ (- cur-level 1) (org-level-increment))
7973 do (org-do-promote)))
7974 ;; If top-level, return to prev-level.
7975 ((= cur-level 1)
7976 (loop repeat (/ (- prev-level 1) (org-level-increment))
7977 do (org-do-demote)))
7978 ;; If less than prev-level, promote one.
7979 ((< cur-level prev-level)
7980 (org-do-promote))
7981 ;; If deeper than prev-level, promote until higher than
7982 ;; prev-level.
7983 ((> cur-level prev-level)
7984 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7985 do (org-do-promote))))
7986 t))))
7988 (defun org-map-tree (fun)
7989 "Call FUN for every heading underneath the current one."
7990 (org-back-to-heading)
7991 (let ((level (funcall outline-level)))
7992 (save-excursion
7993 (funcall fun)
7994 (while (and (progn
7995 (outline-next-heading)
7996 (> (funcall outline-level) level))
7997 (not (eobp)))
7998 (funcall fun)))))
8000 (defun org-map-region (fun beg end)
8001 "Call FUN for every heading between BEG and END."
8002 (let ((org-ignore-region t))
8003 (save-excursion
8004 (setq end (copy-marker end))
8005 (goto-char beg)
8006 (if (and (re-search-forward org-outline-regexp-bol nil t)
8007 (< (point) end))
8008 (funcall fun))
8009 (while (and (progn
8010 (outline-next-heading)
8011 (< (point) end))
8012 (not (eobp)))
8013 (funcall fun)))))
8015 (defvar org-property-end-re) ; silence byte-compiler
8016 (defun org-fixup-indentation (diff)
8017 "Change the indentation in the current entry by DIFF.
8018 However, if any line in the current entry has no indentation, or if it
8019 would end up with no indentation after the change, nothing at all is done."
8020 (save-excursion
8021 (let ((end (save-excursion (outline-next-heading)
8022 (point-marker)))
8023 (prohibit (if (> diff 0)
8024 "^\\S-"
8025 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8026 col)
8027 (unless (save-excursion (end-of-line 1)
8028 (re-search-forward prohibit end t))
8029 (while (and (< (point) end)
8030 (re-search-forward "^[ \t]+" end t))
8031 (goto-char (match-end 0))
8032 (setq col (current-column))
8033 (if (< diff 0) (replace-match ""))
8034 (org-indent-to-column (+ diff col))))
8035 (move-marker end nil))))
8037 (defun org-convert-to-odd-levels ()
8038 "Convert an org-mode file with all levels allowed to one with odd levels.
8039 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8040 level 5 etc."
8041 (interactive)
8042 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8043 (let ((outline-level 'org-outline-level)
8044 (org-odd-levels-only nil) n)
8045 (save-excursion
8046 (goto-char (point-min))
8047 (while (re-search-forward "^\\*\\*+ " nil t)
8048 (setq n (- (length (match-string 0)) 2))
8049 (while (>= (setq n (1- n)) 0)
8050 (org-demote))
8051 (end-of-line 1))))))
8053 (defun org-convert-to-oddeven-levels ()
8054 "Convert an org-mode file with only odd levels to one with odd/even levels.
8055 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8056 file contains a section with an even level, conversion would
8057 destroy the structure of the file. An error is signaled in this
8058 case."
8059 (interactive)
8060 (goto-char (point-min))
8061 ;; First check if there are no even levels
8062 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8063 (org-show-context t)
8064 (error "Not all levels are odd in this file. Conversion not possible"))
8065 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8066 (let ((outline-regexp org-outline-regexp)
8067 (outline-level 'org-outline-level)
8068 (org-odd-levels-only nil) n)
8069 (save-excursion
8070 (goto-char (point-min))
8071 (while (re-search-forward "^\\*\\*+ " nil t)
8072 (setq n (/ (1- (length (match-string 0))) 2))
8073 (while (>= (setq n (1- n)) 0)
8074 (org-promote))
8075 (end-of-line 1))))))
8077 (defun org-tr-level (n)
8078 "Make N odd if required."
8079 (if org-odd-levels-only (1+ (/ n 2)) n))
8081 ;;; Vertical tree motion, cutting and pasting of subtrees
8083 (defun org-move-subtree-up (&optional arg)
8084 "Move the current subtree up past ARG headlines of the same level."
8085 (interactive "p")
8086 (org-move-subtree-down (- (prefix-numeric-value arg))))
8088 (defun org-move-subtree-down (&optional arg)
8089 "Move the current subtree down past ARG headlines of the same level."
8090 (interactive "p")
8091 (setq arg (prefix-numeric-value arg))
8092 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8093 'org-get-last-sibling))
8094 (ins-point (make-marker))
8095 (cnt (abs arg))
8096 (col (current-column))
8097 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8098 ;; Select the tree
8099 (org-back-to-heading)
8100 (setq beg0 (point))
8101 (save-excursion
8102 (setq ne-beg (org-back-over-empty-lines))
8103 (setq beg (point)))
8104 (save-match-data
8105 (save-excursion (outline-end-of-heading)
8106 (setq folded (outline-invisible-p)))
8107 (outline-end-of-subtree))
8108 (outline-next-heading)
8109 (setq ne-end (org-back-over-empty-lines))
8110 (setq end (point))
8111 (goto-char beg0)
8112 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8113 ;; include less whitespace
8114 (save-excursion
8115 (goto-char beg)
8116 (forward-line (- ne-beg ne-end))
8117 (setq beg (point))))
8118 ;; Find insertion point, with error handling
8119 (while (> cnt 0)
8120 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8121 (progn (goto-char beg0)
8122 (user-error "Cannot move past superior level or buffer limit")))
8123 (setq cnt (1- cnt)))
8124 (if (> arg 0)
8125 ;; Moving forward - still need to move over subtree
8126 (progn (org-end-of-subtree t t)
8127 (save-excursion
8128 (org-back-over-empty-lines)
8129 (or (bolp) (newline)))))
8130 (setq ne-ins (org-back-over-empty-lines))
8131 (move-marker ins-point (point))
8132 (setq txt (buffer-substring beg end))
8133 (org-save-markers-in-region beg end)
8134 (delete-region beg end)
8135 (org-remove-empty-overlays-at beg)
8136 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8137 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8138 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8139 (let ((bbb (point)))
8140 (insert-before-markers txt)
8141 (org-reinstall-markers-in-region bbb)
8142 (move-marker ins-point bbb))
8143 (or (bolp) (insert "\n"))
8144 (setq ins-end (point))
8145 (goto-char ins-point)
8146 (org-skip-whitespace)
8147 (when (and (< arg 0)
8148 (org-first-sibling-p)
8149 (> ne-ins ne-beg))
8150 ;; Move whitespace back to beginning
8151 (save-excursion
8152 (goto-char ins-end)
8153 (let ((kill-whole-line t))
8154 (kill-line (- ne-ins ne-beg)) (point)))
8155 (insert (make-string (- ne-ins ne-beg) ?\n)))
8156 (move-marker ins-point nil)
8157 (if folded
8158 (hide-subtree)
8159 (org-show-entry)
8160 (show-children)
8161 (org-cycle-hide-drawers 'children))
8162 (org-clean-visibility-after-subtree-move)
8163 ;; move back to the initial column we were at
8164 (move-to-column col)))
8166 (defvar org-subtree-clip ""
8167 "Clipboard for cut and paste of subtrees.
8168 This is actually only a copy of the kill, because we use the normal kill
8169 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8171 (defvar org-subtree-clip-folded nil
8172 "Was the last copied subtree folded?
8173 This is used to fold the tree back after pasting.")
8175 (defun org-cut-subtree (&optional n)
8176 "Cut the current subtree into the clipboard.
8177 With prefix arg N, cut this many sequential subtrees.
8178 This is a short-hand for marking the subtree and then cutting it."
8179 (interactive "p")
8180 (org-copy-subtree n 'cut))
8182 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8183 "Copy the current subtree it in the clipboard.
8184 With prefix arg N, copy this many sequential subtrees.
8185 This is a short-hand for marking the subtree and then copying it.
8186 If CUT is non-nil, actually cut the subtree.
8187 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8188 of some markers in the region, even if CUT is non-nil. This is
8189 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8190 (interactive "p")
8191 (let (beg end folded (beg0 (point)))
8192 (if (org-called-interactively-p 'any)
8193 (org-back-to-heading nil) ; take what looks like a subtree
8194 (org-back-to-heading t)) ; take what is really there
8195 (setq beg (point))
8196 (skip-chars-forward " \t\r\n")
8197 (save-match-data
8198 (if nosubtrees
8199 (outline-next-heading)
8200 (save-excursion (outline-end-of-heading)
8201 (setq folded (outline-invisible-p)))
8202 (condition-case nil
8203 (org-forward-heading-same-level (1- n) t)
8204 (error nil))
8205 (org-end-of-subtree t t)))
8206 (setq end (point))
8207 (goto-char beg0)
8208 (when (> end beg)
8209 (setq org-subtree-clip-folded folded)
8210 (when (or cut force-store-markers)
8211 (org-save-markers-in-region beg end))
8212 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8213 (setq org-subtree-clip (current-kill 0))
8214 (message "%s: Subtree(s) with %d characters"
8215 (if cut "Cut" "Copied")
8216 (length org-subtree-clip)))))
8218 (defun org-paste-subtree (&optional level tree for-yank)
8219 "Paste the clipboard as a subtree, with modification of headline level.
8220 The entire subtree is promoted or demoted in order to match a new headline
8221 level.
8223 If the cursor is at the beginning of a headline, the same level as
8224 that headline is used to paste the tree.
8226 If not, the new level is derived from the *visible* headings
8227 before and after the insertion point, and taken to be the inferior headline
8228 level of the two. So if the previous visible heading is level 3 and the
8229 next is level 4 (or vice versa), level 4 will be used for insertion.
8230 This makes sure that the subtree remains an independent subtree and does
8231 not swallow low level entries.
8233 You can also force a different level, either by using a numeric prefix
8234 argument, or by inserting the heading marker by hand. For example, if the
8235 cursor is after \"*****\", then the tree will be shifted to level 5.
8237 If optional TREE is given, use this text instead of the kill ring.
8239 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8240 move back over whitespace before inserting, and move point to the end of
8241 the inserted text when done."
8242 (interactive "P")
8243 (setq tree (or tree (and kill-ring (current-kill 0))))
8244 (unless (org-kill-is-subtree-p tree)
8245 (user-error "%s"
8246 (substitute-command-keys
8247 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8248 (org-with-limited-levels
8249 (let* ((visp (not (outline-invisible-p)))
8250 (txt tree)
8251 (^re_ "\\(\\*+\\)[ \t]*")
8252 (old-level (if (string-match org-outline-regexp-bol txt)
8253 (- (match-end 0) (match-beginning 0) 1)
8254 -1))
8255 (force-level (cond (level (prefix-numeric-value level))
8256 ((and (looking-at "[ \t]*$")
8257 (string-match
8258 "^\\*+$" (buffer-substring
8259 (point-at-bol) (point))))
8260 (- (match-end 1) (match-beginning 1)))
8261 ((and (bolp)
8262 (looking-at org-outline-regexp))
8263 (- (match-end 0) (point) 1))))
8264 (previous-level (save-excursion
8265 (condition-case nil
8266 (progn
8267 (outline-previous-visible-heading 1)
8268 (if (looking-at ^re_)
8269 (- (match-end 0) (match-beginning 0) 1)
8271 (error 1))))
8272 (next-level (save-excursion
8273 (condition-case nil
8274 (progn
8275 (or (looking-at org-outline-regexp)
8276 (outline-next-visible-heading 1))
8277 (if (looking-at ^re_)
8278 (- (match-end 0) (match-beginning 0) 1)
8280 (error 1))))
8281 (new-level (or force-level (max previous-level next-level)))
8282 (shift (if (or (= old-level -1)
8283 (= new-level -1)
8284 (= old-level new-level))
8286 (- new-level old-level)))
8287 (delta (if (> shift 0) -1 1))
8288 (func (if (> shift 0) 'org-demote 'org-promote))
8289 (org-odd-levels-only nil)
8290 beg end newend)
8291 ;; Remove the forced level indicator
8292 (if force-level
8293 (delete-region (point-at-bol) (point)))
8294 ;; Paste
8295 (beginning-of-line (if (bolp) 1 2))
8296 (setq beg (point))
8297 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8298 (insert-before-markers txt)
8299 (unless (string-match "\n\\'" txt) (insert "\n"))
8300 (setq newend (point))
8301 (org-reinstall-markers-in-region beg)
8302 (setq end (point))
8303 (goto-char beg)
8304 (skip-chars-forward " \t\n\r")
8305 (setq beg (point))
8306 (if (and (outline-invisible-p) visp)
8307 (save-excursion (outline-show-heading)))
8308 ;; Shift if necessary
8309 (unless (= shift 0)
8310 (save-restriction
8311 (narrow-to-region beg end)
8312 (while (not (= shift 0))
8313 (org-map-region func (point-min) (point-max))
8314 (setq shift (+ delta shift)))
8315 (goto-char (point-min))
8316 (setq newend (point-max))))
8317 (when (or (org-called-interactively-p 'interactive) for-yank)
8318 (message "Clipboard pasted as level %d subtree" new-level))
8319 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8320 kill-ring
8321 (eq org-subtree-clip (current-kill 0))
8322 org-subtree-clip-folded)
8323 ;; The tree was folded before it was killed/copied
8324 (hide-subtree))
8325 (and for-yank (goto-char newend)))))
8327 (defun org-kill-is-subtree-p (&optional txt)
8328 "Check if the current kill is an outline subtree, or a set of trees.
8329 Returns nil if kill does not start with a headline, or if the first
8330 headline level is not the largest headline level in the tree.
8331 So this will actually accept several entries of equal levels as well,
8332 which is OK for `org-paste-subtree'.
8333 If optional TXT is given, check this string instead of the current kill."
8334 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8335 (re (org-get-limited-outline-regexp))
8336 (^re (concat "^" re))
8337 (start-level (and kill
8338 (string-match
8339 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8340 kill)
8341 (- (match-end 2) (match-beginning 2) 1)))
8342 (start (1+ (or (match-beginning 2) -1))))
8343 (if (not start-level)
8344 (progn
8345 nil) ;; does not even start with a heading
8346 (catch 'exit
8347 (while (setq start (string-match ^re kill (1+ start)))
8348 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8349 (throw 'exit nil)))
8350 t))))
8352 (defvar org-markers-to-move nil
8353 "Markers that should be moved with a cut-and-paste operation.
8354 Those markers are stored together with their positions relative to
8355 the start of the region.")
8357 (defun org-save-markers-in-region (beg end)
8358 "Check markers in region.
8359 If these markers are between BEG and END, record their position relative
8360 to BEG, so that after moving the block of text, we can put the markers back
8361 into place.
8362 This function gets called just before an entry or tree gets cut from the
8363 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8364 called immediately, to move the markers with the entries."
8365 (setq org-markers-to-move nil)
8366 (when (featurep 'org-clock)
8367 (org-clock-save-markers-for-cut-and-paste beg end))
8368 (when (featurep 'org-agenda)
8369 (org-agenda-save-markers-for-cut-and-paste beg end)))
8371 (defun org-check-and-save-marker (marker beg end)
8372 "Check if MARKER is between BEG and END.
8373 If yes, remember the marker and the distance to BEG."
8374 (when (and (marker-buffer marker)
8375 (equal (marker-buffer marker) (current-buffer)))
8376 (if (and (>= marker beg) (< marker end))
8377 (push (cons marker (- marker beg)) org-markers-to-move))))
8379 (defun org-reinstall-markers-in-region (beg)
8380 "Move all remembered markers to their position relative to BEG."
8381 (mapc (lambda (x)
8382 (move-marker (car x) (+ beg (cdr x))))
8383 org-markers-to-move)
8384 (setq org-markers-to-move nil))
8386 (defun org-narrow-to-subtree ()
8387 "Narrow buffer to the current subtree."
8388 (interactive)
8389 (save-excursion
8390 (save-match-data
8391 (org-with-limited-levels
8392 (narrow-to-region
8393 (progn (org-back-to-heading t) (point))
8394 (progn (org-end-of-subtree t t)
8395 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8396 (point)))))))
8398 (defun org-narrow-to-block ()
8399 "Narrow buffer to the current block."
8400 (interactive)
8401 (let* ((case-fold-search t)
8402 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8403 "^[ \t]*#\\+end_.*")))
8404 (if blockp
8405 (narrow-to-region (car blockp) (cdr blockp))
8406 (user-error "Not in a block"))))
8408 (eval-when-compile
8409 (defvar org-property-drawer-re))
8411 (defvar org-property-start-re) ;; defined below
8412 (defun org-clone-subtree-with-time-shift (n &optional shift)
8413 "Clone the task (subtree) at point N times.
8414 The clones will be inserted as siblings.
8416 In interactive use, the user will be prompted for the number of
8417 clones to be produced. If the entry has a timestamp, the user
8418 will also be prompted for a time shift, which may be a repeater
8419 as used in time stamps, for example `+3d'. To disable this,
8420 you can call the function with a universal prefix argument.
8422 When a valid repeater is given and the entry contains any time
8423 stamps, the clones will become a sequence in time, with time
8424 stamps in the subtree shifted for each clone produced. If SHIFT
8425 is nil or the empty string, time stamps will be left alone. The
8426 ID property of the original subtree is removed.
8428 If the original subtree did contain time stamps with a repeater,
8429 the following will happen:
8430 - the repeater will be removed in each clone
8431 - an additional clone will be produced, with the current, unshifted
8432 date(s) in the entry.
8433 - the original entry will be placed *after* all the clones, with
8434 repeater intact.
8435 - the start days in the repeater in the original entry will be shifted
8436 to past the last clone.
8437 In this way you can spell out a number of instances of a repeating task,
8438 and still retain the repeater to cover future instances of the task."
8439 (interactive "nNumber of clones to produce: ")
8440 (let ((shift
8441 (or shift
8442 (if (and (not (equal current-prefix-arg '(4)))
8443 (save-excursion
8444 (re-search-forward org-ts-regexp-both
8445 (save-excursion
8446 (org-end-of-subtree t)
8447 (point)) t)))
8448 (read-from-minibuffer
8449 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8450 ""))) ;; No time shift
8451 (n-no-remove -1)
8452 (drawer-re org-drawer-regexp)
8453 beg end template task idprop
8454 shift-n shift-what doshift nmin nmax)
8455 (if (not (and (integerp n) (> n 0)))
8456 (error "Invalid number of replications %s" n))
8457 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8458 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8459 shift)))
8460 (error "Invalid shift specification %s" shift))
8461 (when doshift
8462 (setq shift-n (string-to-number (match-string 1 shift))
8463 shift-what (cdr (assoc (match-string 2 shift)
8464 '(("d" . day) ("w" . week)
8465 ("m" . month) ("y" . year))))))
8466 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8467 (setq nmin 1 nmax n)
8468 (org-back-to-heading t)
8469 (setq beg (point))
8470 (setq idprop (org-entry-get nil "ID"))
8471 (org-end-of-subtree t t)
8472 (or (bolp) (insert "\n"))
8473 (setq end (point))
8474 (setq template (buffer-substring beg end))
8475 (when (and doshift
8476 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8477 (delete-region beg end)
8478 (setq end beg)
8479 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8480 (goto-char end)
8481 (loop for n from nmin to nmax do
8482 ;; prepare clone
8483 (with-temp-buffer
8484 (insert template)
8485 (org-mode)
8486 (goto-char (point-min))
8487 (org-show-subtree)
8488 (and idprop (if org-clone-delete-id
8489 (org-entry-delete nil "ID")
8490 (org-id-get-create t)))
8491 (unless (= n 0)
8492 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8493 (kill-whole-line))
8494 (goto-char (point-min))
8495 (while (re-search-forward drawer-re nil t)
8496 (mapc (lambda (d)
8497 (org-remove-empty-drawer-at d (point))) org-drawers)))
8498 (goto-char (point-min))
8499 (when doshift
8500 (while (re-search-forward org-ts-regexp-both nil t)
8501 (org-timestamp-change (* n shift-n) shift-what))
8502 (unless (= n n-no-remove)
8503 (goto-char (point-min))
8504 (while (re-search-forward org-ts-regexp nil t)
8505 (save-excursion
8506 (goto-char (match-beginning 0))
8507 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8508 (delete-region (match-beginning 1) (match-end 1)))))))
8509 (setq task (buffer-string)))
8510 (insert task))
8511 (goto-char beg)))
8513 ;;; Outline Sorting
8515 (defun org-sort (with-case)
8516 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8517 Optional argument WITH-CASE means sort case-sensitively."
8518 (interactive "P")
8519 (cond
8520 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8521 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8523 (org-call-with-arg 'org-sort-entries with-case))))
8525 (defun org-sort-remove-invisible (s)
8526 "Remove invisible links from string S."
8527 (remove-text-properties 0 (length s) org-rm-props s)
8528 (while (string-match org-bracket-link-regexp s)
8529 (setq s (replace-match (if (match-end 2)
8530 (match-string 3 s)
8531 (match-string 1 s)) t t s)))
8532 (let ((st (format " %s " s)))
8533 (while (string-match org-emph-re st)
8534 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8535 (setq s (substring st 1 -1)))
8538 (defvar org-priority-regexp) ; defined later in the file
8540 (defvar org-after-sorting-entries-or-items-hook nil
8541 "Hook that is run after a bunch of entries or items have been sorted.
8542 When children are sorted, the cursor is in the parent line when this
8543 hook gets called. When a region or a plain list is sorted, the cursor
8544 will be in the first entry of the sorted region/list.")
8546 (defun org-sort-entries
8547 (&optional with-case sorting-type getkey-func compare-func property)
8548 "Sort entries on a certain level of an outline tree.
8549 If there is an active region, the entries in the region are sorted.
8550 Else, if the cursor is before the first entry, sort the top-level items.
8551 Else, the children of the entry at point are sorted.
8553 Sorting can be alphabetically, numerically, by date/time as given by
8554 a time stamp, by a property, by priority order, or by a custom function.
8556 The command prompts for the sorting type unless it has been given to the
8557 function through the SORTING-TYPE argument, which needs to be a character,
8558 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8559 precise meaning of each character:
8561 n Numerically, by converting the beginning of the entry/item to a number.
8562 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8563 o By order of TODO keywords.
8564 t By date/time, either the first active time stamp in the entry, or, if
8565 none exist, by the first inactive one.
8566 s By the scheduled date/time.
8567 d By deadline date/time.
8568 c By creation time, which is assumed to be the first inactive time stamp
8569 at the beginning of a line.
8570 p By priority according to the cookie.
8571 r By the value of a property.
8573 Capital letters will reverse the sort order.
8575 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8576 called with point at the beginning of the record. It must return either
8577 a string or a number that should serve as the sorting key for that record.
8579 Comparing entries ignores case by default. However, with an optional argument
8580 WITH-CASE, the sorting considers case as well.
8582 Sorting is done against the visible part of the headlines, it ignores hidden
8583 links."
8584 (interactive "P")
8585 (let ((case-func (if with-case 'identity 'downcase))
8586 (cmstr
8587 ;; The clock marker is lost when using `sort-subr', let's
8588 ;; store the clocking string.
8589 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8590 (save-excursion
8591 (goto-char org-clock-marker)
8592 (looking-back "^.*") (match-string-no-properties 0))))
8593 start beg end stars re re2
8594 txt what tmp)
8595 ;; Find beginning and end of region to sort
8596 (cond
8597 ((org-region-active-p)
8598 ;; we will sort the region
8599 (setq end (region-end)
8600 what "region")
8601 (goto-char (region-beginning))
8602 (if (not (org-at-heading-p)) (outline-next-heading))
8603 (setq start (point)))
8604 ((or (org-at-heading-p)
8605 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8606 ;; we will sort the children of the current headline
8607 (org-back-to-heading)
8608 (setq start (point)
8609 end (progn (org-end-of-subtree t t)
8610 (or (bolp) (insert "\n"))
8611 (org-back-over-empty-lines)
8612 (point))
8613 what "children")
8614 (goto-char start)
8615 (show-subtree)
8616 (outline-next-heading))
8618 ;; we will sort the top-level entries in this file
8619 (goto-char (point-min))
8620 (or (org-at-heading-p) (outline-next-heading))
8621 (setq start (point))
8622 (goto-char (point-max))
8623 (beginning-of-line 1)
8624 (when (looking-at ".*?\\S-")
8625 ;; File ends in a non-white line
8626 (end-of-line 1)
8627 (insert "\n"))
8628 (setq end (point-max))
8629 (setq what "top-level")
8630 (goto-char start)
8631 (show-all)))
8633 (setq beg (point))
8634 (if (>= beg end) (user-error "Nothing to sort"))
8636 (looking-at "\\(\\*+\\)")
8637 (setq stars (match-string 1)
8638 re (concat "^" (regexp-quote stars) " +")
8639 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8640 txt (buffer-substring beg end))
8641 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8642 (if (and (not (equal stars "*")) (string-match re2 txt))
8643 (user-error "Region to sort contains a level above the first entry"))
8645 (unless sorting-type
8646 (message
8647 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8648 [t]ime [s]cheduled [d]eadline [c]reated
8649 A/N/P/R/O/F/T/S/D/C means reversed:"
8650 what)
8651 (setq sorting-type (read-char-exclusive))
8653 (unless getkey-func
8654 (and (= (downcase sorting-type) ?f)
8655 (setq getkey-func
8656 (org-icompleting-read "Sort using function: "
8657 obarray 'fboundp t nil nil))
8658 (setq getkey-func (intern getkey-func))))
8660 (and (= (downcase sorting-type) ?r)
8661 (not property)
8662 (setq property
8663 (org-icompleting-read "Property: "
8664 (mapcar 'list (org-buffer-property-keys t))
8665 nil t))))
8667 (message "Sorting entries...")
8669 (save-restriction
8670 (narrow-to-region start end)
8671 (let ((dcst (downcase sorting-type))
8672 (case-fold-search nil)
8673 (now (current-time)))
8674 (sort-subr
8675 (/= dcst sorting-type)
8676 ;; This function moves to the beginning character of the "record" to
8677 ;; be sorted.
8678 (lambda nil
8679 (if (re-search-forward re nil t)
8680 (goto-char (match-beginning 0))
8681 (goto-char (point-max))))
8682 ;; This function moves to the last character of the "record" being
8683 ;; sorted.
8684 (lambda nil
8685 (save-match-data
8686 (condition-case nil
8687 (outline-forward-same-level 1)
8688 (error
8689 (goto-char (point-max))))))
8690 ;; This function returns the value that gets sorted against.
8691 (lambda nil
8692 (cond
8693 ((= dcst ?n)
8694 (if (looking-at org-complex-heading-regexp)
8695 (string-to-number (org-sort-remove-invisible (match-string 4)))
8696 nil))
8697 ((= dcst ?a)
8698 (if (looking-at org-complex-heading-regexp)
8699 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8700 nil))
8701 ((= dcst ?t)
8702 (let ((end (save-excursion (outline-next-heading) (point))))
8703 (if (or (re-search-forward org-ts-regexp end t)
8704 (re-search-forward org-ts-regexp-both end t))
8705 (org-time-string-to-seconds (match-string 0))
8706 (org-float-time now))))
8707 ((= dcst ?c)
8708 (let ((end (save-excursion (outline-next-heading) (point))))
8709 (if (re-search-forward
8710 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8711 end t)
8712 (org-time-string-to-seconds (match-string 0))
8713 (org-float-time now))))
8714 ((= dcst ?s)
8715 (let ((end (save-excursion (outline-next-heading) (point))))
8716 (if (re-search-forward org-scheduled-time-regexp end t)
8717 (org-time-string-to-seconds (match-string 1))
8718 (org-float-time now))))
8719 ((= dcst ?d)
8720 (let ((end (save-excursion (outline-next-heading) (point))))
8721 (if (re-search-forward org-deadline-time-regexp end t)
8722 (org-time-string-to-seconds (match-string 1))
8723 (org-float-time now))))
8724 ((= dcst ?p)
8725 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8726 (string-to-char (match-string 2))
8727 org-default-priority))
8728 ((= dcst ?r)
8729 (or (org-entry-get nil property) ""))
8730 ((= dcst ?o)
8731 (if (looking-at org-complex-heading-regexp)
8732 (- 9999 (length (member (match-string 2)
8733 org-todo-keywords-1)))))
8734 ((= dcst ?f)
8735 (if getkey-func
8736 (progn
8737 (setq tmp (funcall getkey-func))
8738 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8739 tmp)
8740 (error "Invalid key function `%s'" getkey-func)))
8741 (t (error "Invalid sorting type `%c'" sorting-type))))
8743 (cond
8744 ((= dcst ?a) 'string<)
8745 ((= dcst ?f) compare-func)
8746 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8747 (run-hooks 'org-after-sorting-entries-or-items-hook)
8748 ;; Reset the clock marker if needed
8749 (when cmstr
8750 (save-excursion
8751 (goto-char start)
8752 (search-forward cmstr nil t)
8753 (move-marker org-clock-marker (point))))
8754 (message "Sorting entries...done")))
8756 (defun org-do-sort (table what &optional with-case sorting-type)
8757 "Sort TABLE of WHAT according to SORTING-TYPE.
8758 The user will be prompted for the SORTING-TYPE if the call to this
8759 function does not specify it. WHAT is only for the prompt, to indicate
8760 what is being sorted. The sorting key will be extracted from
8761 the car of the elements of the table.
8762 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8763 (unless sorting-type
8764 (message
8765 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8766 what)
8767 (setq sorting-type (read-char-exclusive)))
8768 (let ((dcst (downcase sorting-type))
8769 extractfun comparefun)
8770 ;; Define the appropriate functions
8771 (cond
8772 ((= dcst ?n)
8773 (setq extractfun 'string-to-number
8774 comparefun (if (= dcst sorting-type) '< '>)))
8775 ((= dcst ?a)
8776 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8777 (lambda(x) (downcase (org-sort-remove-invisible x))))
8778 comparefun (if (= dcst sorting-type)
8779 'string<
8780 (lambda (a b) (and (not (string< a b))
8781 (not (string= a b)))))))
8782 ((= dcst ?t)
8783 (setq extractfun
8784 (lambda (x)
8785 (if (or (string-match org-ts-regexp x)
8786 (string-match org-ts-regexp-both x))
8787 (org-float-time
8788 (org-time-string-to-time (match-string 0 x)))
8790 comparefun (if (= dcst sorting-type) '< '>)))
8791 (t (error "Invalid sorting type `%c'" sorting-type)))
8793 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8794 table)
8795 (lambda (a b) (funcall comparefun (car a) (car b))))))
8798 ;;; The orgstruct minor mode
8800 ;; Define a minor mode which can be used in other modes in order to
8801 ;; integrate the org-mode structure editing commands.
8803 ;; This is really a hack, because the org-mode structure commands use
8804 ;; keys which normally belong to the major mode. Here is how it
8805 ;; works: The minor mode defines all the keys necessary to operate the
8806 ;; structure commands, but wraps the commands into a function which
8807 ;; tests if the cursor is currently at a headline or a plain list
8808 ;; item. If that is the case, the structure command is used,
8809 ;; temporarily setting many Org-mode variables like regular
8810 ;; expressions for filling etc. However, when any of those keys is
8811 ;; used at a different location, function uses `key-binding' to look
8812 ;; up if the key has an associated command in another currently active
8813 ;; keymap (minor modes, major mode, global), and executes that
8814 ;; command. There might be problems if any of the keys is otherwise
8815 ;; used as a prefix key.
8817 (defcustom orgstruct-heading-prefix-regexp nil
8818 "Regexp that matches the custom prefix of Org headlines in
8819 orgstruct(++)-mode."
8820 :group 'org
8821 :version "24.4"
8822 :package-version '(Org . "8.0")
8823 :type 'string)
8824 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8826 (defcustom orgstruct-setup-hook nil
8827 "Hook run after orgstruct-mode-map is filled."
8828 :group 'org
8829 :version "24.4"
8830 :package-version '(Org . "8.0")
8831 :type 'hook)
8833 (defvar orgstruct-initialized nil)
8835 (defvar org-local-vars nil
8836 "List of local variables, for use by `orgstruct-mode'.")
8838 ;;;###autoload
8839 (define-minor-mode orgstruct-mode
8840 "Toggle the minor mode `orgstruct-mode'.
8841 This mode is for using Org-mode structure commands in other
8842 modes. The following keys behave as if Org-mode were active, if
8843 the cursor is on a headline, or on a plain list item (both as
8844 defined by Org-mode)."
8845 nil " OrgStruct" (make-sparse-keymap)
8846 (funcall (if orgstruct-mode
8847 'add-to-invisibility-spec
8848 'remove-from-invisibility-spec)
8849 '(outline . t))
8850 (when orgstruct-mode
8851 (org-load-modules-maybe)
8852 (unless orgstruct-initialized
8853 (orgstruct-setup)
8854 (setq orgstruct-initialized t))))
8856 ;;;###autoload
8857 (defun turn-on-orgstruct ()
8858 "Unconditionally turn on `orgstruct-mode'."
8859 (orgstruct-mode 1))
8861 (defvar org-fb-vars nil)
8862 (make-variable-buffer-local 'org-fb-vars)
8863 (defun orgstruct++-mode (&optional arg)
8864 "Toggle `orgstruct-mode', the enhanced version of it.
8865 In addition to setting orgstruct-mode, this also exports all
8866 indentation and autofilling variables from org-mode into the
8867 buffer. It will also recognize item context in multiline items."
8868 (interactive "P")
8869 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8870 (if (< arg 1)
8871 (progn (orgstruct-mode -1)
8872 (mapc (lambda(v)
8873 (org-set-local (car v)
8874 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8875 org-fb-vars))
8876 (orgstruct-mode 1)
8877 (setq org-fb-vars nil)
8878 (let (var val)
8879 (mapc
8880 (lambda (x)
8881 (when (string-match
8882 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8883 (symbol-name (car x)))
8884 (setq var (car x) val (nth 1 x))
8885 (push (list var `(quote ,(eval var))) org-fb-vars)
8886 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8887 org-local-vars)
8888 (org-set-local 'orgstruct-is-++ t))))
8890 (defvar orgstruct-is-++ nil
8891 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8892 (make-variable-buffer-local 'orgstruct-is-++)
8894 ;;;###autoload
8895 (defun turn-on-orgstruct++ ()
8896 "Unconditionally turn on `orgstruct++-mode'."
8897 (orgstruct++-mode 1))
8899 (defun orgstruct-error ()
8900 "Error when there is no default binding for a structure key."
8901 (interactive)
8902 (funcall (if (fboundp 'user-error)
8903 'user-error
8904 'error)
8905 "This key has no function outside structure elements"))
8907 (defun orgstruct-setup ()
8908 "Setup orgstruct keymap."
8909 (dolist (cell '((org-demote . t)
8910 (org-metaleft . t)
8911 (org-metaright . t)
8912 (org-promote . t)
8913 (org-shiftmetaleft . t)
8914 (org-shiftmetaright . t)
8915 org-backward-element
8916 org-backward-heading-same-level
8917 org-ctrl-c-ret
8918 org-ctrl-c-minus
8919 org-ctrl-c-star
8920 org-cycle
8921 org-forward-heading-same-level
8922 org-insert-heading
8923 org-insert-heading-respect-content
8924 org-kill-note-or-show-branches
8925 org-mark-subtree
8926 org-meta-return
8927 org-metadown
8928 org-metaup
8929 org-narrow-to-subtree
8930 org-promote-subtree
8931 org-reveal
8932 org-shiftdown
8933 org-shiftleft
8934 org-shiftmetadown
8935 org-shiftmetaup
8936 org-shiftright
8937 org-shifttab
8938 org-shifttab
8939 org-shiftup
8940 org-show-subtree
8941 org-sort
8942 org-up-element
8943 outline-demote
8944 outline-next-visible-heading
8945 outline-previous-visible-heading
8946 outline-promote
8947 outline-up-heading
8948 show-children))
8949 (let ((f (or (car-safe cell) cell))
8950 (disable-when-heading-prefix (cdr-safe cell)))
8951 (when (fboundp f)
8952 (dolist (binding (nconc (where-is-internal f org-mode-map)
8953 (where-is-internal f outline-mode-map)))
8954 ;; TODO use local-function-key-map
8955 (dolist (rep '(("<tab>" . "TAB")
8956 ("<return>" . "RET")
8957 ("<escape>" . "ESC")
8958 ("<delete>" . "DEL")))
8959 (setq binding (read-kbd-macro
8960 (let ((case-fold-search))
8961 (replace-regexp-in-string
8962 (regexp-quote (cdr rep))
8963 (car rep)
8964 (key-description binding))))))
8965 (let ((key (lookup-key orgstruct-mode-map binding)))
8966 (when (or (not key) (numberp key))
8967 (condition-case nil
8968 (org-defkey orgstruct-mode-map
8969 binding
8970 (orgstruct-make-binding f binding disable-when-heading-prefix))
8971 (error nil))))))))
8972 (run-hooks 'orgstruct-setup-hook))
8974 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
8975 "Create a function for binding in the structure minor mode.
8976 FUN is the command to call inside a table. KEY is the key that
8977 should be checked in for a command to execute outside of tables.
8978 Non-nil DISABLE-WHEN-HEADING-PREFIX means to disable the command
8979 if `orgstruct-heading-prefix-regexp' is non-nil."
8980 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
8981 (let ((nname name)
8982 (i 0))
8983 (while (fboundp (intern nname))
8984 (setq nname (format "%s-%d" name (setq i (1+ i)))))
8985 (setq name (intern nname)))
8986 (eval
8987 (let ((bindings '((org-heading-regexp
8988 (concat "^"
8989 orgstruct-heading-prefix-regexp
8990 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
8991 (org-outline-regexp
8992 (concat orgstruct-heading-prefix-regexp "\\*+ "))
8993 (org-outline-regexp-bol
8994 (concat "^" org-outline-regexp))
8995 (outline-regexp org-outline-regexp)
8996 (outline-heading-end-regexp "\n")
8997 (outline-level 'org-outline-level)
8998 (outline-heading-alist))))
8999 `(defun ,name (arg)
9000 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9001 "Outside of structure, run the binding of `"
9002 (key-description key) "'."
9003 (when disable-when-heading-prefix
9004 (concat
9005 "\nIf `orgstruct-heading-prefix-regexp' is non-nil, this command will always fall\n"
9006 "back to the default binding due to limitations of Org's implementation of\n"
9007 "`" (symbol-name fun) "'.")))
9008 (interactive "p")
9009 (let* ((disable
9010 ,(when disable-when-heading-prefix
9011 '(and orgstruct-heading-prefix-regexp
9012 (not (string= orgstruct-heading-prefix-regexp "")))))
9013 (fallback
9014 (or disable
9015 (not
9016 (let* ,bindings
9017 (org-context-p 'headline 'item
9018 ,(when (memq fun '(org-insert-heading))
9019 '(when orgstruct-is-++
9020 'item-body))))))))
9021 (if fallback
9022 (let* ((orgstruct-mode)
9023 (binding
9024 (loop with key = ,key
9025 for rep in
9026 '(nil
9027 ("<\\([^>]*\\)tab>" . "\\1TAB")
9028 ("<\\([^>]*\\)return>" . "\\1RET")
9029 ("<\\([^>]*\\)escape>" . "\\1ESC")
9030 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9032 (when rep
9033 (setq key (read-kbd-macro
9034 (let ((case-fold-search))
9035 (replace-regexp-in-string
9036 (car rep)
9037 (cdr rep)
9038 (key-description key))))))
9039 thereis (key-binding key))))
9040 (if (keymapp binding)
9041 (set-temporary-overlay-map binding)
9042 (let ((func (or binding
9043 (unless disable
9044 'orgstruct-error))))
9045 (when func
9046 (call-interactively func)))))
9047 (org-run-like-in-org-mode
9048 (lambda ()
9049 (interactive)
9050 (let* ,bindings
9051 (call-interactively ',fun)))))))))
9052 name))
9054 (defun org-contextualize-keys (alist contexts)
9055 "Return valid elements in ALIST depending on CONTEXTS.
9057 `org-agenda-custom-commands' or `org-capture-templates' are the
9058 values used for ALIST, and `org-agenda-custom-commands-contexts'
9059 or `org-capture-templates-contexts' are the associated contexts
9060 definitions."
9061 (let ((contexts
9062 ;; normalize contexts
9063 (mapcar
9064 (lambda(c) (cond ((listp (cadr c))
9065 (list (car c) (car c) (cadr c)))
9066 ((string= "" (cadr c))
9067 (list (car c) (car c) (caddr c)))
9068 (t c))) contexts))
9069 (a alist) c r s)
9070 ;; loop over all commands or templates
9071 (while (setq c (pop a))
9072 (let (vrules repl)
9073 (cond
9074 ((not (assoc (car c) contexts))
9075 (push c r))
9076 ((and (assoc (car c) contexts)
9077 (setq vrules (org-contextualize-validate-key
9078 (car c) contexts)))
9079 (mapc (lambda (vr)
9080 (when (not (equal (car vr) (cadr vr)))
9081 (setq repl vr))) vrules)
9082 (if (not repl) (push c r)
9083 (push (cadr repl) s)
9084 (push
9085 (cons (car c)
9086 (cdr (or (assoc (cadr repl) alist)
9087 (error "Undefined key `%s' as contextual replacement for `%s'"
9088 (cadr repl) (car c)))))
9089 r))))))
9090 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9091 (delq
9093 (delete-dups
9094 (mapcar (lambda (x)
9095 (let ((tpl (car x)))
9096 (when (not (delq
9098 (mapcar (lambda(y)
9099 (equal y tpl)) s))) x)))
9100 (reverse r))))))
9102 (defun org-contextualize-validate-key (key contexts)
9103 "Check CONTEXTS for agenda or capture KEY."
9104 (let (r rr res)
9105 (while (setq r (pop contexts))
9106 (mapc
9107 (lambda (rr)
9108 (when
9109 (and (equal key (car r))
9110 (if (functionp rr) (funcall rr)
9111 (or (and (eq (car rr) 'in-file)
9112 (buffer-file-name)
9113 (string-match (cdr rr) (buffer-file-name)))
9114 (and (eq (car rr) 'in-mode)
9115 (string-match (cdr rr) (symbol-name major-mode)))
9116 (and (eq (car rr) 'in-buffer)
9117 (string-match (cdr rr) (buffer-name)))
9118 (when (and (eq (car rr) 'not-in-file)
9119 (buffer-file-name))
9120 (not (string-match (cdr rr) (buffer-file-name))))
9121 (when (eq (car rr) 'not-in-mode)
9122 (not (string-match (cdr rr) (symbol-name major-mode))))
9123 (when (eq (car rr) 'not-in-buffer)
9124 (not (string-match (cdr rr) (buffer-name)))))))
9125 (push r res)))
9126 (car (last r))))
9127 (delete-dups (delq nil res))))
9129 (defun org-context-p (&rest contexts)
9130 "Check if local context is any of CONTEXTS.
9131 Possible values in the list of contexts are `table', `headline', and `item'."
9132 (let ((pos (point)))
9133 (goto-char (point-at-bol))
9134 (prog1 (or (and (memq 'table contexts)
9135 (looking-at "[ \t]*|"))
9136 (and (memq 'headline contexts)
9137 (looking-at org-outline-regexp))
9138 (and (memq 'item contexts)
9139 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9140 (and (memq 'item-body contexts)
9141 (org-in-item-p)))
9142 (goto-char pos))))
9144 (defun org-get-local-variables ()
9145 "Return a list of all local variables in an Org mode buffer."
9146 (let (varlist)
9147 (with-current-buffer (get-buffer-create "*Org tmp*")
9148 (erase-buffer)
9149 (org-mode)
9150 (setq varlist (buffer-local-variables)))
9151 (kill-buffer "*Org tmp*")
9152 (delq nil
9153 (mapcar
9154 (lambda (x)
9155 (setq x
9156 (if (symbolp x)
9157 (list x)
9158 (list (car x) (cdr x))))
9159 (if (and (not (get (car x) 'org-state))
9160 (string-match
9161 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9162 (symbol-name (car x))))
9163 x nil))
9164 varlist))))
9166 (defun org-clone-local-variables (from-buffer &optional regexp)
9167 "Clone local variables from FROM-BUFFER.
9168 Optional argument REGEXP selects variables to clone."
9169 (mapc
9170 (lambda (pair)
9171 (and (symbolp (car pair))
9172 (or (null regexp)
9173 (string-match regexp (symbol-name (car pair))))
9174 (set (make-local-variable (car pair))
9175 (cdr pair))))
9176 (buffer-local-variables from-buffer)))
9178 ;;;###autoload
9179 (defun org-run-like-in-org-mode (cmd)
9180 "Run a command, pretending that the current buffer is in Org-mode.
9181 This will temporarily bind local variables that are typically bound in
9182 Org-mode to the values they have in Org-mode, and then interactively
9183 call CMD."
9184 (org-load-modules-maybe)
9185 (unless org-local-vars
9186 (setq org-local-vars (org-get-local-variables)))
9187 (let (binds)
9188 (dolist (var org-local-vars)
9189 (when (or (not (boundp (car var)))
9190 (eq (symbol-value (car var))
9191 (default-value (car var))))
9192 (push (list (car var) `(quote ,(cadr var))) binds)))
9193 (eval `(let ,binds
9194 (call-interactively (quote ,cmd))))))
9196 ;;;; Archiving
9198 (defun org-get-category (&optional pos force-refresh)
9199 "Get the category applying to position POS."
9200 (save-match-data
9201 (if force-refresh (org-refresh-category-properties))
9202 (let ((pos (or pos (point))))
9203 (or (get-text-property pos 'org-category)
9204 (progn (org-refresh-category-properties)
9205 (get-text-property pos 'org-category))))))
9207 (defun org-refresh-category-properties ()
9208 "Refresh category text properties in the buffer."
9209 (let ((case-fold-search t)
9210 (inhibit-read-only t)
9211 (def-cat (cond
9212 ((null org-category)
9213 (if buffer-file-name
9214 (file-name-sans-extension
9215 (file-name-nondirectory buffer-file-name))
9216 "???"))
9217 ((symbolp org-category) (symbol-name org-category))
9218 (t org-category)))
9219 beg end cat pos optionp)
9220 (org-with-silent-modifications
9221 (save-excursion
9222 (save-restriction
9223 (widen)
9224 (goto-char (point-min))
9225 (put-text-property (point) (point-max) 'org-category def-cat)
9226 (while (re-search-forward
9227 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9228 (setq pos (match-end 0)
9229 optionp (equal (char-after (match-beginning 0)) ?#)
9230 cat (org-trim (match-string 2)))
9231 (if optionp
9232 (setq beg (point-at-bol) end (point-max))
9233 (org-back-to-heading t)
9234 (setq beg (point) end (org-end-of-subtree t t)))
9235 (put-text-property beg end 'org-category cat)
9236 (put-text-property beg end 'org-category-position beg)
9237 (goto-char pos)))))))
9239 (defun org-refresh-properties (dprop tprop)
9240 "Refresh buffer text properties.
9241 DPROP is the drawer property and TPROP is the corresponding text
9242 property to set."
9243 (let ((case-fold-search t)
9244 (inhibit-read-only t) p)
9245 (org-with-silent-modifications
9246 (save-excursion
9247 (save-restriction
9248 (widen)
9249 (goto-char (point-min))
9250 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9251 (setq p (org-match-string-no-properties 1))
9252 (save-excursion
9253 (org-back-to-heading t)
9254 (put-text-property
9255 (point-at-bol) (org-end-of-subtree t t) tprop p))))))))
9258 ;;;; Link Stuff
9260 ;;; Link abbreviations
9262 (defun org-link-expand-abbrev (link)
9263 "Apply replacements as defined in `org-link-abbrev-alist'."
9264 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9265 (let* ((key (match-string 1 link))
9266 (as (or (assoc key org-link-abbrev-alist-local)
9267 (assoc key org-link-abbrev-alist)))
9268 (tag (and (match-end 2) (match-string 3 link)))
9269 rpl)
9270 (if (not as)
9271 link
9272 (setq rpl (cdr as))
9273 (cond
9274 ((symbolp rpl) (funcall rpl tag))
9275 ((string-match "%(\\([^)]+\\))" rpl)
9276 (replace-match
9277 (save-match-data
9278 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9279 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9280 ((string-match "%h" rpl)
9281 (replace-match (url-hexify-string (or tag "")) t t rpl))
9282 (t (concat rpl tag)))))
9283 link))
9285 ;;; Storing and inserting links
9287 (defvar org-insert-link-history nil
9288 "Minibuffer history for links inserted with `org-insert-link'.")
9290 (defvar org-stored-links nil
9291 "Contains the links stored with `org-store-link'.")
9293 (defvar org-store-link-plist nil
9294 "Plist with info about the most recently link created with `org-store-link'.")
9296 (defvar org-link-protocols nil
9297 "Link protocols added to Org-mode using `org-add-link-type'.")
9299 (defvar org-store-link-functions nil
9300 "List of functions that are called to create and store a link.
9301 Each function will be called in turn until one returns a non-nil
9302 value. Each function should check if it is responsible for creating
9303 this link (for example by looking at the major mode).
9304 If not, it must exit and return nil.
9305 If yes, it should return a non-nil value after a calling
9306 `org-store-link-props' with a list of properties and values.
9307 Special properties are:
9309 :type The link prefix, like \"http\". This must be given.
9310 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9311 This is obligatory as well.
9312 :description Optional default description for the second pair
9313 of brackets in an Org-mode link. The user can still change
9314 this when inserting this link into an Org-mode buffer.
9316 In addition to these, any additional properties can be specified
9317 and then used in capture templates.")
9319 (defun org-add-link-type (type &optional follow export)
9320 "Add TYPE to the list of `org-link-types'.
9321 Re-compute all regular expressions depending on `org-link-types'
9323 FOLLOW and EXPORT are two functions.
9325 FOLLOW should take the link path as the single argument and do whatever
9326 is necessary to follow the link, for example find a file or display
9327 a mail message.
9329 EXPORT should format the link path for export to one of the export formats.
9330 It should be a function accepting three arguments:
9332 path the path of the link, the text after the prefix (like \"http:\")
9333 desc the description of the link, if any, or a description added by
9334 org-export-normalize-links if there is none
9335 format the export format, a symbol like `html' or `latex' or `ascii'..
9337 The function may use the FORMAT information to return different values
9338 depending on the format. The return value will be put literally into
9339 the exported file. If the return value is nil, this means Org should
9340 do what it normally does with links which do not have EXPORT defined.
9342 Org-mode has a built-in default for exporting links. If you are happy with
9343 this default, there is no need to define an export function for the link
9344 type. For a simple example of an export function, see `org-bbdb.el'."
9345 (add-to-list 'org-link-types type t)
9346 (org-make-link-regexps)
9347 (if (assoc type org-link-protocols)
9348 (setcdr (assoc type org-link-protocols) (list follow export))
9349 (push (list type follow export) org-link-protocols)))
9351 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9352 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9354 ;;;###autoload
9355 (defun org-store-link (arg)
9356 "\\<org-mode-map>Store an org-link to the current location.
9357 This link is added to `org-stored-links' and can later be inserted
9358 into an org-buffer with \\[org-insert-link].
9360 For some link types, a prefix arg is interpreted.
9361 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9362 For file links, arg negates `org-context-in-file-links'.
9364 A double prefix arg force skipping storing functions that are not
9365 part of Org's core.
9367 A triple prefix arg force storing a link for each line in the
9368 active region."
9369 (interactive "P")
9370 (org-load-modules-maybe)
9371 (if (and (equal arg '(64)) (org-region-active-p))
9372 (save-excursion
9373 (let ((end (region-end)))
9374 (goto-char (region-beginning))
9375 (set-mark (point))
9376 (while (< (point-at-eol) end)
9377 (move-end-of-line 1) (activate-mark)
9378 (let (current-prefix-arg)
9379 (call-interactively 'org-store-link))
9380 (move-beginning-of-line 2)
9381 (set-mark (point)))))
9382 (org-with-limited-levels
9383 (setq org-store-link-plist nil)
9384 (let (link cpltxt desc description search
9385 txt custom-id agenda-link sfuns sfunsn)
9386 (cond
9388 ;; Store a link using an external link type
9389 ((and (not (equal arg '(16)))
9390 (setq sfuns
9391 (delq
9392 nil (mapcar (lambda (f)
9393 (let (fs) (if (funcall f) (push f fs))))
9394 org-store-link-functions))
9395 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9396 (or (and (cdr sfuns)
9397 (funcall (intern
9398 (completing-read
9399 "Which function for creating the link? "
9400 sfunsn t (car sfunsn)))))
9401 (funcall (caar sfuns)))
9402 (setq link (plist-get org-store-link-plist :link)
9403 desc (or (plist-get org-store-link-plist
9404 :description) link))))
9406 ;; Store a link from a source code buffer
9407 ((org-src-edit-buffer-p)
9408 (let (label gc)
9409 (while (or (not label)
9410 (save-excursion
9411 (save-restriction
9412 (widen)
9413 (goto-char (point-min))
9414 (re-search-forward
9415 (regexp-quote (format org-coderef-label-format label))
9416 nil t))))
9417 (when label (message "Label exists already") (sit-for 2))
9418 (setq label (read-string "Code line label: " label)))
9419 (end-of-line 1)
9420 (setq link (format org-coderef-label-format label))
9421 (setq gc (- 79 (length link)))
9422 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9423 (insert link)
9424 (setq link (concat "(" label ")") desc nil)))
9426 ;; We are in the agenda, link to referenced location
9427 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9428 (let ((m (or (get-text-property (point) 'org-hd-marker)
9429 (get-text-property (point) 'org-marker))))
9430 (when m
9431 (org-with-point-at m
9432 (setq agenda-link
9433 (if (org-called-interactively-p 'any)
9434 (call-interactively 'org-store-link)
9435 (org-store-link nil)))))))
9437 ((eq major-mode 'calendar-mode)
9438 (let ((cd (calendar-cursor-to-date)))
9439 (setq link
9440 (format-time-string
9441 (car org-time-stamp-formats)
9442 (apply 'encode-time
9443 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9444 nil nil nil))))
9445 (org-store-link-props :type "calendar" :date cd)))
9447 ((eq major-mode 'help-mode)
9448 (setq link (concat "help:" (save-excursion
9449 (goto-char (point-min))
9450 (looking-at "^[^ ]+")
9451 (match-string 0))))
9452 (org-store-link-props :type "help"))
9454 ((eq major-mode 'w3-mode)
9455 (setq cpltxt (if (and (buffer-name)
9456 (not (string-match "Untitled" (buffer-name))))
9457 (buffer-name)
9458 (url-view-url t))
9459 link (url-view-url t))
9460 (org-store-link-props :type "w3" :url (url-view-url t)))
9462 ((eq major-mode 'image-mode)
9463 (setq cpltxt (concat "file:"
9464 (abbreviate-file-name buffer-file-name))
9465 link cpltxt)
9466 (org-store-link-props :type "image" :file buffer-file-name))
9468 ;; In dired, store a link to the file of the current line
9469 ((eq major-mode 'dired-mode)
9470 (let ((file (dired-get-filename nil t)))
9471 (setq file (if file
9472 (abbreviate-file-name
9473 (expand-file-name (dired-get-filename nil t)))
9474 ;; otherwise, no file so use current directory.
9475 default-directory))
9476 (setq cpltxt (concat "file:" file)
9477 link cpltxt)))
9479 ((setq search (run-hook-with-args-until-success
9480 'org-create-file-search-functions))
9481 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9482 "::" search))
9483 (setq cpltxt (or description link)))
9485 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9486 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9487 (cond
9488 ;; Store a link using the target at point
9489 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9490 (setq cpltxt
9491 (concat "file:"
9492 (abbreviate-file-name
9493 (buffer-file-name (buffer-base-buffer)))
9494 "::" (match-string 1))
9495 link cpltxt))
9496 ((and (featurep 'org-id)
9497 (or (eq org-id-link-to-org-use-id t)
9498 (and (org-called-interactively-p 'any)
9499 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9500 (and (eq org-id-link-to-org-use-id
9501 'create-if-interactive-and-no-custom-id)
9502 (not custom-id))))
9503 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9504 ;; Store a link using the ID at point
9505 (setq link (condition-case nil
9506 (prog1 (org-id-store-link)
9507 (setq desc (plist-get org-store-link-plist
9508 :description)))
9509 (error
9510 ;; Probably before first headline, link only to file
9511 (concat "file:"
9512 (abbreviate-file-name
9513 (buffer-file-name (buffer-base-buffer))))))))
9515 ;; Just link to current headline
9516 (setq cpltxt (concat "file:"
9517 (abbreviate-file-name
9518 (buffer-file-name (buffer-base-buffer)))))
9519 ;; Add a context search string
9520 (when (org-xor org-context-in-file-links arg)
9521 (let* ((ee (org-element-at-point))
9522 (et (org-element-type ee))
9523 (ev (plist-get (cadr ee) :value))
9524 (ek (plist-get (cadr ee) :key))
9525 (eok (and (stringp ek) (string-match "name" ek))))
9526 (setq txt (cond
9527 ((org-at-heading-p) nil)
9528 ((and (eq et 'keyword) eok) ev)
9529 ((org-region-active-p)
9530 (buffer-substring (region-beginning) (region-end)))))
9531 (when (or (null txt) (string-match "\\S-" txt))
9532 (setq cpltxt
9533 (concat cpltxt "::"
9534 (condition-case nil
9535 (org-make-org-heading-search-string txt)
9536 (error "")))
9537 desc (or (and (eq et 'keyword) eok ev)
9538 (nth 4 (ignore-errors (org-heading-components)))
9539 "NONE")))))
9540 (if (string-match "::\\'" cpltxt)
9541 (setq cpltxt (substring cpltxt 0 -2)))
9542 (setq link cpltxt))))
9544 ((buffer-file-name (buffer-base-buffer))
9545 ;; Just link to this file here.
9546 (setq cpltxt (concat "file:"
9547 (abbreviate-file-name
9548 (buffer-file-name (buffer-base-buffer)))))
9549 ;; Add a context string.
9550 (when (org-xor org-context-in-file-links arg)
9551 (setq txt (if (org-region-active-p)
9552 (buffer-substring (region-beginning) (region-end))
9553 (buffer-substring (point-at-bol) (point-at-eol))))
9554 ;; Only use search option if there is some text.
9555 (when (string-match "\\S-" txt)
9556 (setq cpltxt
9557 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9558 desc "NONE")))
9559 (setq link cpltxt))
9561 ((org-called-interactively-p 'interactive)
9562 (user-error "No method for storing a link from this buffer"))
9564 (t (setq link nil)))
9566 ;; We're done setting link and desc, clean up
9567 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9568 (setq link (or link cpltxt)
9569 desc (or desc cpltxt))
9570 (cond ((equal desc "NONE") (setq desc nil))
9571 ((string-match org-bracket-link-analytic-regexp desc)
9572 (let ((d0 (match-string 3 desc))
9573 (p0 (match-string 5 desc)))
9574 (setq desc
9575 (replace-regexp-in-string
9576 org-bracket-link-regexp
9577 (concat (or p0 d0)
9578 (if (equal (length (match-string 0 desc))
9579 (length desc)) "*" "")) desc)))))
9581 ;; Return the link
9582 (if (not (and (or (org-called-interactively-p 'any)
9583 executing-kbd-macro) link))
9584 (or agenda-link (and link (org-make-link-string link desc)))
9585 (push (list link desc) org-stored-links)
9586 (message "Stored: %s" (or desc link))
9587 (when custom-id
9588 (setq link (concat "file:" (abbreviate-file-name
9589 (buffer-file-name)) "::#" custom-id))
9590 (push (list link desc) org-stored-links)))))))
9592 (defun org-store-link-props (&rest plist)
9593 "Store link properties, extract names and addresses."
9594 (let (x adr)
9595 (when (setq x (plist-get plist :from))
9596 (setq adr (mail-extract-address-components x))
9597 (setq plist (plist-put plist :fromname (car adr)))
9598 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9599 (when (setq x (plist-get plist :to))
9600 (setq adr (mail-extract-address-components x))
9601 (setq plist (plist-put plist :toname (car adr)))
9602 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9603 (let ((from (plist-get plist :from))
9604 (to (plist-get plist :to)))
9605 (when (and from to org-from-is-user-regexp)
9606 (setq plist
9607 (plist-put plist :fromto
9608 (if (string-match org-from-is-user-regexp from)
9609 (concat "to %t")
9610 (concat "from %f"))))))
9611 (setq org-store-link-plist plist))
9613 (defun org-add-link-props (&rest plist)
9614 "Add these properties to the link property list."
9615 (let (key value)
9616 (while plist
9617 (setq key (pop plist) value (pop plist))
9618 (setq org-store-link-plist
9619 (plist-put org-store-link-plist key value)))))
9621 (defun org-email-link-description (&optional fmt)
9622 "Return the description part of an email link.
9623 This takes information from `org-store-link-plist' and formats it
9624 according to FMT (default from `org-email-link-description-format')."
9625 (setq fmt (or fmt org-email-link-description-format))
9626 (let* ((p org-store-link-plist)
9627 (to (plist-get p :toaddress))
9628 (from (plist-get p :fromaddress))
9629 (table
9630 (list
9631 (cons "%c" (plist-get p :fromto))
9632 (cons "%F" (plist-get p :from))
9633 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9634 (cons "%T" (plist-get p :to))
9635 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9636 (cons "%s" (plist-get p :subject))
9637 (cons "%d" (plist-get p :date))
9638 (cons "%m" (plist-get p :message-id)))))
9639 (when (string-match "%c" fmt)
9640 ;; Check if the user wrote this message
9641 (if (and org-from-is-user-regexp from to
9642 (save-match-data (string-match org-from-is-user-regexp from)))
9643 (setq fmt (replace-match "to %t" t t fmt))
9644 (setq fmt (replace-match "from %f" t t fmt))))
9645 (org-replace-escapes fmt table)))
9647 (defun org-make-org-heading-search-string (&optional string)
9648 "Make search string for the current headline or STRING."
9649 (let ((s (or string
9650 (and (derived-mode-p 'org-mode)
9651 (save-excursion
9652 (org-back-to-heading t)
9653 (org-element-property :raw-value (org-element-at-point))))))
9654 (lines org-context-in-file-links))
9655 (or string (setq s (concat "*" s))) ; Add * for headlines
9656 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9657 (when (and string (integerp lines) (> lines 0))
9658 (let ((slines (org-split-string s "\n")))
9659 (when (< lines (length slines))
9660 (setq s (mapconcat
9661 'identity
9662 (reverse (nthcdr (- (length slines) lines)
9663 (reverse slines))) "\n")))))
9664 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9666 (defun org-make-link-string (link &optional description)
9667 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9668 (unless (string-match "\\S-" link)
9669 (error "Empty link"))
9670 (when (and description
9671 (stringp description)
9672 (not (string-match "\\S-" description)))
9673 (setq description nil))
9674 (when (stringp description)
9675 ;; Remove brackets from the description, they are fatal.
9676 (while (string-match "\\[" description)
9677 (setq description (replace-match "{" t t description)))
9678 (while (string-match "\\]" description)
9679 (setq description (replace-match "}" t t description))))
9680 (when (equal link description)
9681 ;; No description needed, it is identical
9682 (setq description nil))
9683 (when (and (not description)
9684 (not (string-match (org-image-file-name-regexp) link))
9685 (not (equal link (org-link-escape link))))
9686 (setq description (org-extract-attributes link)))
9687 (setq link
9688 (cond ((string-match (org-image-file-name-regexp) link) link)
9689 ((string-match org-link-types-re link)
9690 (concat (match-string 1 link)
9691 (org-link-escape (substring link (match-end 1)))))
9692 (t (org-link-escape link))))
9693 (concat "[[" link "]"
9694 (if description (concat "[" description "]") "")
9695 "]"))
9697 (defconst org-link-escape-chars
9698 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9699 "List of characters that should be escaped in link.
9700 This is the list that is used for internal purposes.")
9702 (defconst org-link-escape-chars-browser
9703 '(?\ )
9704 "List of escapes for characters that are problematic in links.
9705 This is the list that is used before handing over to the browser.")
9707 (defun org-link-escape (text &optional table merge)
9708 "Return percent escaped representation of TEXT.
9709 TEXT is a string with the text to escape.
9710 Optional argument TABLE is a list with characters that should be
9711 escaped. When nil, `org-link-escape-chars' is used.
9712 If optional argument MERGE is set, merge TABLE into
9713 `org-link-escape-chars'."
9714 (cond
9715 ((and table merge)
9716 (mapc (lambda (defchr)
9717 (unless (member defchr table)
9718 (setq table (cons defchr table)))) org-link-escape-chars))
9719 ((null table)
9720 (setq table org-link-escape-chars)))
9721 (mapconcat
9722 (lambda (char)
9723 (if (or (member char table)
9724 (and (or (< char 32) (= char 37) (> char 126))
9725 org-url-hexify-p))
9726 (mapconcat (lambda (sequence-element)
9727 (format "%%%.2X" sequence-element))
9728 (or (encode-coding-char char 'utf-8)
9729 (error "Unable to percent escape character: %s"
9730 (char-to-string char))) "")
9731 (char-to-string char))) text ""))
9733 (defun org-link-unescape (str)
9734 "Unhex hexified Unicode strings as returned from the JavaScript function
9735 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9736 (unless (and (null str) (string= "" str))
9737 (let ((pos 0) (case-fold-search t) unhexed)
9738 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9739 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9740 (setq str (replace-match unhexed t t str))
9741 (setq pos (+ pos (length unhexed))))))
9742 str)
9744 (defun org-link-unescape-compound (hex)
9745 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9746 Note: this function also decodes single byte encodings like
9747 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9748 (save-match-data
9749 (let* ((bytes (cdr (split-string hex "%")))
9750 (ret "")
9751 (eat 0)
9752 (sum 0))
9753 (while bytes
9754 (let* ((val (string-to-number (pop bytes) 16))
9755 (shift-xor
9756 (if (= 0 eat)
9757 (cond
9758 ((>= val 252) (cons 6 252))
9759 ((>= val 248) (cons 5 248))
9760 ((>= val 240) (cons 4 240))
9761 ((>= val 224) (cons 3 224))
9762 ((>= val 192) (cons 2 192))
9763 (t (cons 0 0)))
9764 (cons 6 128))))
9765 (if (>= val 192) (setq eat (car shift-xor)))
9766 (setq val (logxor val (cdr shift-xor)))
9767 (setq sum (+ (lsh sum (car shift-xor)) val))
9768 (if (> eat 0) (setq eat (- eat 1)))
9769 (cond
9770 ((= 0 eat) ;multi byte
9771 (setq ret (concat ret (org-char-to-string sum)))
9772 (setq sum 0))
9773 ((not bytes) ; single byte(s)
9774 (setq ret (org-link-unescape-single-byte-sequence hex))))
9775 )) ;; end (while bytes
9776 ret )))
9778 (defun org-link-unescape-single-byte-sequence (hex)
9779 "Unhexify hex-encoded single byte character sequences."
9780 (mapconcat (lambda (byte)
9781 (char-to-string (string-to-number byte 16)))
9782 (cdr (split-string hex "%")) ""))
9784 (defun org-xor (a b)
9785 "Exclusive or."
9786 (if a (not b) b))
9788 (defun org-fixup-message-id-for-http (s)
9789 "Replace special characters in a message id, so it can be used in an http query."
9790 (when (string-match "%" s)
9791 (setq s (mapconcat (lambda (c)
9792 (if (eq c ?%)
9793 "%25"
9794 (char-to-string c)))
9795 s "")))
9796 (while (string-match "<" s)
9797 (setq s (replace-match "%3C" t t s)))
9798 (while (string-match ">" s)
9799 (setq s (replace-match "%3E" t t s)))
9800 (while (string-match "@" s)
9801 (setq s (replace-match "%40" t t s)))
9804 (defun org-link-prettify (link)
9805 "Return a human-readable representation of LINK.
9806 The car of LINK must be a raw link the cdr of LINK must be either
9807 a link description or nil."
9808 (let ((desc (or (cadr link) "<no description>")))
9809 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9810 "<" (car link) ">")))
9812 ;;;###autoload
9813 (defun org-insert-link-global ()
9814 "Insert a link like Org-mode does.
9815 This command can be called in any mode to insert a link in Org-mode syntax."
9816 (interactive)
9817 (org-load-modules-maybe)
9818 (org-run-like-in-org-mode 'org-insert-link))
9820 (defun org-insert-all-links (&optional keep)
9821 "Insert all links in `org-stored-links'."
9822 (interactive "P")
9823 (let ((links (copy-sequence org-stored-links)) l)
9824 (while (setq l (if keep (pop links) (pop org-stored-links)))
9825 (insert "- ")
9826 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9827 (insert "\n"))))
9829 (defun org-link-fontify-links-to-this-file ()
9830 "Fontify links to the current file in `org-stored-links'."
9831 (let ((f (buffer-file-name)) a b)
9832 (setq a (mapcar (lambda(l)
9833 (let ((ll (car l)))
9834 (when (and (string-match "^file:\\(.+\\)::" ll)
9835 (equal f (expand-file-name (match-string 1 ll))))
9836 ll)))
9837 org-stored-links))
9838 (when (featurep 'org-id)
9839 (setq b (mapcar (lambda(l)
9840 (let ((ll (car l)))
9841 (when (and (string-match "^id:\\(.+\\)$" ll)
9842 (equal f (expand-file-name
9843 (or (org-id-find-id-file
9844 (match-string 1 ll)) ""))))
9845 ll)))
9846 org-stored-links)))
9847 (mapcar (lambda(l)
9848 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9849 (delq nil (append a b)))))
9851 (defvar org-link-links-in-this-file nil)
9852 (defun org-insert-link (&optional complete-file link-location default-description)
9853 "Insert a link. At the prompt, enter the link.
9855 Completion can be used to insert any of the link protocol prefixes like
9856 http or ftp in use.
9858 The history can be used to select a link previously stored with
9859 `org-store-link'. When the empty string is entered (i.e. if you just
9860 press RET at the prompt), the link defaults to the most recently
9861 stored link. As SPC triggers completion in the minibuffer, you need to
9862 use M-SPC or C-q SPC to force the insertion of a space character.
9864 You will also be prompted for a description, and if one is given, it will
9865 be displayed in the buffer instead of the link.
9867 If there is already a link at point, this command will allow you to edit link
9868 and description parts.
9870 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9871 be selected using completion. The path to the file will be relative to the
9872 current directory if the file is in the current directory or a subdirectory.
9873 Otherwise, the link will be the absolute path as completed in the minibuffer
9874 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9875 option `org-link-file-path-type'.
9877 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9878 the current directory or below.
9880 With three \\[universal-argument] prefixes, negate the meaning of
9881 `org-keep-stored-link-after-insertion'.
9883 If `org-make-link-description-function' is non-nil, this function will be
9884 called with the link target, and the result will be the default
9885 link description.
9887 If the LINK-LOCATION parameter is non-nil, this value will be
9888 used as the link location instead of reading one interactively.
9890 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9891 be used as the default description."
9892 (interactive "P")
9893 (let* ((wcf (current-window-configuration))
9894 (origbuf (current-buffer))
9895 (region (if (org-region-active-p)
9896 (buffer-substring (region-beginning) (region-end))))
9897 (remove (and region (list (region-beginning) (region-end))))
9898 (desc region)
9899 tmphist ; byte-compile incorrectly complains about this
9900 (link link-location)
9901 (abbrevs org-link-abbrev-alist-local)
9902 entry file all-prefixes auto-desc)
9903 (cond
9904 (link-location) ; specified by arg, just use it.
9905 ((org-in-regexp org-bracket-link-regexp 1)
9906 ;; We do have a link at point, and we are going to edit it.
9907 (setq remove (list (match-beginning 0) (match-end 0)))
9908 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9909 (setq link (read-string "Link: "
9910 (org-link-unescape
9911 (org-match-string-no-properties 1)))))
9912 ((or (org-in-regexp org-angle-link-re)
9913 (org-in-regexp org-plain-link-re))
9914 ;; Convert to bracket link
9915 (setq remove (list (match-beginning 0) (match-end 0))
9916 link (read-string "Link: "
9917 (org-remove-angle-brackets (match-string 0)))))
9918 ((member complete-file '((4) (16)))
9919 ;; Completing read for file names.
9920 (setq link (org-file-complete-link complete-file)))
9922 ;; Read link, with completion for stored links.
9923 (org-link-fontify-links-to-this-file)
9924 (org-switch-to-buffer-other-window "*Org Links*")
9925 (with-current-buffer "*Org Links*"
9926 (erase-buffer)
9927 (insert "Insert a link.
9928 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9929 (when org-stored-links
9930 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9931 (insert (mapconcat 'org-link-prettify
9932 (reverse org-stored-links) "\n")))
9933 (goto-char (point-min)))
9934 (let ((cw (selected-window)))
9935 (select-window (get-buffer-window "*Org Links*" 'visible))
9936 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9937 (unless (pos-visible-in-window-p (point-max))
9938 (org-fit-window-to-buffer))
9939 (and (window-live-p cw) (select-window cw)))
9940 ;; Fake a link history, containing the stored links.
9941 (setq tmphist (append (mapcar 'car org-stored-links)
9942 org-insert-link-history))
9943 (setq all-prefixes (append (mapcar 'car abbrevs)
9944 (mapcar 'car org-link-abbrev-alist)
9945 org-link-types))
9946 (unwind-protect
9947 (progn
9948 (setq link
9949 (org-completing-read
9950 "Link: "
9951 (append
9952 (mapcar (lambda (x) (concat x ":"))
9953 all-prefixes)
9954 (mapcar 'car org-stored-links))
9955 nil nil nil
9956 'tmphist
9957 (caar org-stored-links)))
9958 (if (not (string-match "\\S-" link))
9959 (user-error "No link selected"))
9960 (mapc (lambda(l)
9961 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9962 org-stored-links)
9963 (if (or (member link all-prefixes)
9964 (and (equal ":" (substring link -1))
9965 (member (substring link 0 -1) all-prefixes)
9966 (setq link (substring link 0 -1))))
9967 (setq link (with-current-buffer origbuf
9968 (org-link-try-special-completion link)))))
9969 (set-window-configuration wcf)
9970 (kill-buffer "*Org Links*"))
9971 (setq entry (assoc link org-stored-links))
9972 (or entry (push link org-insert-link-history))
9973 (setq desc (or desc (nth 1 entry)))))
9975 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9976 (not org-keep-stored-link-after-insertion))
9977 (setq org-stored-links (delq (assoc link org-stored-links)
9978 org-stored-links)))
9980 (if (string-match org-plain-link-re link)
9981 ;; URL-like link, normalize the use of angular brackets.
9982 (setq link (org-remove-angle-brackets link)))
9984 ;; Check if we are linking to the current file with a search
9985 ;; option If yes, simplify the link by using only the search
9986 ;; option.
9987 (when (and buffer-file-name
9988 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
9989 (let* ((path (match-string 1 link))
9990 (case-fold-search nil)
9991 (search (match-string 2 link)))
9992 (save-match-data
9993 (if (equal (file-truename buffer-file-name) (file-truename path))
9994 ;; We are linking to this same file, with a search option
9995 (setq link search)))))
9997 ;; Check if we can/should use a relative path. If yes, simplify the link
9998 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9999 (let* ((type (match-string 1 link))
10000 (path (match-string 2 link))
10001 (origpath path)
10002 (case-fold-search nil))
10003 (cond
10004 ((or (eq org-link-file-path-type 'absolute)
10005 (equal complete-file '(16)))
10006 (setq path (abbreviate-file-name (expand-file-name path))))
10007 ((eq org-link-file-path-type 'noabbrev)
10008 (setq path (expand-file-name path)))
10009 ((eq org-link-file-path-type 'relative)
10010 (setq path (file-relative-name path)))
10012 (save-match-data
10013 (if (string-match (concat "^" (regexp-quote
10014 (expand-file-name
10015 (file-name-as-directory
10016 default-directory))))
10017 (expand-file-name path))
10018 ;; We are linking a file with relative path name.
10019 (setq path (substring (expand-file-name path)
10020 (match-end 0)))
10021 (setq path (abbreviate-file-name (expand-file-name path)))))))
10022 (setq link (concat type path))
10023 (if (equal desc origpath)
10024 (setq desc path))))
10026 (if org-make-link-description-function
10027 (setq desc
10028 (or (condition-case nil
10029 (funcall org-make-link-description-function link desc)
10030 (error (progn (message "Can't get link description from `%s'"
10031 (symbol-name org-make-link-description-function))
10032 (sit-for 2) nil)))
10033 (read-string "Description: " default-description)))
10034 (if default-description (setq desc default-description)
10035 (setq desc (or (and auto-desc desc)
10036 (read-string "Description: " desc)))))
10038 (unless (string-match "\\S-" desc) (setq desc nil))
10039 (if remove (apply 'delete-region remove))
10040 (insert (org-make-link-string link desc))))
10042 (defun org-link-try-special-completion (type)
10043 "If there is completion support for link type TYPE, offer it."
10044 (let ((fun (intern (concat "org-" type "-complete-link"))))
10045 (if (functionp fun)
10046 (funcall fun)
10047 (read-string "Link (no completion support): " (concat type ":")))))
10049 (defun org-file-complete-link (&optional arg)
10050 "Create a file link using completion."
10051 (let (file link)
10052 (setq file (org-iread-file-name "File: "))
10053 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10054 (pwd1 (file-name-as-directory (abbreviate-file-name
10055 (expand-file-name ".")))))
10056 (cond
10057 ((equal arg '(16))
10058 (setq link (concat
10059 "file:"
10060 (abbreviate-file-name (expand-file-name file)))))
10061 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10062 (setq link (concat "file:" (match-string 1 file))))
10063 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10064 (expand-file-name file))
10065 (setq link (concat
10066 "file:" (match-string 1 (expand-file-name file)))))
10067 (t (setq link (concat "file:" file)))))
10068 link))
10070 (defun org-iread-file-name (&rest args)
10071 "Read-file-name using `ido-mode' speedup if available.
10072 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10073 See `read-file-name' for a description of parameters."
10074 (org-without-partial-completion
10075 (if (and org-completion-use-ido
10076 (fboundp 'ido-read-file-name)
10077 (boundp 'ido-mode) ido-mode
10078 (listp (second args)))
10079 (let ((ido-enter-matching-directory nil))
10080 (apply 'ido-read-file-name args))
10081 (apply 'read-file-name args))))
10083 (defun org-completing-read (&rest args)
10084 "Completing-read with SPACE being a normal character."
10085 (let ((enable-recursive-minibuffers t)
10086 (minibuffer-local-completion-map
10087 (copy-keymap minibuffer-local-completion-map)))
10088 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10089 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10090 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10091 (apply 'org-icompleting-read args)))
10093 (defun org-completing-read-no-i (&rest args)
10094 (let (org-completion-use-ido org-completion-use-iswitchb)
10095 (apply 'org-completing-read args)))
10097 (defun org-iswitchb-completing-read (prompt choices &rest args)
10098 "Use iswitch as a completing-read replacement to choose from choices.
10099 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10100 from."
10101 (let* ((iswitchb-use-virtual-buffers nil)
10102 (iswitchb-make-buflist-hook
10103 (lambda ()
10104 (setq iswitchb-temp-buflist choices))))
10105 (iswitchb-read-buffer prompt)))
10107 (defun org-icompleting-read (&rest args)
10108 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10109 (org-without-partial-completion
10110 (if (and org-completion-use-ido
10111 (fboundp 'ido-completing-read)
10112 (boundp 'ido-mode) ido-mode
10113 (listp (second args)))
10114 (let ((ido-enter-matching-directory nil))
10115 (apply 'ido-completing-read (concat (car args))
10116 (if (consp (car (nth 1 args)))
10117 (mapcar 'car (nth 1 args))
10118 (nth 1 args))
10119 (cddr args)))
10120 (if (and org-completion-use-iswitchb
10121 (boundp 'iswitchb-mode) iswitchb-mode
10122 (listp (second args)))
10123 (apply 'org-iswitchb-completing-read (concat (car args))
10124 (if (consp (car (nth 1 args)))
10125 (mapcar 'car (nth 1 args))
10126 (nth 1 args))
10127 (cddr args))
10128 (apply 'completing-read args)))))
10130 (defun org-extract-attributes (s)
10131 "Extract the attributes cookie from a string and set as text property."
10132 (let (a attr (start 0) key value)
10133 (save-match-data
10134 (when (string-match "{{\\([^}]+\\)}}$" s)
10135 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10136 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10137 (setq key (match-string 1 a) value (match-string 2 a)
10138 start (match-end 0)
10139 attr (plist-put attr (intern key) value))))
10140 (org-add-props s nil 'org-attr attr))
10143 ;;; Opening/following a link
10145 (defvar org-link-search-failed nil)
10147 (defvar org-open-link-functions nil
10148 "Hook for functions finding a plain text link.
10149 These functions must take a single argument, the link content.
10150 They will be called for links that look like [[link text][description]]
10151 when LINK TEXT does not have a protocol like \"http:\" and does not look
10152 like a filename (e.g. \"./blue.png\").
10154 These functions will be called *before* Org attempts to resolve the
10155 link by doing text searches in the current buffer - so if you want a
10156 link \"[[target]]\" to still find \"<<target>>\", your function should
10157 handle this as a special case.
10159 When the function does handle the link, it must return a non-nil value.
10160 If it decides that it is not responsible for this link, it must return
10161 nil to indicate that that Org-mode can continue with other options
10162 like exact and fuzzy text search.")
10164 (defun org-next-link (&optional search-backward)
10165 "Move forward to the next link.
10166 If the link is in hidden text, expose it."
10167 (interactive "P")
10168 (when (and org-link-search-failed (eq this-command last-command))
10169 (goto-char (point-min))
10170 (message "Link search wrapped back to beginning of buffer"))
10171 (setq org-link-search-failed nil)
10172 (let* ((pos (point))
10173 (ct (org-context))
10174 (a (assoc :link ct))
10175 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10176 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10177 ((looking-at org-any-link-re)
10178 ;; Don't stay stuck at link without an org-link face
10179 (forward-char (if search-backward -1 1))))
10180 (if (funcall srch-fun org-any-link-re nil t)
10181 (progn
10182 (goto-char (match-beginning 0))
10183 (if (outline-invisible-p) (org-show-context)))
10184 (goto-char pos)
10185 (setq org-link-search-failed t)
10186 (message "No further link found"))))
10188 (defun org-previous-link ()
10189 "Move backward to the previous link.
10190 If the link is in hidden text, expose it."
10191 (interactive)
10192 (funcall 'org-next-link t))
10194 (defun org-translate-link (s)
10195 "Translate a link string if a translation function has been defined."
10196 (if (and org-link-translation-function
10197 (fboundp org-link-translation-function)
10198 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10199 (progn
10200 (setq s (funcall org-link-translation-function
10201 (match-string 1 s) (match-string 2 s)))
10202 (concat (car s) ":" (cdr s)))
10205 (defun org-translate-link-from-planner (type path)
10206 "Translate a link from Emacs Planner syntax so that Org can follow it.
10207 This is still an experimental function, your mileage may vary."
10208 (cond
10209 ((member type '("http" "https" "news" "ftp"))
10210 ;; standard Internet links are the same.
10211 nil)
10212 ((and (equal type "irc") (string-match "^//" path))
10213 ;; Planner has two / at the beginning of an irc link, we have 1.
10214 ;; We should have zero, actually....
10215 (setq path (substring path 1)))
10216 ((and (equal type "lisp") (string-match "^/" path))
10217 ;; Planner has a slash, we do not.
10218 (setq type "elisp" path (substring path 1)))
10219 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10220 ;; A typical message link. Planner has the id after the final slash,
10221 ;; we separate it with a hash mark
10222 (setq path (concat (match-string 1 path) "#"
10223 (org-remove-angle-brackets (match-string 2 path))))))
10224 (cons type path))
10226 (defun org-find-file-at-mouse (ev)
10227 "Open file link or URL at mouse."
10228 (interactive "e")
10229 (mouse-set-point ev)
10230 (org-open-at-point 'in-emacs))
10232 (defun org-open-at-mouse (ev)
10233 "Open file link or URL at mouse.
10234 See the docstring of `org-open-file' for details."
10235 (interactive "e")
10236 (mouse-set-point ev)
10237 (if (eq major-mode 'org-agenda-mode)
10238 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10239 (org-open-at-point))
10241 (defvar org-window-config-before-follow-link nil
10242 "The window configuration before following a link.
10243 This is saved in case the need arises to restore it.")
10245 (defvar org-open-link-marker (make-marker)
10246 "Marker pointing to the location where `org-open-at-point; was called.")
10248 ;;;###autoload
10249 (defun org-open-at-point-global ()
10250 "Follow a link like Org-mode does.
10251 This command can be called in any mode to follow a link that has
10252 Org-mode syntax."
10253 (interactive)
10254 (org-run-like-in-org-mode 'org-open-at-point))
10256 ;;;###autoload
10257 (defun org-open-link-from-string (s &optional arg reference-buffer)
10258 "Open a link in the string S, as if it was in Org-mode."
10259 (interactive "sLink: \nP")
10260 (let ((reference-buffer (or reference-buffer (current-buffer))))
10261 (with-temp-buffer
10262 (let ((org-inhibit-startup (not reference-buffer)))
10263 (org-mode)
10264 (insert s)
10265 (goto-char (point-min))
10266 (when reference-buffer
10267 (setq org-link-abbrev-alist-local
10268 (with-current-buffer reference-buffer
10269 org-link-abbrev-alist-local)))
10270 (org-open-at-point arg reference-buffer)))))
10272 (defvar org-open-at-point-functions nil
10273 "Hook that is run when following a link at point.
10275 Functions in this hook must return t if they identify and follow
10276 a link at point. If they don't find anything interesting at point,
10277 they must return nil.")
10279 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10280 (defun org-open-at-point (&optional arg reference-buffer)
10281 "Open link at or after point.
10282 If there is no link at point, this function will search forward up to
10283 the end of the current line.
10284 Normally, files will be opened by an appropriate application. If the
10285 optional prefix argument ARG is non-nil, Emacs will visit the file.
10286 With a double prefix argument, try to open outside of Emacs, in the
10287 application the system uses for this file type."
10288 (interactive "P")
10289 ;; if in a code block, then open the block's results
10290 (unless (call-interactively #'org-babel-open-src-block-result)
10291 (org-load-modules-maybe)
10292 (move-marker org-open-link-marker (point))
10293 (setq org-window-config-before-follow-link (current-window-configuration))
10294 (org-remove-occur-highlights nil nil t)
10295 (cond
10296 ((and (org-at-heading-p)
10297 (not (org-at-timestamp-p t))
10298 (not (org-in-regexp
10299 (concat org-plain-link-re "\\|"
10300 org-bracket-link-regexp "\\|"
10301 org-angle-link-re "\\|"
10302 "[ \t]:[^ \t\n]+:[ \t]*$")))
10303 (not (get-text-property (point) 'org-linked-text)))
10304 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10305 (lk0 (car lkall))
10306 (lk (if (stringp lk0) (list lk0) lk0))
10307 (lkend (cdr lkall)))
10308 (mapcar (lambda(l)
10309 (search-forward l nil lkend)
10310 (goto-char (match-beginning 0))
10311 (org-open-at-point))
10312 lk))
10313 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10314 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10315 ((and (org-at-timestamp-p t)
10316 (not (org-in-regexp org-bracket-link-regexp)))
10317 (org-follow-timestamp-link))
10318 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10319 (not (org-in-regexp org-any-link-re)))
10320 (org-footnote-action))
10322 (let (type path link line search (pos (point)))
10323 (catch 'match
10324 (save-excursion
10325 (skip-chars-forward "^]\n\r")
10326 (when (org-in-regexp org-bracket-link-regexp 1)
10327 (setq link (org-extract-attributes
10328 (org-link-unescape (org-match-string-no-properties 1))))
10329 (while (string-match " *\n *" link)
10330 (setq link (replace-match " " t t link)))
10331 (setq link (org-link-expand-abbrev link))
10332 (cond
10333 ((or (file-name-absolute-p link)
10334 (string-match "^\\.\\.?/" link))
10335 (setq type "file" path link))
10336 ((string-match org-link-re-with-space3 link)
10337 (setq type (match-string 1 link) path (match-string 2 link)))
10338 ((string-match "^help:+\\(.+\\)" link)
10339 (setq type "help" path (match-string 1 link)))
10340 (t (setq type "thisfile" path link)))
10341 (throw 'match t)))
10343 (when (get-text-property (point) 'org-linked-text)
10344 (setq type "thisfile"
10345 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10346 (1+ (point)) (point))
10347 path (buffer-substring
10348 (or (previous-single-property-change pos 'org-linked-text)
10349 (point-min))
10350 (or (next-single-property-change pos 'org-linked-text)
10351 (point-max)))
10352 ;; Ensure we will search for a <<<radio>>> link, not
10353 ;; a simple reference like <<ref>>
10354 path (concat "<" path))
10355 (throw 'match t))
10357 (save-excursion
10358 (when (or (org-in-regexp org-angle-link-re)
10359 (let ((match (org-in-regexp org-plain-link-re)))
10360 ;; Check a plain link is not within a bracket link
10361 (and match
10362 (save-excursion
10363 (progn
10364 (goto-char (car match))
10365 (not (org-in-regexp org-bracket-link-regexp))))))
10366 (let ((line_ending (save-excursion (end-of-line) (point))))
10367 ;; We are in a line before a plain or bracket link
10368 (or (re-search-forward org-plain-link-re line_ending t)
10369 (re-search-forward org-bracket-link-regexp line_ending t))))
10370 (setq type (match-string 1)
10371 path (org-link-unescape (match-string 2)))
10372 (throw 'match t)))
10373 (save-excursion
10374 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10375 (setq type "tags"
10376 path (match-string 1))
10377 (while (string-match ":" path)
10378 (setq path (replace-match "+" t t path)))
10379 (throw 'match t)))
10380 (when (org-in-regexp "<\\([^><\n]+\\)>")
10381 (setq type "tree-match"
10382 path (match-string 1))
10383 (throw 'match t)))
10384 (unless path
10385 (user-error "No link found"))
10387 ;; switch back to reference buffer
10388 ;; needed when if called in a temporary buffer through
10389 ;; org-open-link-from-string
10390 (with-current-buffer (or reference-buffer (current-buffer))
10392 ;; Remove any trailing spaces in path
10393 (if (string-match " +\\'" path)
10394 (setq path (replace-match "" t t path)))
10395 (if (and org-link-translation-function
10396 (fboundp org-link-translation-function))
10397 ;; Check if we need to translate the link
10398 (let ((tmp (funcall org-link-translation-function type path)))
10399 (setq type (car tmp) path (cdr tmp))))
10401 (cond
10403 ((assoc type org-link-protocols)
10404 (funcall (nth 1 (assoc type org-link-protocols)) path))
10406 ((equal type "help")
10407 (let ((f-or-v (intern path)))
10408 (cond ((fboundp f-or-v)
10409 (describe-function f-or-v))
10410 ((boundp f-or-v)
10411 (describe-variable f-or-v))
10412 (t (error "Not a known function or variable")))))
10414 ((equal type "mailto")
10415 (let ((cmd (car org-link-mailto-program))
10416 (args (cdr org-link-mailto-program)) args1
10417 (address path) (subject "") a)
10418 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10419 (setq address (match-string 1 path)
10420 subject (org-link-escape (match-string 2 path))))
10421 (while args
10422 (cond
10423 ((not (stringp (car args))) (push (pop args) args1))
10424 (t (setq a (pop args))
10425 (if (string-match "%a" a)
10426 (setq a (replace-match address t t a)))
10427 (if (string-match "%s" a)
10428 (setq a (replace-match subject t t a)))
10429 (push a args1))))
10430 (apply cmd (nreverse args1))))
10432 ((member type '("http" "https" "ftp" "news"))
10433 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
10434 (org-link-escape
10435 path org-link-escape-chars-browser)
10436 path))))
10438 ((string= type "doi")
10439 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
10440 (org-link-escape
10441 path org-link-escape-chars-browser)
10442 path))))
10444 ((member type '("message"))
10445 (browse-url (concat type ":" path)))
10447 ((string= type "tags")
10448 (org-tags-view arg path))
10450 ((string= type "tree-match")
10451 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10453 ((string= type "file")
10454 (if (string-match "::\\([0-9]+\\)\\'" path)
10455 (setq line (string-to-number (match-string 1 path))
10456 path (substring path 0 (match-beginning 0)))
10457 (if (string-match "::\\(.+\\)\\'" path)
10458 (setq search (match-string 1 path)
10459 path (substring path 0 (match-beginning 0)))))
10460 (if (string-match "[*?{]" (file-name-nondirectory path))
10461 (dired path)
10462 (org-open-file path arg line search)))
10464 ((string= type "shell")
10465 (let ((buf (generate-new-buffer "*Org Shell Output"))
10466 (cmd path))
10467 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10468 (string-match org-confirm-shell-link-not-regexp cmd))
10469 (not org-confirm-shell-link-function)
10470 (funcall org-confirm-shell-link-function
10471 (format "Execute \"%s\" in shell? "
10472 (org-add-props cmd nil
10473 'face 'org-warning))))
10474 (progn
10475 (message "Executing %s" cmd)
10476 (shell-command cmd buf)
10477 (if (featurep 'midnight)
10478 (setq clean-buffer-list-kill-buffer-names
10479 (cons buf clean-buffer-list-kill-buffer-names))))
10480 (error "Abort"))))
10482 ((string= type "elisp")
10483 (let ((cmd path))
10484 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10485 (string-match org-confirm-elisp-link-not-regexp cmd))
10486 (not org-confirm-elisp-link-function)
10487 (funcall org-confirm-elisp-link-function
10488 (format "Execute \"%s\" as elisp? "
10489 (org-add-props cmd nil
10490 'face 'org-warning))))
10491 (message "%s => %s" cmd
10492 (if (equal (string-to-char cmd) ?\()
10493 (eval (read cmd))
10494 (call-interactively (read cmd))))
10495 (error "Abort"))))
10497 ((and (string= type "thisfile")
10498 (run-hook-with-args-until-success
10499 'org-open-link-functions path)))
10501 ((string= type "thisfile")
10502 (if arg
10503 (switch-to-buffer-other-window
10504 (org-get-buffer-for-internal-link (current-buffer)))
10505 (org-mark-ring-push))
10506 (let ((cmd `(org-link-search
10507 ,path
10508 ,(cond ((equal arg '(4)) ''occur)
10509 ((equal arg '(16)) ''org-occur))
10510 ,pos)))
10511 (condition-case nil (let ((org-link-search-inhibit-query t))
10512 (eval cmd))
10513 (error (progn (widen) (eval cmd))))))
10515 (t (browse-url-at-point)))))))
10516 (move-marker org-open-link-marker nil)
10517 (run-hook-with-args 'org-follow-link-hook)))
10519 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10520 "Offer links in the current entry and return the selected link.
10521 If there is only one link, return it.
10522 If NTH is an integer, return the NTH link found.
10523 If ZERO is a string, check also this string for a link, and if
10524 there is one, return it."
10525 (with-current-buffer buffer
10526 (save-excursion
10527 (save-restriction
10528 (widen)
10529 (goto-char marker)
10530 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10531 "\\(" org-angle-link-re "\\)\\|"
10532 "\\(" org-plain-link-re "\\)"))
10533 (cnt ?0)
10534 (in-emacs (if (integerp nth) nil nth))
10535 have-zero end links link c)
10536 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10537 (push (match-string 0 zero) links)
10538 (setq cnt (1- cnt) have-zero t))
10539 (save-excursion
10540 (org-back-to-heading t)
10541 (setq end (save-excursion (outline-next-heading) (point)))
10542 (while (re-search-forward re end t)
10543 (push (match-string 0) links))
10544 (setq links (org-uniquify (reverse links))))
10545 (cond
10546 ((null links)
10547 (message "No links"))
10548 ((equal (length links) 1)
10549 (setq link (car links)))
10550 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10551 (setq link (nth (if have-zero nth (1- nth)) links)))
10552 (t ; we have to select a link
10553 (save-excursion
10554 (save-window-excursion
10555 (delete-other-windows)
10556 (with-output-to-temp-buffer "*Select Link*"
10557 (mapc (lambda (l)
10558 (if (not (string-match org-bracket-link-regexp l))
10559 (princ (format "[%c] %s\n" (incf cnt)
10560 (org-remove-angle-brackets l)))
10561 (if (match-end 3)
10562 (princ (format "[%c] %s (%s)\n" (incf cnt)
10563 (match-string 3 l) (match-string 1 l)))
10564 (princ (format "[%c] %s\n" (incf cnt)
10565 (match-string 1 l))))))
10566 links))
10567 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10568 (message "Select link to open, RET to open all:")
10569 (setq c (read-char-exclusive))
10570 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10571 (when (equal c ?q) (error "Abort"))
10572 (if (equal c ?\C-m)
10573 (setq link links)
10574 (setq nth (- c ?0))
10575 (if have-zero (setq nth (1+ nth)))
10576 (unless (and (integerp nth) (>= (length links) nth))
10577 (user-error "Invalid link selection"))
10578 (setq link (nth (1- nth) links)))))
10579 (cons link end))))))
10581 ;; Add special file links that specify the way of opening
10583 (org-add-link-type "file+sys" 'org-open-file-with-system)
10584 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10585 (defun org-open-file-with-system (path)
10586 "Open file at PATH using the system way of opening it."
10587 (org-open-file path 'system))
10588 (defun org-open-file-with-emacs (path)
10589 "Open file at PATH in Emacs."
10590 (org-open-file path 'emacs))
10593 ;;; File search
10595 (defvar org-create-file-search-functions nil
10596 "List of functions to construct the right search string for a file link.
10597 These functions are called in turn with point at the location to
10598 which the link should point.
10600 A function in the hook should first test if it would like to
10601 handle this file type, for example by checking the `major-mode'
10602 or the file extension. If it decides not to handle this file, it
10603 should just return nil to give other functions a chance. If it
10604 does handle the file, it must return the search string to be used
10605 when following the link. The search string will be part of the
10606 file link, given after a double colon, and `org-open-at-point'
10607 will automatically search for it. If special measures must be
10608 taken to make the search successful, another function should be
10609 added to the companion hook `org-execute-file-search-functions',
10610 which see.
10612 A function in this hook may also use `setq' to set the variable
10613 `description' to provide a suggestion for the descriptive text to
10614 be used for this link when it gets inserted into an Org-mode
10615 buffer with \\[org-insert-link].")
10617 (defvar org-execute-file-search-functions nil
10618 "List of functions to execute a file search triggered by a link.
10620 Functions added to this hook must accept a single argument, the
10621 search string that was part of the file link, the part after the
10622 double colon. The function must first check if it would like to
10623 handle this search, for example by checking the `major-mode' or
10624 the file extension. If it decides not to handle this search, it
10625 should just return nil to give other functions a chance. If it
10626 does handle the search, it must return a non-nil value to keep
10627 other functions from trying.
10629 Each function can access the current prefix argument through the
10630 variable `current-prefix-arg'. Note that a single prefix is used
10631 to force opening a link in Emacs, so it may be good to only use a
10632 numeric or double prefix to guide the search function.
10634 In case this is needed, a function in this hook can also restore
10635 the window configuration before `org-open-at-point' was called using:
10637 (set-window-configuration org-window-config-before-follow-link)")
10639 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10640 (defun org-link-search (s &optional type avoid-pos stealth)
10641 "Search for a link search option.
10642 If S is surrounded by forward slashes, it is interpreted as a
10643 regular expression. In org-mode files, this will create an `org-occur'
10644 sparse tree. In ordinary files, `occur' will be used to list matches.
10645 If the current buffer is in `dired-mode', grep will be used to search
10646 in all files. If AVOID-POS is given, ignore matches near that position.
10648 When optional argument STEALTH is non-nil, do not modify
10649 visibility around point, thus ignoring
10650 `org-show-hierarchy-above', `org-show-following-heading' and
10651 `org-show-siblings' variables."
10652 (let ((case-fold-search t)
10653 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10654 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10655 (append '(("") (" ") ("\t") ("\n"))
10656 org-emphasis-alist)
10657 "\\|") "\\)"))
10658 (pos (point))
10659 (pre nil) (post nil)
10660 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10661 (cond
10662 ;; First check if there are any special search functions
10663 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10664 ;; Now try the builtin stuff
10665 ((and (equal (string-to-char s0) ?#)
10666 (> (length s0) 1)
10667 (save-excursion
10668 (goto-char (point-min))
10669 (and
10670 (re-search-forward
10671 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10672 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10673 (setq type 'dedicated
10674 pos (match-beginning 0))))
10675 ;; There is an exact target for this
10676 (goto-char pos)
10677 (org-back-to-heading t)))
10678 ((save-excursion
10679 (goto-char (point-min))
10680 (and
10681 (re-search-forward
10682 (concat "<<" (regexp-quote s0) ">>") nil t)
10683 (setq type 'dedicated
10684 pos (match-beginning 0))))
10685 ;; There is an exact target for this
10686 (goto-char pos))
10687 ((save-excursion
10688 (goto-char (point-min))
10689 (and
10690 (re-search-forward
10691 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10692 (setq type 'dedicated pos (match-beginning 0))))
10693 ;; Found an element with a matching #+name affiliated keyword.
10694 (goto-char pos))
10695 ((and (string-match "^(\\(.*\\))$" s0)
10696 (save-excursion
10697 (goto-char (point-min))
10698 (and
10699 (re-search-forward
10700 (concat "[^[]" (regexp-quote
10701 (format org-coderef-label-format
10702 (match-string 1 s0))))
10703 nil t)
10704 (setq type 'dedicated
10705 pos (1+ (match-beginning 0))))))
10706 ;; There is a coderef target for this
10707 (goto-char pos))
10708 ((string-match "^/\\(.*\\)/$" s)
10709 ;; A regular expression
10710 (cond
10711 ((derived-mode-p 'org-mode)
10712 (org-occur (match-string 1 s)))
10713 (t (org-do-occur (match-string 1 s)))))
10714 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10715 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10716 (goto-char (point-min))
10717 (cond
10718 ((let (case-fold-search)
10719 (re-search-forward (format org-complex-heading-regexp-format
10720 (regexp-quote s))
10721 nil t))
10722 ;; OK, found a match
10723 (setq type 'dedicated)
10724 (goto-char (match-beginning 0)))
10725 ((and (not org-link-search-inhibit-query)
10726 (eq org-link-search-must-match-exact-headline 'query-to-create)
10727 (y-or-n-p "No match - create this as a new heading? "))
10728 (goto-char (point-max))
10729 (or (bolp) (newline))
10730 (insert "* " s "\n")
10731 (beginning-of-line 0))
10733 (goto-char pos)
10734 (error "No match"))))
10736 ;; A normal search string
10737 (when (equal (string-to-char s) ?*)
10738 ;; Anchor on headlines, post may include tags.
10739 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10740 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10741 s (substring s 1)))
10742 (remove-text-properties
10743 0 (length s)
10744 '(face nil mouse-face nil keymap nil fontified nil) s)
10745 ;; Make a series of regular expressions to find a match
10746 (setq words (org-split-string s "[ \n\r\t]+")
10748 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10749 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10750 "\\)" markers)
10751 re2a_ (concat "\\(" (mapconcat 'downcase words
10752 "[ \t\r\n]+") "\\)[ \t\r\n]")
10753 re2a (concat "[ \t\r\n]" re2a_)
10754 re4_ (concat "\\(" (mapconcat 'downcase words
10755 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10756 re4 (concat "[^a-zA-Z_]" re4_)
10758 re1 (concat pre re2 post)
10759 re3 (concat pre (if pre re4_ re4) post)
10760 re5 (concat pre ".*" re4)
10761 re2 (concat pre re2)
10762 re2a (concat pre (if pre re2a_ re2a))
10763 re4 (concat pre (if pre re4_ re4))
10764 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10765 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10766 re5 "\\)"))
10767 (cond
10768 ((eq type 'org-occur) (org-occur reall))
10769 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10770 (t (goto-char (point-min))
10771 (setq type 'fuzzy)
10772 (if (or (and (org-search-not-self 1 re0 nil t)
10773 (setq type 'dedicated))
10774 (org-search-not-self 1 re1 nil t)
10775 (org-search-not-self 1 re2 nil t)
10776 (org-search-not-self 1 re2a nil t)
10777 (org-search-not-self 1 re3 nil t)
10778 (org-search-not-self 1 re4 nil t)
10779 (org-search-not-self 1 re5 nil t))
10780 (goto-char (match-beginning 1))
10781 (goto-char pos)
10782 (error "No match"))))))
10783 (and (derived-mode-p 'org-mode)
10784 (not stealth)
10785 (org-show-context 'link-search))
10786 type))
10788 (defun org-search-not-self (group &rest args)
10789 "Execute `re-search-forward', but only accept matches that do not
10790 enclose the position of `org-open-link-marker'."
10791 (let ((m org-open-link-marker))
10792 (catch 'exit
10793 (while (apply 're-search-forward args)
10794 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10795 (goto-char (match-end group))
10796 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10797 (> (match-beginning 0) (marker-position m))
10798 (< (match-end 0) (marker-position m)))
10799 (save-match-data
10800 (or (not (org-in-regexp
10801 org-bracket-link-analytic-regexp 1))
10802 (not (match-end 4)) ; no description
10803 (and (<= (match-beginning 4) (point))
10804 (>= (match-end 4) (point))))))
10805 (throw 'exit (point))))))))
10807 (defun org-get-buffer-for-internal-link (buffer)
10808 "Return a buffer to be used for displaying the link target of internal links."
10809 (cond
10810 ((not org-display-internal-link-with-indirect-buffer)
10811 buffer)
10812 ((string-match "(Clone)$" (buffer-name buffer))
10813 (message "Buffer is already a clone, not making another one")
10814 ;; we also do not modify visibility in this case
10815 buffer)
10816 (t ; make a new indirect buffer for displaying the link
10817 (let* ((bn (buffer-name buffer))
10818 (ibn (concat bn "(Clone)"))
10819 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10820 (with-current-buffer ib (org-overview))
10821 ib))))
10823 (defun org-do-occur (regexp &optional cleanup)
10824 "Call the Emacs command `occur'.
10825 If CLEANUP is non-nil, remove the printout of the regular expression
10826 in the *Occur* buffer. This is useful if the regex is long and not useful
10827 to read."
10828 (occur regexp)
10829 (when cleanup
10830 (let ((cwin (selected-window)) win beg end)
10831 (when (setq win (get-buffer-window "*Occur*"))
10832 (select-window win))
10833 (goto-char (point-min))
10834 (when (re-search-forward "match[a-z]+" nil t)
10835 (setq beg (match-end 0))
10836 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10837 (setq end (1- (match-beginning 0)))))
10838 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10839 (goto-char (point-min))
10840 (select-window cwin))))
10842 ;;; The mark ring for links jumps
10844 (defvar org-mark-ring nil
10845 "Mark ring for positions before jumps in Org-mode.")
10846 (defvar org-mark-ring-last-goto nil
10847 "Last position in the mark ring used to go back.")
10848 ;; Fill and close the ring
10849 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10850 (loop for i from 1 to org-mark-ring-length do
10851 (push (make-marker) org-mark-ring))
10852 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10853 org-mark-ring)
10855 (defun org-mark-ring-push (&optional pos buffer)
10856 "Put the current position or POS into the mark ring and rotate it."
10857 (interactive)
10858 (setq pos (or pos (point)))
10859 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10860 (move-marker (car org-mark-ring)
10861 (or pos (point))
10862 (or buffer (current-buffer)))
10863 (message "%s"
10864 (substitute-command-keys
10865 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10867 (defun org-mark-ring-goto (&optional n)
10868 "Jump to the previous position in the mark ring.
10869 With prefix arg N, jump back that many stored positions. When
10870 called several times in succession, walk through the entire ring.
10871 Org-mode commands jumping to a different position in the current file,
10872 or to another Org-mode file, automatically push the old position
10873 onto the ring."
10874 (interactive "p")
10875 (let (p m)
10876 (if (eq last-command this-command)
10877 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10878 (setq p org-mark-ring))
10879 (setq org-mark-ring-last-goto p)
10880 (setq m (car p))
10881 (org-pop-to-buffer-same-window (marker-buffer m))
10882 (goto-char m)
10883 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10885 (defun org-remove-angle-brackets (s)
10886 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10887 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10889 (defun org-add-angle-brackets (s)
10890 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10891 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10893 (defun org-remove-double-quotes (s)
10894 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10895 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10898 ;;; Following specific links
10900 (defun org-follow-timestamp-link ()
10901 "Open an agenda view for the time-stamp date/range at point."
10902 (cond
10903 ((org-at-date-range-p t)
10904 (let ((org-agenda-start-on-weekday)
10905 (t1 (match-string 1))
10906 (t2 (match-string 2)) tt1 tt2)
10907 (setq tt1 (time-to-days (org-time-string-to-time t1))
10908 tt2 (time-to-days (org-time-string-to-time t2)))
10909 (let ((org-agenda-buffer-tmp-name
10910 (format "*Org Agenda(a:%s)"
10911 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10912 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10913 ((org-at-timestamp-p t)
10914 (let ((org-agenda-buffer-tmp-name
10915 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10916 (org-agenda-list nil (time-to-days (org-time-string-to-time
10917 (substring (match-string 1) 0 10)))
10918 1)))
10919 (t (error "This should not happen"))))
10922 ;;; Following file links
10923 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10924 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10925 (declare-function mailcap-mime-info
10926 "mailcap" (string &optional request no-decode))
10927 (defvar org-wait nil)
10928 (defun org-open-file (path &optional in-emacs line search)
10929 "Open the file at PATH.
10930 First, this expands any special file name abbreviations. Then the
10931 configuration variable `org-file-apps' is checked if it contains an
10932 entry for this file type, and if yes, the corresponding command is launched.
10934 If no application is found, Emacs simply visits the file.
10936 With optional prefix argument IN-EMACS, Emacs will visit the file.
10937 With a double \\[universal-argument] \\[universal-argument] \
10938 prefix arg, Org tries to avoid opening in Emacs
10939 and to use an external application to visit the file.
10941 Optional LINE specifies a line to go to, optional SEARCH a string
10942 to search for. If LINE or SEARCH is given, the file will be
10943 opened in Emacs, unless an entry from org-file-apps that makes
10944 use of groups in a regexp matches.
10946 If you want to change the way frames are used when following a
10947 link, please customize `org-link-frame-setup'.
10949 If the file does not exist, an error is thrown."
10950 (let* ((file (if (equal path "")
10951 buffer-file-name
10952 (substitute-in-file-name (expand-file-name path))))
10953 (file-apps (append org-file-apps (org-default-apps)))
10954 (apps (org-remove-if
10955 'org-file-apps-entry-match-against-dlink-p file-apps))
10956 (apps-dlink (org-remove-if-not
10957 'org-file-apps-entry-match-against-dlink-p file-apps))
10958 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10959 (dirp (if remp nil (file-directory-p file)))
10960 (file (if (and dirp org-open-directory-means-index-dot-org)
10961 (concat (file-name-as-directory file) "index.org")
10962 file))
10963 (a-m-a-p (assq 'auto-mode apps))
10964 (dfile (downcase file))
10965 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10966 (link (cond ((and (eq line nil)
10967 (eq search nil))
10968 file)
10969 (line
10970 (concat file "::" (number-to-string line)))
10971 (search
10972 (concat file "::" search))))
10973 (dlink (downcase link))
10974 (old-buffer (current-buffer))
10975 (old-pos (point))
10976 (old-mode major-mode)
10977 ext cmd link-match-data)
10978 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10979 (setq ext (match-string 1 dfile))
10980 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10981 (setq ext (match-string 1 dfile))))
10982 (cond
10983 ((member in-emacs '((16) system))
10984 (setq cmd (cdr (assoc 'system apps))))
10985 (in-emacs (setq cmd 'emacs))
10987 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10988 (and dirp (cdr (assoc 'directory apps)))
10989 ; first, try matching against apps-dlink
10990 ; if we get a match here, store the match data for later
10991 (let ((match (assoc-default dlink apps-dlink
10992 'string-match)))
10993 (if match
10994 (progn (setq link-match-data (match-data))
10995 match)
10996 (progn (setq in-emacs (or in-emacs line search))
10997 nil))) ; if we have no match in apps-dlink,
10998 ; always open the file in emacs if line or search
10999 ; is given (for backwards compatibility)
11000 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11001 'string-match)
11002 (cdr (assoc ext apps))
11003 (cdr (assoc t apps))))))
11004 (when (eq cmd 'system)
11005 (setq cmd (cdr (assoc 'system apps))))
11006 (when (eq cmd 'default)
11007 (setq cmd (cdr (assoc t apps))))
11008 (when (eq cmd 'mailcap)
11009 (require 'mailcap)
11010 (mailcap-parse-mailcaps)
11011 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11012 (command (mailcap-mime-info mime-type)))
11013 (if (stringp command)
11014 (setq cmd command)
11015 (setq cmd 'emacs))))
11016 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11017 (not (file-exists-p file))
11018 (not org-open-non-existing-files))
11019 (user-error "No such file: %s" file))
11020 (cond
11021 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11022 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11023 (while (string-match "['\"]%s['\"]" cmd)
11024 (setq cmd (replace-match "%s" t t cmd)))
11025 (while (string-match "%s" cmd)
11026 (setq cmd (replace-match
11027 (save-match-data
11028 (shell-quote-argument
11029 (convert-standard-filename file)))
11030 t t cmd)))
11032 ;; Replace "%1", "%2" etc. in command with group matches from regex
11033 (save-match-data
11034 (let ((match-index 1)
11035 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11036 (set-match-data link-match-data)
11037 (while (<= match-index number-of-groups)
11038 (let ((regex (concat "%" (number-to-string match-index)))
11039 (replace-with (match-string match-index dlink)))
11040 (while (string-match regex cmd)
11041 (setq cmd (replace-match replace-with t t cmd))))
11042 (setq match-index (+ match-index 1)))))
11044 (save-window-excursion
11045 (message "Running %s...done" cmd)
11046 (start-process-shell-command cmd nil cmd)
11047 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11048 ((or (stringp cmd)
11049 (eq cmd 'emacs))
11050 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11051 (widen)
11052 (if line (org-goto-line line)
11053 (if search (org-link-search search))))
11054 ((consp cmd)
11055 (let ((file (convert-standard-filename file)))
11056 (save-match-data
11057 (set-match-data link-match-data)
11058 (eval cmd))))
11059 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11060 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11061 (or (not (equal old-buffer (current-buffer)))
11062 (not (equal old-pos (point))))
11063 (org-mark-ring-push old-pos old-buffer))))
11065 (defun org-file-apps-entry-match-against-dlink-p (entry)
11066 "This function returns non-nil if `entry' uses a regular
11067 expression which should be matched against the whole link by
11068 org-open-file.
11070 It assumes that is the case when the entry uses a regular
11071 expression which has at least one grouping construct and the
11072 action is either a lisp form or a command string containing
11073 '%1', i.e. using at least one subexpression match as a
11074 parameter."
11075 (let ((selector (car entry))
11076 (action (cdr entry)))
11077 (if (stringp selector)
11078 (and (> (regexp-opt-depth selector) 0)
11079 (or (and (stringp action)
11080 (string-match "%[0-9]" action))
11081 (consp action)))
11082 nil)))
11084 (defun org-default-apps ()
11085 "Return the default applications for this operating system."
11086 (cond
11087 ((eq system-type 'darwin)
11088 org-file-apps-defaults-macosx)
11089 ((eq system-type 'windows-nt)
11090 org-file-apps-defaults-windowsnt)
11091 (t org-file-apps-defaults-gnu)))
11093 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11094 "Convert extensions to regular expressions in the cars of LIST.
11095 Also, weed out any non-string entries, because the return value is used
11096 only for regexp matching.
11097 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11098 point to the symbol `emacs', indicating that the file should
11099 be opened in Emacs."
11100 (append
11101 (delq nil
11102 (mapcar (lambda (x)
11103 (if (not (stringp (car x)))
11105 (if (string-match "\\W" (car x))
11107 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11108 list))
11109 (if add-auto-mode
11110 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11112 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11113 (defun org-file-remote-p (file)
11114 "Test whether FILE specifies a location on a remote system.
11115 Return non-nil if the location is indeed remote.
11117 For example, the filename \"/user@host:/foo\" specifies a location
11118 on the system \"/user@host:\"."
11119 (cond ((fboundp 'file-remote-p)
11120 (file-remote-p file))
11121 ((fboundp 'tramp-handle-file-remote-p)
11122 (tramp-handle-file-remote-p file))
11123 ((and (boundp 'ange-ftp-name-format)
11124 (string-match (car ange-ftp-name-format) file))
11125 t)))
11128 ;;;; Refiling
11130 (defun org-get-org-file ()
11131 "Read a filename, with default directory `org-directory'."
11132 (let ((default (or org-default-notes-file remember-data-file)))
11133 (read-file-name (format "File name [%s]: " default)
11134 (file-name-as-directory org-directory)
11135 default)))
11137 (defun org-notes-order-reversed-p ()
11138 "Check if the current file should receive notes in reversed order."
11139 (cond
11140 ((not org-reverse-note-order) nil)
11141 ((eq t org-reverse-note-order) t)
11142 ((not (listp org-reverse-note-order)) nil)
11143 (t (catch 'exit
11144 (let ((all org-reverse-note-order)
11145 entry)
11146 (while (setq entry (pop all))
11147 (if (string-match (car entry) buffer-file-name)
11148 (throw 'exit (cdr entry))))
11149 nil)))))
11151 (defvar org-refile-target-table nil
11152 "The list of refile targets, created by `org-refile'.")
11154 (defvar org-agenda-new-buffers nil
11155 "Buffers created to visit agenda files.")
11157 (defvar org-refile-cache nil
11158 "Cache for refile targets.")
11160 (defvar org-refile-markers nil
11161 "All the markers used for caching refile locations.")
11163 (defun org-refile-marker (pos)
11164 "Get a new refile marker, but only if caching is in use."
11165 (if (not org-refile-use-cache)
11167 (let ((m (make-marker)))
11168 (move-marker m pos)
11169 (push m org-refile-markers)
11170 m)))
11172 (defun org-refile-cache-clear ()
11173 "Clear the refile cache and disable all the markers."
11174 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11175 (setq org-refile-markers nil)
11176 (setq org-refile-cache nil)
11177 (message "Refile cache has been cleared"))
11179 (defun org-refile-cache-check-set (set)
11180 "Check if all the markers in the cache still have live buffers."
11181 (let (marker)
11182 (catch 'exit
11183 (while (and set (setq marker (nth 3 (pop set))))
11184 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11185 (when (and marker (null (marker-buffer marker)))
11186 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11187 (sit-for 3)
11188 (throw 'exit nil)))
11189 t)))
11191 (defun org-refile-cache-put (set &rest identifiers)
11192 "Push the refile targets SET into the cache, under IDENTIFIERS."
11193 (let* ((key (sha1 (prin1-to-string identifiers)))
11194 (entry (assoc key org-refile-cache)))
11195 (if entry
11196 (setcdr entry set)
11197 (push (cons key set) org-refile-cache))))
11199 (defun org-refile-cache-get (&rest identifiers)
11200 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11201 (cond
11202 ((not org-refile-cache) nil)
11203 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11205 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11206 org-refile-cache))))
11207 (and set (org-refile-cache-check-set set) set)))))
11209 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11210 "Produce a table with refile targets."
11211 (let ((case-fold-search nil)
11212 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11213 (entries (or org-refile-targets '((nil . (:level . 1)))))
11214 targets tgs txt re files f desc descre fast-path-p level pos0)
11215 (message "Getting targets...")
11216 (with-current-buffer (or default-buffer (current-buffer))
11217 (while (setq entry (pop entries))
11218 (setq files (car entry) desc (cdr entry))
11219 (setq fast-path-p nil)
11220 (cond
11221 ((null files) (setq files (list (current-buffer))))
11222 ((eq files 'org-agenda-files)
11223 (setq files (org-agenda-files 'unrestricted)))
11224 ((and (symbolp files) (fboundp files))
11225 (setq files (funcall files)))
11226 ((and (symbolp files) (boundp files))
11227 (setq files (symbol-value files))))
11228 (if (stringp files) (setq files (list files)))
11229 (cond
11230 ((eq (car desc) :tag)
11231 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11232 ((eq (car desc) :todo)
11233 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11234 ((eq (car desc) :regexp)
11235 (setq descre (cdr desc)))
11236 ((eq (car desc) :level)
11237 (setq descre (concat "^\\*\\{" (number-to-string
11238 (if org-odd-levels-only
11239 (1- (* 2 (cdr desc)))
11240 (cdr desc)))
11241 "\\}[ \t]")))
11242 ((eq (car desc) :maxlevel)
11243 (setq fast-path-p t)
11244 (setq descre (concat "^\\*\\{1," (number-to-string
11245 (if org-odd-levels-only
11246 (1- (* 2 (cdr desc)))
11247 (cdr desc)))
11248 "\\}[ \t]")))
11249 (t (error "Bad refiling target description %s" desc)))
11250 (while (setq f (pop files))
11251 (with-current-buffer
11252 (if (bufferp f) f (org-get-agenda-file-buffer f))
11254 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11255 (progn
11256 (if (bufferp f) (setq f (buffer-file-name
11257 (buffer-base-buffer f))))
11258 (setq f (and f (expand-file-name f)))
11259 (if (eq org-refile-use-outline-path 'file)
11260 (push (list (file-name-nondirectory f) f nil nil) tgs))
11261 (save-excursion
11262 (save-restriction
11263 (widen)
11264 (goto-char (point-min))
11265 (while (re-search-forward descre nil t)
11266 (goto-char (setq pos0 (point-at-bol)))
11267 (catch 'next
11268 (when org-refile-target-verify-function
11269 (save-match-data
11270 (or (funcall org-refile-target-verify-function)
11271 (throw 'next t))))
11272 (when (and (looking-at org-complex-heading-regexp)
11273 (not (member (match-string 4) excluded-entries))
11274 (match-string 4))
11275 (setq level (org-reduced-level
11276 (- (match-end 1) (match-beginning 1)))
11277 txt (org-link-display-format (match-string 4))
11278 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11279 re (format org-complex-heading-regexp-format
11280 (regexp-quote (match-string 4))))
11281 (when org-refile-use-outline-path
11282 (setq txt (mapconcat
11283 'org-protect-slash
11284 (append
11285 (if (eq org-refile-use-outline-path
11286 'file)
11287 (list (file-name-nondirectory
11288 (buffer-file-name
11289 (buffer-base-buffer))))
11290 (if (eq org-refile-use-outline-path
11291 'full-file-path)
11292 (list (buffer-file-name
11293 (buffer-base-buffer)))))
11294 (org-get-outline-path fast-path-p
11295 level txt)
11296 (list txt))
11297 "/")))
11298 (push (list txt f re (org-refile-marker (point)))
11299 tgs)))
11300 (when (= (point) pos0)
11301 ;; verification function has not moved point
11302 (goto-char (point-at-eol))))))))
11303 (when org-refile-use-cache
11304 (org-refile-cache-put tgs (buffer-file-name) descre))
11305 (setq targets (append tgs targets))))))
11306 (message "Getting targets...done")
11307 (nreverse targets)))
11309 (defun org-protect-slash (s)
11310 (while (string-match "/" s)
11311 (setq s (replace-match "\\" t t s)))
11314 (defvar org-olpa (make-vector 20 nil))
11316 (defun org-get-outline-path (&optional fastp level heading)
11317 "Return the outline path to the current entry, as a list.
11319 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11320 routine which makes outline path derivations for an entire file,
11321 avoiding backtracing. Refile target collection makes use of that."
11322 (if fastp
11323 (progn
11324 (if (> level 19)
11325 (error "Outline path failure, more than 19 levels"))
11326 (loop for i from level upto 19 do
11327 (aset org-olpa i nil))
11328 (prog1
11329 (delq nil (append org-olpa nil))
11330 (aset org-olpa level heading)))
11331 (let (rtn case-fold-search)
11332 (save-excursion
11333 (save-restriction
11334 (widen)
11335 (while (org-up-heading-safe)
11336 (when (looking-at org-complex-heading-regexp)
11337 (push (org-trim
11338 (replace-regexp-in-string
11339 ;; Remove statistical/checkboxes cookies
11340 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11341 (org-match-string-no-properties 4)))
11342 rtn)))
11343 rtn)))))
11345 (defun org-format-outline-path (path &optional width prefix separator)
11346 "Format the outline path PATH for display.
11347 WIDTH is the maximum number of characters that is available.
11348 PREFIX is a prefix to be included in the returned string,
11349 such as the file name.
11350 SEPARATOR is inserted between the different parts of the path,
11351 the default is \"/\"."
11352 (setq width (or width 79))
11353 (if prefix (setq width (- width (length prefix))))
11354 (if (not path)
11355 (or prefix "")
11356 (let* ((nsteps (length path))
11357 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11358 (maxwidth (if (<= total-width width)
11359 10000 ;; everything fits
11360 ;; we need to shorten the level headings
11361 (/ (- width nsteps) nsteps)))
11362 (org-odd-levels-only nil)
11363 (n 0)
11364 (total (1+ (length prefix))))
11365 (setq maxwidth (max maxwidth 10))
11366 (concat prefix
11367 (if prefix (or separator "/"))
11368 (mapconcat
11369 (lambda (h)
11370 (setq n (1+ n))
11371 (if (and (= n nsteps) (< maxwidth 10000))
11372 (setq maxwidth (- total-width total)))
11373 (if (< (length h) maxwidth)
11374 (progn (setq total (+ total (length h) 1)) h)
11375 (setq h (substring h 0 (- maxwidth 2))
11376 total (+ total maxwidth 1))
11377 (if (string-match "[ \t]+\\'" h)
11378 (setq h (substring h 0 (match-beginning 0))))
11379 (setq h (concat h "..")))
11380 (org-add-props h nil 'face
11381 (nth (% (1- n) org-n-level-faces)
11382 org-level-faces))
11384 path (or separator "/"))))))
11386 (defun org-display-outline-path (&optional file current separator just-return-string)
11387 "Display the current outline path in the echo area.
11389 If FILE is non-nil, prepend the output with the file name.
11390 If CURRENT is non-nil, append the current heading to the output.
11391 SEPARATOR is passed through to `org-format-outline-path'. It separates
11392 the different parts of the path and defaults to \"/\".
11393 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11394 (interactive "P")
11395 (let* (case-fold-search
11396 message-log-max ; Don't populate the *Messages* buffer
11397 (bfn (buffer-file-name (buffer-base-buffer)))
11398 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11399 res)
11400 (if current (setq path (append path
11401 (save-excursion
11402 (org-back-to-heading t)
11403 (if (looking-at org-complex-heading-regexp)
11404 (list (match-string 4)))))))
11405 (setq res
11406 (org-format-outline-path
11407 path
11408 (1- (frame-width))
11409 (and file bfn (concat (file-name-nondirectory bfn) separator))
11410 separator))
11411 (if just-return-string
11412 (org-no-properties res)
11413 (message "%s" res))))
11415 (defvar org-refile-history nil
11416 "History for refiling operations.")
11418 (defvar org-after-refile-insert-hook nil
11419 "Hook run after `org-refile' has inserted its stuff at the new location.
11420 Note that this is still *before* the stuff will be removed from
11421 the *old* location.")
11423 (defvar org-capture-last-stored-marker)
11424 (defvar org-refile-keep nil
11425 "Non-nil means `org-refile' will copy instead of refile.")
11427 (defun org-copy ()
11428 "Like `org-refile', but copy."
11429 (interactive)
11430 (let ((org-refile-keep t))
11431 (funcall 'org-refile nil nil nil "Copy")))
11433 (defun org-refile (&optional goto default-buffer rfloc msg)
11434 "Move the entry or entries at point to another heading.
11435 The list of target headings is compiled using the information in
11436 `org-refile-targets', which see.
11438 At the target location, the entry is filed as a subitem of the target
11439 heading. Depending on `org-reverse-note-order', the new subitem will
11440 either be the first or the last subitem.
11442 If there is an active region, all entries in that region will be moved.
11443 However, the region must fulfill the requirement that the first heading
11444 is the first one sets the top-level of the moved text - at most siblings
11445 below it are allowed.
11447 With prefix arg GOTO, the command will only visit the target location
11448 and not actually move anything.
11450 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11451 go to the location where the last refiling operation has put the subtree.
11452 With a prefix argument of `2', refile to the running clock.
11454 RFLOC can be a refile location obtained in a different way.
11456 MSG is a string to replace \"Refile\" in the default prompt with
11457 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11459 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11461 If you are using target caching (see `org-refile-use-cache'),
11462 you have to clear the target cache in order to find new targets.
11463 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11464 prefix argument (`C-u C-u C-u C-c C-w')."
11466 (interactive "P")
11467 (if (member goto '(0 (64)))
11468 (org-refile-cache-clear)
11469 (let* ((actionmsg (or msg "Refile"))
11470 (cbuf (current-buffer))
11471 (regionp (org-region-active-p))
11472 (region-start (and regionp (region-beginning)))
11473 (region-end (and regionp (region-end)))
11474 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11475 pos it nbuf file re level reversed)
11476 (setq last-command nil)
11477 (when regionp
11478 (goto-char region-start)
11479 (or (bolp) (goto-char (point-at-bol)))
11480 (setq region-start (point))
11481 (unless (or (org-kill-is-subtree-p
11482 (buffer-substring region-start region-end))
11483 (prog1 org-refile-active-region-within-subtree
11484 (let ((s (point-at-eol)))
11485 (org-toggle-heading)
11486 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11487 (user-error "The region is not a (sequence of) subtree(s)")))
11488 (if (equal goto '(16))
11489 (org-refile-goto-last-stored)
11490 (when (or
11491 (and (equal goto 2)
11492 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11493 (prog1
11494 (setq it (list (or org-clock-heading "running clock")
11495 (buffer-file-name
11496 (marker-buffer org-clock-hd-marker))
11498 (marker-position org-clock-hd-marker)))
11499 (setq goto nil)))
11500 (setq it (or rfloc
11501 (let (heading-text)
11502 (save-excursion
11503 (unless goto
11504 (org-back-to-heading t)
11505 (setq heading-text
11506 (nth 4 (org-heading-components))))
11508 (org-refile-get-location
11509 (cond (goto "Goto")
11510 (regionp (concat actionmsg " region to"))
11511 (t (concat actionmsg " subtree \""
11512 heading-text "\" to")))
11513 default-buffer
11514 (and (not (equal '(4) goto))
11515 org-refile-allow-creating-parent-nodes)
11516 goto))))))
11517 (setq file (nth 1 it)
11518 re (nth 2 it)
11519 pos (nth 3 it))
11520 (if (and (not goto)
11522 (equal (buffer-file-name) file)
11523 (if regionp
11524 (and (>= pos region-start)
11525 (<= pos region-end))
11526 (and (>= pos (point))
11527 (< pos (save-excursion
11528 (org-end-of-subtree t t))))))
11529 (error "Cannot refile to position inside the tree or region"))
11531 (setq nbuf (or (find-buffer-visiting file)
11532 (find-file-noselect file)))
11533 (if goto
11534 (progn
11535 (org-pop-to-buffer-same-window nbuf)
11536 (goto-char pos)
11537 (org-show-context 'org-goto))
11538 (if regionp
11539 (progn
11540 (org-kill-new (buffer-substring region-start region-end))
11541 (org-save-markers-in-region region-start region-end))
11542 (org-copy-subtree 1 nil t))
11543 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11544 (find-file-noselect file)))
11545 (setq reversed (org-notes-order-reversed-p))
11546 (save-excursion
11547 (save-restriction
11548 (widen)
11549 (if pos
11550 (progn
11551 (goto-char pos)
11552 (looking-at org-outline-regexp)
11553 (setq level (org-get-valid-level (funcall outline-level) 1))
11554 (goto-char
11555 (if reversed
11556 (or (outline-next-heading) (point-max))
11557 (or (save-excursion (org-get-next-sibling))
11558 (org-end-of-subtree t t)
11559 (point-max)))))
11560 (setq level 1)
11561 (if (not reversed)
11562 (goto-char (point-max))
11563 (goto-char (point-min))
11564 (or (outline-next-heading) (goto-char (point-max)))))
11565 (if (not (bolp)) (newline))
11566 (org-paste-subtree level)
11567 (when org-log-refile
11568 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11569 (unless (eq org-log-refile 'note)
11570 (save-excursion (org-add-log-note))))
11571 (and org-auto-align-tags
11572 (let ((org-loop-over-headlines-in-active-region nil))
11573 (org-set-tags nil t)))
11574 (with-demoted-errors
11575 (bookmark-set "org-refile-last-stored"))
11576 ;; If we are refiling for capture, make sure that the
11577 ;; last-capture pointers point here
11578 (when (org-bound-and-true-p org-refile-for-capture)
11579 (with-demoted-errors
11580 (bookmark-set "org-capture-last-stored-marker"))
11581 (move-marker org-capture-last-stored-marker (point)))
11582 (if (fboundp 'deactivate-mark) (deactivate-mark))
11583 (run-hooks 'org-after-refile-insert-hook))))
11584 (unless org-refile-keep
11585 (if regionp
11586 (delete-region (point) (+ (point) (- region-end region-start)))
11587 (delete-region
11588 (point-at-bol)
11589 (min (buffer-size) (1+ (org-end-of-subtree t))))))
11590 (when (featurep 'org-inlinetask)
11591 (org-inlinetask-remove-END-maybe))
11592 (setq org-markers-to-move nil)
11593 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11595 (defun org-refile-goto-last-stored ()
11596 "Go to the location where the last refile was stored."
11597 (interactive)
11598 (bookmark-jump "org-refile-last-stored")
11599 (message "This is the location of the last refile"))
11601 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11602 no-exclude)
11603 "Prompt the user for a refile location, using PROMPT.
11604 PROMPT should not be suffixed with a colon and a space, because
11605 this function appends the default value from
11606 `org-refile-history' automatically, if that is not empty.
11607 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11608 this is used for the GOTO interface."
11609 (let ((org-refile-targets org-refile-targets)
11610 (org-refile-use-outline-path org-refile-use-outline-path)
11611 excluded-entries)
11612 (when (and (derived-mode-p 'org-mode)
11613 (not org-refile-use-cache)
11614 (not no-exclude))
11615 (org-map-tree
11616 (lambda()
11617 (setq excluded-entries
11618 (append excluded-entries (list (org-get-heading t t)))))))
11619 (setq org-refile-target-table
11620 (org-refile-get-targets default-buffer excluded-entries)))
11621 (unless org-refile-target-table
11622 (user-error "No refile targets"))
11623 (let* ((cbuf (current-buffer))
11624 (partial-completion-mode nil)
11625 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11626 (cfunc (if (and org-refile-use-outline-path
11627 org-outline-path-complete-in-steps)
11628 'org-olpath-completing-read
11629 'org-icompleting-read))
11630 (extra (if org-refile-use-outline-path "/" ""))
11631 (cbnex (concat (buffer-name) extra))
11632 (filename (and cfn (expand-file-name cfn)))
11633 (tbl (mapcar
11634 (lambda (x)
11635 (if (and (not (member org-refile-use-outline-path
11636 '(file full-file-path)))
11637 (not (equal filename (nth 1 x))))
11638 (cons (concat (car x) extra " ("
11639 (file-name-nondirectory (nth 1 x)) ")")
11640 (cdr x))
11641 (cons (concat (car x) extra) (cdr x))))
11642 org-refile-target-table))
11643 (completion-ignore-case t)
11644 cdef
11645 (prompt (concat prompt
11646 (or (and (car org-refile-history)
11647 (concat " (default " (car org-refile-history) ")"))
11648 (and (assoc cbnex tbl) (setq cdef cbnex)
11649 (concat " (default " cbnex ")"))) ": "))
11650 pa answ parent-target child parent old-hist)
11651 (setq old-hist org-refile-history)
11652 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11653 nil 'org-refile-history (or cdef (car org-refile-history))))
11654 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11655 (org-refile-check-position pa)
11656 (if pa
11657 (progn
11658 (when (or (not org-refile-history)
11659 (not (eq old-hist org-refile-history))
11660 (not (equal (car pa) (car org-refile-history))))
11661 (setq org-refile-history
11662 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11663 org-refile-history
11664 (cdr org-refile-history))))
11665 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11666 (pop org-refile-history)))
11668 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11669 (progn
11670 (setq parent (match-string 1 answ)
11671 child (match-string 2 answ))
11672 (setq parent-target (or (assoc parent tbl)
11673 (assoc (concat parent "/") tbl)))
11674 (when (and parent-target
11675 (or (eq new-nodes t)
11676 (and (eq new-nodes 'confirm)
11677 (y-or-n-p (format "Create new node \"%s\"? "
11678 child)))))
11679 (org-refile-new-child parent-target child)))
11680 (user-error "Invalid target location")))))
11682 (declare-function org-string-nw-p "org-macs" (s))
11683 (defun org-refile-check-position (refile-pointer)
11684 "Check if the refile pointer matches the headline to which it points."
11685 (let* ((file (nth 1 refile-pointer))
11686 (re (nth 2 refile-pointer))
11687 (pos (nth 3 refile-pointer))
11688 buffer)
11689 (if (and (not (markerp pos)) (not file))
11690 (user-error "Please save the buffer to a file before refiling")
11691 (when (org-string-nw-p re)
11692 (setq buffer (if (markerp pos)
11693 (marker-buffer pos)
11694 (or (find-buffer-visiting file)
11695 (find-file-noselect file))))
11696 (with-current-buffer buffer
11697 (save-excursion
11698 (save-restriction
11699 (widen)
11700 (goto-char pos)
11701 (beginning-of-line 1)
11702 (unless (org-looking-at-p re)
11703 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11705 (defun org-refile-new-child (parent-target child)
11706 "Use refile target PARENT-TARGET to add new CHILD below it."
11707 (unless parent-target
11708 (error "Cannot find parent for new node"))
11709 (let ((file (nth 1 parent-target))
11710 (pos (nth 3 parent-target))
11711 level)
11712 (with-current-buffer (or (find-buffer-visiting file)
11713 (find-file-noselect file))
11714 (save-excursion
11715 (save-restriction
11716 (widen)
11717 (if pos
11718 (goto-char pos)
11719 (goto-char (point-max))
11720 (if (not (bolp)) (newline)))
11721 (when (looking-at org-outline-regexp)
11722 (setq level (funcall outline-level))
11723 (org-end-of-subtree t t))
11724 (org-back-over-empty-lines)
11725 (insert "\n" (make-string
11726 (if pos (org-get-valid-level level 1) 1) ?*)
11727 " " child "\n")
11728 (beginning-of-line 0)
11729 (list (concat (car parent-target) "/" child) file "" (point)))))))
11731 (defun org-olpath-completing-read (prompt collection &rest args)
11732 "Read an outline path like a file name."
11733 (let ((thetable collection)
11734 (org-completion-use-ido nil) ; does not work with ido.
11735 (org-completion-use-iswitchb nil)) ; or iswitchb
11736 (apply
11737 'org-icompleting-read prompt
11738 (lambda (string predicate &optional flag)
11739 (let (rtn r f (l (length string)))
11740 (cond
11741 ((eq flag nil)
11742 ;; try completion
11743 (try-completion string thetable))
11744 ((eq flag t)
11745 ;; all-completions
11746 (setq rtn (all-completions string thetable predicate))
11747 (mapcar
11748 (lambda (x)
11749 (setq r (substring x l))
11750 (if (string-match " ([^)]*)$" x)
11751 (setq f (match-string 0 x))
11752 (setq f ""))
11753 (if (string-match "/" r)
11754 (concat string (substring r 0 (match-end 0)) f)
11756 rtn))
11757 ((eq flag 'lambda)
11758 ;; exact match?
11759 (assoc string thetable)))))
11760 args)))
11762 ;;;; Dynamic blocks
11764 (defun org-find-dblock (name)
11765 "Find the first dynamic block with name NAME in the buffer.
11766 If not found, stay at current position and return nil."
11767 (let ((case-fold-search t) pos)
11768 (save-excursion
11769 (goto-char (point-min))
11770 (setq pos (and (re-search-forward
11771 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11772 (match-beginning 0))))
11773 (if pos (goto-char pos))
11774 pos))
11776 (defconst org-dblock-start-re
11777 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11778 "Matches the start line of a dynamic block, with parameters.")
11780 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11781 "Matches the end of a dynamic block.")
11783 (defun org-create-dblock (plist)
11784 "Create a dynamic block section, with parameters taken from PLIST.
11785 PLIST must contain a :name entry which is used as name of the block."
11786 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11787 (end-of-line 1)
11788 (newline))
11789 (let ((col (current-column))
11790 (name (plist-get plist :name)))
11791 (insert "#+BEGIN: " name)
11792 (while plist
11793 (if (eq (car plist) :name)
11794 (setq plist (cddr plist))
11795 (insert " " (prin1-to-string (pop plist)))))
11796 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11797 (beginning-of-line -2)))
11799 (defun org-prepare-dblock ()
11800 "Prepare dynamic block for refresh.
11801 This empties the block, puts the cursor at the insert position and returns
11802 the property list including an extra property :name with the block name."
11803 (unless (looking-at org-dblock-start-re)
11804 (user-error "Not at a dynamic block"))
11805 (let* ((begdel (1+ (match-end 0)))
11806 (name (org-no-properties (match-string 1)))
11807 (params (append (list :name name)
11808 (read (concat "(" (match-string 3) ")")))))
11809 (save-excursion
11810 (beginning-of-line 1)
11811 (skip-chars-forward " \t")
11812 (setq params (plist-put params :indentation-column (current-column))))
11813 (unless (re-search-forward org-dblock-end-re nil t)
11814 (error "Dynamic block not terminated"))
11815 (setq params
11816 (append params
11817 (list :content (buffer-substring
11818 begdel (match-beginning 0)))))
11819 (delete-region begdel (match-beginning 0))
11820 (goto-char begdel)
11821 (open-line 1)
11822 params))
11824 (defun org-map-dblocks (&optional command)
11825 "Apply COMMAND to all dynamic blocks in the current buffer.
11826 If COMMAND is not given, use `org-update-dblock'."
11827 (let ((cmd (or command 'org-update-dblock)))
11828 (save-excursion
11829 (goto-char (point-min))
11830 (while (re-search-forward org-dblock-start-re nil t)
11831 (goto-char (match-beginning 0))
11832 (save-excursion
11833 (condition-case nil
11834 (funcall cmd)
11835 (error (message "Error during update of dynamic block"))))
11836 (unless (re-search-forward org-dblock-end-re nil t)
11837 (error "Dynamic block not terminated"))))))
11839 (defun org-dblock-update (&optional arg)
11840 "User command for updating dynamic blocks.
11841 Update the dynamic block at point. With prefix ARG, update all dynamic
11842 blocks in the buffer."
11843 (interactive "P")
11844 (if arg
11845 (org-update-all-dblocks)
11846 (or (looking-at org-dblock-start-re)
11847 (org-beginning-of-dblock))
11848 (org-update-dblock)))
11850 (defun org-update-dblock ()
11851 "Update the dynamic block at point.
11852 This means to empty the block, parse for parameters and then call
11853 the correct writing function."
11854 (interactive)
11855 (save-window-excursion
11856 (let* ((pos (point))
11857 (line (org-current-line))
11858 (params (org-prepare-dblock))
11859 (name (plist-get params :name))
11860 (indent (plist-get params :indentation-column))
11861 (cmd (intern (concat "org-dblock-write:" name))))
11862 (message "Updating dynamic block `%s' at line %d..." name line)
11863 (funcall cmd params)
11864 (message "Updating dynamic block `%s' at line %d...done" name line)
11865 (goto-char pos)
11866 (when (and indent (> indent 0))
11867 (setq indent (make-string indent ?\ ))
11868 (save-excursion
11869 (org-beginning-of-dblock)
11870 (forward-line 1)
11871 (while (not (looking-at org-dblock-end-re))
11872 (insert indent)
11873 (beginning-of-line 2))
11874 (when (looking-at org-dblock-end-re)
11875 (and (looking-at "[ \t]+")
11876 (replace-match ""))
11877 (insert indent)))))))
11879 (defun org-beginning-of-dblock ()
11880 "Find the beginning of the dynamic block at point.
11881 Error if there is no such block at point."
11882 (let ((pos (point))
11883 beg)
11884 (end-of-line 1)
11885 (if (and (re-search-backward org-dblock-start-re nil t)
11886 (setq beg (match-beginning 0))
11887 (re-search-forward org-dblock-end-re nil t)
11888 (> (match-end 0) pos))
11889 (goto-char beg)
11890 (goto-char pos)
11891 (error "Not in a dynamic block"))))
11893 (defun org-update-all-dblocks ()
11894 "Update all dynamic blocks in the buffer.
11895 This function can be used in a hook."
11896 (interactive)
11897 (when (derived-mode-p 'org-mode)
11898 (org-map-dblocks 'org-update-dblock)))
11901 ;;;; Completion
11903 (defun org-get-export-keywords ()
11904 "Return a list of all currently understood export keywords.
11905 Export keywords include options, block names, attributes and
11906 keywords relative to each registered export back-end."
11907 (delq nil
11908 (let (keywords)
11909 (mapc
11910 (lambda (back-end)
11911 (let ((props (cdr back-end)))
11912 ;; Back-end name (for keywords, like #+LATEX:)
11913 (push (upcase (symbol-name (car back-end))) keywords)
11914 ;; Back-end options.
11915 (mapc (lambda (option) (push (cadr option) keywords))
11916 (plist-get (cdr back-end) :options-alist))))
11917 (org-bound-and-true-p org-export-registered-backends))
11918 keywords)))
11920 (defconst org-options-keywords
11921 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11922 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11923 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11924 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11925 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11927 (defcustom org-structure-template-alist
11928 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11929 "<src lang=\"?\">\n\n</src>")
11930 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11931 "<example>\n?\n</example>")
11932 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11933 "<quote>\n?\n</quote>")
11934 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11935 "<verse>\n?\n</verse>")
11936 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11937 "<verbatim>\n?\n</verbatim>")
11938 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11939 "<center>\n?\n</center>")
11940 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11941 "<literal style=\"latex\">\n?\n</literal>")
11942 ("L" "#+LaTeX: "
11943 "<literal style=\"latex\">?</literal>")
11944 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11945 "<literal style=\"html\">\n?\n</literal>")
11946 ("H" "#+HTML: "
11947 "<literal style=\"html\">?</literal>")
11948 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11949 ("A" "#+ASCII: ")
11950 ("i" "#+INDEX: ?"
11951 "#+INDEX: ?")
11952 ("I" "#+INCLUDE: %file ?"
11953 "<include file=%file markup=\"?\">"))
11954 "Structure completion elements.
11955 This is a list of abbreviation keys and values. The value gets inserted
11956 if you type `<' followed by the key and then press the completion key,
11957 usually `M-TAB'. %file will be replaced by a file name after prompting
11958 for the file using completion. The cursor will be placed at the position
11959 of the `?` in the template.
11960 There are two templates for each key, the first uses the original Org syntax,
11961 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11962 the default when the /org-mtags.el/ module has been loaded. See also the
11963 variable `org-mtags-prefer-muse-templates'."
11964 :group 'org-completion
11965 :type '(repeat
11966 (string :tag "Key")
11967 (string :tag "Template")
11968 (string :tag "Muse Template")))
11970 (defun org-try-structure-completion ()
11971 "Try to complete a structure template before point.
11972 This looks for strings like \"<e\" on an otherwise empty line and
11973 expands them."
11974 (let ((l (buffer-substring (point-at-bol) (point)))
11976 (when (and (looking-at "[ \t]*$")
11977 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11978 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11979 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11980 (match-beginning 1)) a)
11981 t)))
11983 (defun org-complete-expand-structure-template (start cell)
11984 "Expand a structure template."
11985 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11986 (rpl (nth (if musep 2 1) cell))
11987 (ind ""))
11988 (delete-region start (point))
11989 (when (string-match "\\`#\\+" rpl)
11990 (cond
11991 ((bolp))
11992 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11993 (setq ind (buffer-substring (point-at-bol) (point))))
11994 (t (newline))))
11995 (setq start (point))
11996 (if (string-match "%file" rpl)
11997 (setq rpl (replace-match
11998 (concat
11999 "\""
12000 (save-match-data
12001 (abbreviate-file-name (read-file-name "Include file: ")))
12002 "\"")
12003 t t rpl)))
12004 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12005 (concat "\n" ind)))
12006 (insert rpl)
12007 (if (re-search-backward "\\?" start t) (delete-char 1))))
12009 ;;;; TODO, DEADLINE, Comments
12011 (defun org-toggle-comment ()
12012 "Change the COMMENT state of an entry."
12013 (interactive)
12014 (save-excursion
12015 (org-back-to-heading)
12016 (let (case-fold-search)
12017 (cond
12018 ((looking-at (format org-heading-keyword-regexp-format
12019 org-comment-string))
12020 (goto-char (match-end 1))
12021 (looking-at (concat " +" org-comment-string))
12022 (replace-match "" t t)
12023 (when (eolp) (insert " ")))
12024 ((looking-at org-outline-regexp)
12025 (goto-char (match-end 0))
12026 (insert org-comment-string " "))))))
12028 (defvar org-last-todo-state-is-todo nil
12029 "This is non-nil when the last TODO state change led to a TODO state.
12030 If the last change removed the TODO tag or switched to DONE, then
12031 this is nil.")
12033 (defvar org-setting-tags nil) ; dynamically skipped
12035 (defvar org-todo-setup-filter-hook nil
12036 "Hook for functions that pre-filter todo specs.
12037 Each function takes a todo spec and returns either nil or the spec
12038 transformed into canonical form." )
12040 (defvar org-todo-get-default-hook nil
12041 "Hook for functions that get a default item for todo.
12042 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12043 nil or a string to be used for the todo mark." )
12045 (defvar org-agenda-headline-snapshot-before-repeat)
12047 (defun org-current-effective-time ()
12048 "Return current time adjusted for `org-extend-today-until' variable."
12049 (let* ((ct (org-current-time))
12050 (dct (decode-time ct))
12051 (ct1
12052 (cond
12053 (org-use-last-clock-out-time-as-effective-time
12054 (or (org-clock-get-last-clock-out-time) ct))
12055 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12056 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12057 (t ct))))
12058 ct1))
12060 (defun org-todo-yesterday (&optional arg)
12061 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12062 (interactive "P")
12063 (if (eq major-mode 'org-agenda-mode)
12064 (apply 'org-agenda-todo-yesterday arg)
12065 (let* ((hour (third (decode-time
12066 (org-current-time))))
12067 (org-extend-today-until (1+ hour)))
12068 (org-todo arg))))
12070 (defvar org-block-entry-blocking ""
12071 "First entry preventing the TODO state change.")
12073 (defun org-todo (&optional arg)
12074 "Change the TODO state of an item.
12075 The state of an item is given by a keyword at the start of the heading,
12076 like
12077 *** TODO Write paper
12078 *** DONE Call mom
12080 The different keywords are specified in the variable `org-todo-keywords'.
12081 By default the available states are \"TODO\" and \"DONE\".
12082 So for this example: when the item starts with TODO, it is changed to DONE.
12083 When it starts with DONE, the DONE is removed. And when neither TODO nor
12084 DONE are present, add TODO at the beginning of the heading.
12086 With \\[universal-argument] prefix arg, use completion to determine the new \
12087 state.
12088 With numeric prefix arg, switch to that state.
12089 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12090 keywords (nextset).
12091 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12092 With a numeric prefix arg of 0, inhibit note taking for the change.
12094 For calling through lisp, arg is also interpreted in the following way:
12095 'none -> empty state
12096 \"\"(empty string) -> switch to empty state
12097 'done -> switch to DONE
12098 'nextset -> switch to the next set of keywords
12099 'previousset -> switch to the previous set of keywords
12100 \"WAITING\" -> switch to the specified keyword, but only if it
12101 really is a member of `org-todo-keywords'."
12102 (interactive "P")
12103 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12104 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12105 'region-start-level 'region))
12106 org-loop-over-headlines-in-active-region)
12107 (org-map-entries
12108 `(org-todo ,arg)
12109 org-loop-over-headlines-in-active-region
12110 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12111 (if (equal arg '(16)) (setq arg 'nextset))
12112 (let ((org-blocker-hook org-blocker-hook)
12113 commentp
12114 case-fold-search)
12115 (when (equal arg '(64))
12116 (setq arg nil org-blocker-hook nil))
12117 (when (and org-blocker-hook
12118 (or org-inhibit-blocking
12119 (org-entry-get nil "NOBLOCKING")))
12120 (setq org-blocker-hook nil))
12121 (save-excursion
12122 (catch 'exit
12123 (org-back-to-heading t)
12124 (when (looking-at (concat "^\\*+ " org-comment-string))
12125 (org-toggle-comment)
12126 (setq commentp t))
12127 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12128 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12129 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12130 (let* ((match-data (match-data))
12131 (startpos (point-at-bol))
12132 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12133 (org-log-done org-log-done)
12134 (org-log-repeat org-log-repeat)
12135 (org-todo-log-states org-todo-log-states)
12136 (org-inhibit-logging
12137 (if (equal arg 0)
12138 (progn (setq arg nil) 'note) org-inhibit-logging))
12139 (this (match-string 1))
12140 (hl-pos (match-beginning 0))
12141 (head (org-get-todo-sequence-head this))
12142 (ass (assoc head org-todo-kwd-alist))
12143 (interpret (nth 1 ass))
12144 (done-word (nth 3 ass))
12145 (final-done-word (nth 4 ass))
12146 (org-last-state (or this ""))
12147 (completion-ignore-case t)
12148 (member (member this org-todo-keywords-1))
12149 (tail (cdr member))
12150 (org-state (cond
12151 ((and org-todo-key-trigger
12152 (or (and (equal arg '(4))
12153 (eq org-use-fast-todo-selection 'prefix))
12154 (and (not arg) org-use-fast-todo-selection
12155 (not (eq org-use-fast-todo-selection
12156 'prefix)))))
12157 ;; Use fast selection
12158 (org-fast-todo-selection))
12159 ((and (equal arg '(4))
12160 (or (not org-use-fast-todo-selection)
12161 (not org-todo-key-trigger)))
12162 ;; Read a state with completion
12163 (org-icompleting-read
12164 "State: " (mapcar 'list org-todo-keywords-1)
12165 nil t))
12166 ((eq arg 'right)
12167 (if this
12168 (if tail (car tail) nil)
12169 (car org-todo-keywords-1)))
12170 ((eq arg 'left)
12171 (if (equal member org-todo-keywords-1)
12173 (if this
12174 (nth (- (length org-todo-keywords-1)
12175 (length tail) 2)
12176 org-todo-keywords-1)
12177 (org-last org-todo-keywords-1))))
12178 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12179 (setq arg nil))) ; hack to fall back to cycling
12180 (arg
12181 ;; user or caller requests a specific state
12182 (cond
12183 ((equal arg "") nil)
12184 ((eq arg 'none) nil)
12185 ((eq arg 'done) (or done-word (car org-done-keywords)))
12186 ((eq arg 'nextset)
12187 (or (car (cdr (member head org-todo-heads)))
12188 (car org-todo-heads)))
12189 ((eq arg 'previousset)
12190 (let ((org-todo-heads (reverse org-todo-heads)))
12191 (or (car (cdr (member head org-todo-heads)))
12192 (car org-todo-heads))))
12193 ((car (member arg org-todo-keywords-1)))
12194 ((stringp arg)
12195 (user-error "State `%s' not valid in this file" arg))
12196 ((nth (1- (prefix-numeric-value arg))
12197 org-todo-keywords-1))))
12198 ((null member) (or head (car org-todo-keywords-1)))
12199 ((equal this final-done-word) nil) ;; -> make empty
12200 ((null tail) nil) ;; -> first entry
12201 ((memq interpret '(type priority))
12202 (if (eq this-command last-command)
12203 (car tail)
12204 (if (> (length tail) 0)
12205 (or done-word (car org-done-keywords))
12206 nil)))
12208 (car tail))))
12209 (org-state (or
12210 (run-hook-with-args-until-success
12211 'org-todo-get-default-hook org-state org-last-state)
12212 org-state))
12213 (next (if org-state (concat " " org-state " ") " "))
12214 (change-plist (list :type 'todo-state-change :from this :to org-state
12215 :position startpos))
12216 dolog now-done-p)
12217 (when org-blocker-hook
12218 (setq org-last-todo-state-is-todo
12219 (not (member this org-done-keywords)))
12220 (unless (save-excursion
12221 (save-match-data
12222 (org-with-wide-buffer
12223 (run-hook-with-args-until-failure
12224 'org-blocker-hook change-plist))))
12225 (if (org-called-interactively-p 'interactive)
12226 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12227 this org-state org-block-entry-blocking)
12228 ;; fail silently
12229 (message "TODO state change from %s to %s blocked (by \"%s\")"
12230 this org-state org-block-entry-blocking)
12231 (throw 'exit nil))))
12232 (store-match-data match-data)
12233 (replace-match next t t)
12234 (unless (pos-visible-in-window-p hl-pos)
12235 (message "TODO state changed to %s" (org-trim next)))
12236 (unless head
12237 (setq head (org-get-todo-sequence-head org-state)
12238 ass (assoc head org-todo-kwd-alist)
12239 interpret (nth 1 ass)
12240 done-word (nth 3 ass)
12241 final-done-word (nth 4 ass)))
12242 (when (memq arg '(nextset previousset))
12243 (message "Keyword-Set %d/%d: %s"
12244 (- (length org-todo-sets) -1
12245 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12246 (length org-todo-sets)
12247 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12248 (setq org-last-todo-state-is-todo
12249 (not (member org-state org-done-keywords)))
12250 (setq now-done-p (and (member org-state org-done-keywords)
12251 (not (member this org-done-keywords))))
12252 (and logging (org-local-logging logging))
12253 (when (and (or org-todo-log-states org-log-done)
12254 (not (eq org-inhibit-logging t))
12255 (not (memq arg '(nextset previousset))))
12256 ;; we need to look at recording a time and note
12257 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12258 (nth 2 (assoc this org-todo-log-states))))
12259 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12260 (setq dolog 'time))
12261 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12262 (and org-state
12263 (member org-state org-not-done-keywords)
12264 (not (member this org-not-done-keywords))))
12265 ;; This is now a todo state and was not one before
12266 ;; If there was a CLOSED time stamp, get rid of it.
12267 (org-add-planning-info nil nil 'closed))
12268 (when (and now-done-p org-log-done)
12269 ;; It is now done, and it was not done before
12270 (org-add-planning-info 'closed (org-current-effective-time))
12271 (if (and (not dolog) (eq 'note org-log-done))
12272 (org-add-log-setup 'done org-state this 'findpos 'note)))
12273 (when (and org-state dolog)
12274 ;; This is a non-nil state, and we need to log it
12275 (org-add-log-setup 'state org-state this 'findpos dolog)))
12276 ;; Fixup tag positioning
12277 (org-todo-trigger-tag-changes org-state)
12278 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12279 (when org-provide-todo-statistics
12280 (org-update-parent-todo-statistics))
12281 (run-hooks 'org-after-todo-state-change-hook)
12282 (if (and arg (not (member org-state org-done-keywords)))
12283 (setq head (org-get-todo-sequence-head org-state)))
12284 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12285 ;; Do we need to trigger a repeat?
12286 (when now-done-p
12287 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12288 ;; This is for the agenda, take a snapshot of the headline.
12289 (save-match-data
12290 (setq org-agenda-headline-snapshot-before-repeat
12291 (org-get-heading))))
12292 (org-auto-repeat-maybe org-state))
12293 ;; Fixup cursor location if close to the keyword
12294 (if (and (outline-on-heading-p)
12295 (not (bolp))
12296 (save-excursion (beginning-of-line 1)
12297 (looking-at org-todo-line-regexp))
12298 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12299 (progn
12300 (goto-char (or (match-end 2) (match-end 1)))
12301 (and (looking-at " ") (just-one-space))))
12302 (when org-trigger-hook
12303 (save-excursion
12304 (run-hook-with-args 'org-trigger-hook change-plist)))
12305 (when commentp (org-toggle-comment))))))))
12307 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12308 "Block turning an entry into a TODO, using the hierarchy.
12309 This checks whether the current task should be blocked from state
12310 changes. Such blocking occurs when:
12312 1. The task has children which are not all in a completed state.
12314 2. A task has a parent with the property :ORDERED:, and there
12315 are siblings prior to the current task with incomplete
12316 status.
12318 3. The parent of the task is blocked because it has siblings that should
12319 be done first, or is child of a block grandparent TODO entry."
12321 (if (not org-enforce-todo-dependencies)
12322 t ; if locally turned off don't block
12323 (catch 'dont-block
12324 ;; If this is not a todo state change, or if this entry is already DONE,
12325 ;; do not block
12326 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12327 (member (plist-get change-plist :from)
12328 (cons 'done org-done-keywords))
12329 (member (plist-get change-plist :to)
12330 (cons 'todo org-not-done-keywords))
12331 (not (plist-get change-plist :to)))
12332 (throw 'dont-block t))
12333 ;; If this task has children, and any are undone, it's blocked
12334 (save-excursion
12335 (org-back-to-heading t)
12336 (let ((this-level (funcall outline-level)))
12337 (outline-next-heading)
12338 (let ((child-level (funcall outline-level)))
12339 (while (and (not (eobp))
12340 (> child-level this-level))
12341 ;; this todo has children, check whether they are all
12342 ;; completed
12343 (if (and (not (org-entry-is-done-p))
12344 (org-entry-is-todo-p))
12345 (progn (setq org-block-entry-blocking (org-get-heading))
12346 (throw 'dont-block nil)))
12347 (outline-next-heading)
12348 (setq child-level (funcall outline-level))))))
12349 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12350 ;; any previous siblings are undone, it's blocked
12351 (save-excursion
12352 (org-back-to-heading t)
12353 (let* ((pos (point))
12354 (parent-pos (and (org-up-heading-safe) (point))))
12355 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12356 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12357 (forward-line 1)
12358 (re-search-forward org-not-done-heading-regexp pos t))
12359 (setq org-block-entry-blocking (match-string 0))
12360 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12361 ;; Search further up the hierarchy, to see if an ancestor is blocked
12362 (while t
12363 (goto-char parent-pos)
12364 (if (not (looking-at org-not-done-heading-regexp))
12365 (throw 'dont-block t)) ; do not block, parent is not a TODO
12366 (setq pos (point))
12367 (setq parent-pos (and (org-up-heading-safe) (point)))
12368 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12369 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12370 (forward-line 1)
12371 (re-search-forward org-not-done-heading-regexp pos t)
12372 (setq org-block-entry-blocking (org-get-heading)))
12373 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12375 (defcustom org-track-ordered-property-with-tag nil
12376 "Should the ORDERED property also be shown as a tag?
12377 The ORDERED property decides if an entry should require subtasks to be
12378 completed in sequence. Since a property is not very visible, setting
12379 this option means that toggling the ORDERED property with the command
12380 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12381 not relevant for the behavior, but it makes things more visible.
12383 Note that toggling the tag with tags commands will not change the property
12384 and therefore not influence behavior!
12386 This can be t, meaning the tag ORDERED should be used, It can also be a
12387 string to select a different tag for this task."
12388 :group 'org-todo
12389 :type '(choice
12390 (const :tag "No tracking" nil)
12391 (const :tag "Track with ORDERED tag" t)
12392 (string :tag "Use other tag")))
12394 (defun org-toggle-ordered-property ()
12395 "Toggle the ORDERED property of the current entry.
12396 For better visibility, you can track the value of this property with a tag.
12397 See variable `org-track-ordered-property-with-tag'."
12398 (interactive)
12399 (let* ((t1 org-track-ordered-property-with-tag)
12400 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12401 (save-excursion
12402 (org-back-to-heading)
12403 (if (org-entry-get nil "ORDERED")
12404 (progn
12405 (org-delete-property "ORDERED" "PROPERTIES")
12406 (and tag (org-toggle-tag tag 'off))
12407 (message "Subtasks can be completed in arbitrary order"))
12408 (org-entry-put nil "ORDERED" "t")
12409 (and tag (org-toggle-tag tag 'on))
12410 (message "Subtasks must be completed in sequence")))))
12412 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12413 (defun org-block-todo-from-checkboxes (change-plist)
12414 "Block turning an entry into a TODO, using checkboxes.
12415 This checks whether the current task should be blocked from state
12416 changes because there are unchecked boxes in this entry."
12417 (if (not org-enforce-todo-checkbox-dependencies)
12418 t ; if locally turned off don't block
12419 (catch 'dont-block
12420 ;; If this is not a todo state change, or if this entry is already DONE,
12421 ;; do not block
12422 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12423 (member (plist-get change-plist :from)
12424 (cons 'done org-done-keywords))
12425 (member (plist-get change-plist :to)
12426 (cons 'todo org-not-done-keywords))
12427 (not (plist-get change-plist :to)))
12428 (throw 'dont-block t))
12429 ;; If this task has checkboxes that are not checked, it's blocked
12430 (save-excursion
12431 (org-back-to-heading t)
12432 (let ((beg (point)) end)
12433 (outline-next-heading)
12434 (setq end (point))
12435 (goto-char beg)
12436 (if (org-list-search-forward
12437 (concat (org-item-beginning-re)
12438 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12439 "\\[[- ]\\]")
12440 end t)
12441 (progn
12442 (if (boundp 'org-blocked-by-checkboxes)
12443 (setq org-blocked-by-checkboxes t))
12444 (throw 'dont-block nil)))))
12445 t))) ; do not block
12447 (defun org-entry-blocked-p ()
12448 "Is the current entry blocked?"
12449 (org-with-silent-modifications
12450 (if (org-entry-get nil "NOBLOCKING")
12451 nil ;; Never block this entry
12452 (not (run-hook-with-args-until-failure
12453 'org-blocker-hook
12454 (list :type 'todo-state-change
12455 :position (point)
12456 :from 'todo
12457 :to 'done))))))
12459 (defun org-update-statistics-cookies (all)
12460 "Update the statistics cookie, either from TODO or from checkboxes.
12461 This should be called with the cursor in a line with a statistics cookie."
12462 (interactive "P")
12463 (if all
12464 (progn
12465 (org-update-checkbox-count 'all)
12466 (org-map-entries 'org-update-parent-todo-statistics))
12467 (if (not (org-at-heading-p))
12468 (org-update-checkbox-count)
12469 (let ((pos (point-marker))
12470 end l1 l2)
12471 (ignore-errors (org-back-to-heading t))
12472 (if (not (org-at-heading-p))
12473 (org-update-checkbox-count)
12474 (setq l1 (org-outline-level))
12475 (setq end (save-excursion
12476 (outline-next-heading)
12477 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12478 (point)))
12479 (if (and (save-excursion
12480 (re-search-forward
12481 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12482 (not (save-excursion (re-search-forward
12483 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12484 (org-update-checkbox-count)
12485 (if (and l2 (> l2 l1))
12486 (progn
12487 (goto-char end)
12488 (org-update-parent-todo-statistics))
12489 (goto-char pos)
12490 (beginning-of-line 1)
12491 (while (re-search-forward
12492 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12493 (point-at-eol) t)
12494 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12495 (goto-char pos)
12496 (move-marker pos nil)))))
12498 (defvar org-entry-property-inherited-from) ;; defined below
12499 (defun org-update-parent-todo-statistics ()
12500 "Update any statistics cookie in the parent of the current headline.
12501 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12502 the entire subtree and this will travel up the hierarchy and update
12503 statistics everywhere."
12504 (let* ((prop (save-excursion (org-up-heading-safe)
12505 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12506 (recursive (or (not org-hierarchical-todo-statistics)
12507 (and prop (string-match "\\<recursive\\>" prop))))
12508 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12510 (first t)
12511 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12512 level ltoggle l1 new ndel
12513 (cnt-all 0) (cnt-done 0) is-percent kwd
12514 checkbox-beg ov ovs ove cookie-present)
12515 (catch 'exit
12516 (save-excursion
12517 (beginning-of-line 1)
12518 (setq ltoggle (funcall outline-level))
12519 ;; Three situations are to consider:
12521 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12522 ;; to the top-level ancestor on the headline;
12524 ;; 2. If parent has "recursive" property, repeat up to the
12525 ;; headline setting that property, taking inheritance into
12526 ;; account;
12528 ;; 3. Else, move up to direct parent and proceed only once.
12529 (while (and (setq level (org-up-heading-safe))
12530 (or recursive first)
12531 (>= (point) lim))
12532 (setq first nil cookie-present nil)
12533 (unless (and level
12534 (not (string-match
12535 "\\<checkbox\\>"
12536 (downcase (or (org-entry-get nil "COOKIE_DATA")
12537 "")))))
12538 (throw 'exit nil))
12539 (while (re-search-forward box-re (point-at-eol) t)
12540 (setq cnt-all 0 cnt-done 0 cookie-present t)
12541 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12542 (save-match-data
12543 (unless (outline-next-heading) (throw 'exit nil))
12544 (while (and (looking-at org-complex-heading-regexp)
12545 (> (setq l1 (length (match-string 1))) level))
12546 (setq kwd (and (or recursive (= l1 ltoggle))
12547 (match-string 2)))
12548 (if (or (eq org-provide-todo-statistics 'all-headlines)
12549 (and (listp org-provide-todo-statistics)
12550 (or (member kwd org-provide-todo-statistics)
12551 (member kwd org-done-keywords))))
12552 (setq cnt-all (1+ cnt-all))
12553 (if (eq org-provide-todo-statistics t)
12554 (and kwd (setq cnt-all (1+ cnt-all)))))
12555 (and (member kwd org-done-keywords)
12556 (setq cnt-done (1+ cnt-done)))
12557 (outline-next-heading)))
12558 (setq new
12559 (if is-percent
12560 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12561 (format "[%d/%d]" cnt-done cnt-all))
12562 ndel (- (match-end 0) checkbox-beg))
12563 ;; handle overlays when updating cookie from column view
12564 (when (setq ov (car (overlays-at checkbox-beg)))
12565 (setq ovs (overlay-start ov) ove (overlay-end ov))
12566 (delete-overlay ov))
12567 (goto-char checkbox-beg)
12568 (insert new)
12569 (delete-region (point) (+ (point) ndel))
12570 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12571 (when ov (move-overlay ov ovs ove)))
12572 (when cookie-present
12573 (run-hook-with-args 'org-after-todo-statistics-hook
12574 cnt-done (- cnt-all cnt-done))))))
12575 (run-hooks 'org-todo-statistics-hook)))
12577 (defvar org-after-todo-statistics-hook nil
12578 "Hook that is called after a TODO statistics cookie has been updated.
12579 Each function is called with two arguments: the number of not-done entries
12580 and the number of done entries.
12582 For example, the following function, when added to this hook, will switch
12583 an entry to DONE when all children are done, and back to TODO when new
12584 entries are set to a TODO status. Note that this hook is only called
12585 when there is a statistics cookie in the headline!
12587 (defun org-summary-todo (n-done n-not-done)
12588 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12589 (let (org-log-done org-log-states) ; turn off logging
12590 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12593 (defvar org-todo-statistics-hook nil
12594 "Hook that is run whenever Org thinks TODO statistics should be updated.
12595 This hook runs even if there is no statistics cookie present, in which case
12596 `org-after-todo-statistics-hook' would not run.")
12598 (defun org-todo-trigger-tag-changes (state)
12599 "Apply the changes defined in `org-todo-state-tags-triggers'."
12600 (let ((l org-todo-state-tags-triggers)
12601 changes)
12602 (when (or (not state) (equal state ""))
12603 (setq changes (append changes (cdr (assoc "" l)))))
12604 (when (and (stringp state) (> (length state) 0))
12605 (setq changes (append changes (cdr (assoc state l)))))
12606 (when (member state org-not-done-keywords)
12607 (setq changes (append changes (cdr (assoc 'todo l)))))
12608 (when (member state org-done-keywords)
12609 (setq changes (append changes (cdr (assoc 'done l)))))
12610 (dolist (c changes)
12611 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12613 (defun org-local-logging (value)
12614 "Get logging settings from a property VALUE."
12615 (let* (words w a)
12616 ;; directly set the variables, they are already local.
12617 (setq org-log-done nil
12618 org-log-repeat nil
12619 org-todo-log-states nil)
12620 (setq words (org-split-string value))
12621 (while (setq w (pop words))
12622 (cond
12623 ((setq a (assoc w org-startup-options))
12624 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12625 (set (nth 1 a) (nth 2 a))))
12626 ((setq a (org-extract-log-state-settings w))
12627 (and (member (car a) org-todo-keywords-1)
12628 (push a org-todo-log-states)))))))
12630 (defun org-get-todo-sequence-head (kwd)
12631 "Return the head of the TODO sequence to which KWD belongs.
12632 If KWD is not set, check if there is a text property remembering the
12633 right sequence."
12634 (let (p)
12635 (cond
12636 ((not kwd)
12637 (or (get-text-property (point-at-bol) 'org-todo-head)
12638 (progn
12639 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12640 nil (point-at-eol)))
12641 (get-text-property p 'org-todo-head))))
12642 ((not (member kwd org-todo-keywords-1))
12643 (car org-todo-keywords-1))
12644 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12646 (defun org-fast-todo-selection ()
12647 "Fast TODO keyword selection with single keys.
12648 Returns the new TODO keyword, or nil if no state change should occur."
12649 (let* ((fulltable org-todo-key-alist)
12650 (done-keywords org-done-keywords) ;; needed for the faces.
12651 (maxlen (apply 'max (mapcar
12652 (lambda (x)
12653 (if (stringp (car x)) (string-width (car x)) 0))
12654 fulltable)))
12655 (expert nil)
12656 (fwidth (+ maxlen 3 1 3))
12657 (ncol (/ (- (window-width) 4) fwidth))
12658 tg cnt e c tbl
12659 groups ingroup)
12660 (save-excursion
12661 (save-window-excursion
12662 (if expert
12663 (set-buffer (get-buffer-create " *Org todo*"))
12664 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12665 (erase-buffer)
12666 (org-set-local 'org-done-keywords done-keywords)
12667 (setq tbl fulltable cnt 0)
12668 (while (setq e (pop tbl))
12669 (cond
12670 ((equal e '(:startgroup))
12671 (push '() groups) (setq ingroup t)
12672 (when (not (= cnt 0))
12673 (setq cnt 0)
12674 (insert "\n"))
12675 (insert "{ "))
12676 ((equal e '(:endgroup))
12677 (setq ingroup nil cnt 0)
12678 (insert "}\n"))
12679 ((equal e '(:newline))
12680 (when (not (= cnt 0))
12681 (setq cnt 0)
12682 (insert "\n")
12683 (setq e (car tbl))
12684 (while (equal (car tbl) '(:newline))
12685 (insert "\n")
12686 (setq tbl (cdr tbl)))))
12688 (setq tg (car e) c (cdr e))
12689 (if ingroup (push tg (car groups)))
12690 (setq tg (org-add-props tg nil 'face
12691 (org-get-todo-face tg)))
12692 (if (and (= cnt 0) (not ingroup)) (insert " "))
12693 (insert "[" c "] " tg (make-string
12694 (- fwidth 4 (length tg)) ?\ ))
12695 (when (= (setq cnt (1+ cnt)) ncol)
12696 (insert "\n")
12697 (if ingroup (insert " "))
12698 (setq cnt 0)))))
12699 (insert "\n")
12700 (goto-char (point-min))
12701 (if (not expert) (org-fit-window-to-buffer))
12702 (message "[a-z..]:Set [SPC]:clear")
12703 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12704 (cond
12705 ((or (= c ?\C-g)
12706 (and (= c ?q) (not (rassoc c fulltable))))
12707 (setq quit-flag t))
12708 ((= c ?\ ) nil)
12709 ((setq e (rassoc c fulltable) tg (car e))
12711 (t (setq quit-flag t)))))))
12713 (defun org-entry-is-todo-p ()
12714 (member (org-get-todo-state) org-not-done-keywords))
12716 (defun org-entry-is-done-p ()
12717 (member (org-get-todo-state) org-done-keywords))
12719 (defun org-get-todo-state ()
12720 "Return the TODO keyword of the current subtree."
12721 (save-excursion
12722 (org-back-to-heading t)
12723 (and (looking-at org-todo-line-regexp)
12724 (match-end 2)
12725 (match-string 2))))
12727 (defun org-at-date-range-p (&optional inactive-ok)
12728 "Is the cursor inside a date range?"
12729 (interactive)
12730 (save-excursion
12731 (catch 'exit
12732 (let ((pos (point)))
12733 (skip-chars-backward "^[<\r\n")
12734 (skip-chars-backward "<[")
12735 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12736 (>= (match-end 0) pos)
12737 (throw 'exit t))
12738 (skip-chars-backward "^<[\r\n")
12739 (skip-chars-backward "<[")
12740 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12741 (>= (match-end 0) pos)
12742 (throw 'exit t)))
12743 nil)))
12745 (defun org-get-repeat (&optional tagline)
12746 "Check if there is a deadline/schedule with repeater in this entry."
12747 (save-match-data
12748 (save-excursion
12749 (org-back-to-heading t)
12750 (and (re-search-forward (if tagline
12751 (concat tagline "\\s-*" org-repeat-re)
12752 org-repeat-re)
12753 (org-entry-end-position) t)
12754 (match-string-no-properties 1)))))
12756 (defvar org-last-changed-timestamp)
12757 (defvar org-last-inserted-timestamp)
12758 (defvar org-log-post-message)
12759 (defvar org-log-note-purpose)
12760 (defvar org-log-note-how)
12761 (defvar org-log-note-extra)
12762 (defun org-auto-repeat-maybe (done-word)
12763 "Check if the current headline contains a repeated deadline/schedule.
12764 If yes, set TODO state back to what it was and change the base date
12765 of repeating deadline/scheduled time stamps to new date.
12766 This function is run automatically after each state change to a DONE state."
12767 ;; last-state is dynamically scoped into this function
12768 (let* ((repeat (org-get-repeat))
12769 (aa (assoc org-last-state org-todo-kwd-alist))
12770 (interpret (nth 1 aa))
12771 (head (nth 2 aa))
12772 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12773 (msg "Entry repeats: ")
12774 (org-log-done nil)
12775 (org-todo-log-states nil)
12776 re type n what ts time to-state)
12777 (when repeat
12778 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12779 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12780 org-todo-repeat-to-state))
12781 (unless (and to-state (member to-state org-todo-keywords-1))
12782 (setq to-state (if (eq interpret 'type) org-last-state head)))
12783 (org-todo to-state)
12784 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12785 (org-entry-put nil "LAST_REPEAT" (format-time-string
12786 (org-time-stamp-format t t))))
12787 (when org-log-repeat
12788 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12789 (memq 'org-add-log-note post-command-hook))
12790 ;; OK, we are already setup for some record
12791 (if (eq org-log-repeat 'note)
12792 ;; make sure we take a note, not only a time stamp
12793 (setq org-log-note-how 'note))
12794 ;; Set up for taking a record
12795 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12796 org-last-state
12797 'findpos org-log-repeat)))
12798 (org-back-to-heading t)
12799 (org-add-planning-info nil nil 'closed)
12800 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12801 org-deadline-time-regexp "\\)\\|\\("
12802 org-ts-regexp "\\)"))
12803 (while (re-search-forward
12804 re (save-excursion (outline-next-heading) (point)) t)
12805 (setq type (if (match-end 1) org-scheduled-string
12806 (if (match-end 3) org-deadline-string "Plain:"))
12807 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12808 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12809 (setq n (string-to-number (match-string 2 ts))
12810 what (match-string 3 ts))
12811 (if (equal what "w") (setq n (* n 7) what "d"))
12812 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12813 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12814 ;; Preparation, see if we need to modify the start date for the change
12815 (when (match-end 1)
12816 (setq time (save-match-data (org-time-string-to-time ts)))
12817 (cond
12818 ((equal (match-string 1 ts) ".")
12819 ;; Shift starting date to today
12820 (org-timestamp-change
12821 (- (org-today) (time-to-days time))
12822 'day))
12823 ((equal (match-string 1 ts) "+")
12824 (let ((nshiftmax 10) (nshift 0))
12825 (while (or (= nshift 0)
12826 (<= (time-to-days time)
12827 (time-to-days (current-time))))
12828 (when (= (incf nshift) nshiftmax)
12829 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12830 (error "Abort")))
12831 (org-timestamp-change n (cdr (assoc what whata)))
12832 (org-at-timestamp-p t)
12833 (setq ts (match-string 1))
12834 (setq time (save-match-data (org-time-string-to-time ts)))))
12835 (org-timestamp-change (- n) (cdr (assoc what whata)))
12836 ;; rematch, so that we have everything in place for the real shift
12837 (org-at-timestamp-p t)
12838 (setq ts (match-string 1))
12839 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12840 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12841 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12842 (setq org-log-post-message msg)
12843 (message "%s" msg))))
12845 (defun org-show-todo-tree (arg)
12846 "Make a compact tree which shows all headlines marked with TODO.
12847 The tree will show the lines where the regexp matches, and all higher
12848 headlines above the match.
12849 With a \\[universal-argument] prefix, prompt for a regexp to match.
12850 With a numeric prefix N, construct a sparse tree for the Nth element
12851 of `org-todo-keywords-1'."
12852 (interactive "P")
12853 (let ((case-fold-search nil)
12854 (kwd-re
12855 (cond ((null arg) org-not-done-regexp)
12856 ((equal arg '(4))
12857 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12858 (mapcar 'list org-todo-keywords-1))))
12859 (concat "\\("
12860 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12861 "\\)\\>")))
12862 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12863 (regexp-quote (nth (1- (prefix-numeric-value arg))
12864 org-todo-keywords-1)))
12865 (t (user-error "Invalid prefix argument: %s" arg)))))
12866 (message "%d TODO entries found"
12867 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12869 (defun org-deadline (arg &optional time)
12870 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12871 With one universal prefix argument, remove any deadline from the item.
12872 With two universal prefix arguments, prompt for a warning delay.
12873 With argument TIME, set the deadline at the corresponding date. TIME
12874 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12875 (interactive "P")
12876 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12877 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12878 'region-start-level 'region))
12879 org-loop-over-headlines-in-active-region)
12880 (org-map-entries
12881 `(org-deadline ',arg ,time)
12882 org-loop-over-headlines-in-active-region
12883 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12884 (let* ((old-date (org-entry-get nil "DEADLINE"))
12885 (old-date-time (if old-date (org-time-string-to-time old-date)))
12886 (repeater (and old-date
12887 (string-match
12888 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12889 old-date)
12890 (match-string 1 old-date))))
12891 (cond
12892 ((equal arg '(4))
12893 (when (and old-date org-log-redeadline)
12894 (org-add-log-setup 'deldeadline nil old-date 'findpos
12895 org-log-redeadline))
12896 (org-remove-timestamp-with-keyword org-deadline-string)
12897 (message "Item no longer has a deadline."))
12898 ((equal arg '(16))
12899 (save-excursion
12900 (if (re-search-forward
12901 org-deadline-time-regexp
12902 (save-excursion (outline-next-heading) (point)) t)
12903 (let* ((rpl0 (match-string 1))
12904 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12905 (replace-match
12906 (concat org-deadline-string
12907 " <" rpl
12908 (format " -%dd"
12909 (abs
12910 (- (time-to-days
12911 (save-match-data
12912 (org-read-date nil t nil "Warn starting from" old-date-time)))
12913 (time-to-days old-date-time))))
12914 ">") t t))
12915 (user-error "No deadline information to update"))))
12917 (org-add-planning-info 'deadline time 'closed)
12918 (when (and old-date org-log-redeadline
12919 (not (equal old-date
12920 (substring org-last-inserted-timestamp 1 -1))))
12921 (org-add-log-setup 'redeadline nil old-date 'findpos
12922 org-log-redeadline))
12923 (when repeater
12924 (save-excursion
12925 (org-back-to-heading t)
12926 (when (re-search-forward (concat org-deadline-string " "
12927 org-last-inserted-timestamp)
12928 (save-excursion
12929 (outline-next-heading) (point)) t)
12930 (goto-char (1- (match-end 0)))
12931 (insert " " repeater)
12932 (setq org-last-inserted-timestamp
12933 (concat (substring org-last-inserted-timestamp 0 -1)
12934 " " repeater
12935 (substring org-last-inserted-timestamp -1))))))
12936 (message "Deadline on %s" org-last-inserted-timestamp))))))
12938 (defun org-schedule (arg &optional time)
12939 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12940 With one universal prefix argument, remove any scheduling date from the item.
12941 With two universal prefix arguments, prompt for a delay cookie.
12942 With argument TIME, scheduled at the corresponding date. TIME can
12943 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12944 (interactive "P")
12945 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12946 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12947 'region-start-level 'region))
12948 org-loop-over-headlines-in-active-region)
12949 (org-map-entries
12950 `(org-schedule ',arg ,time)
12951 org-loop-over-headlines-in-active-region
12952 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12953 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12954 (old-date-time (if old-date (org-time-string-to-time old-date)))
12955 (repeater (and old-date
12956 (string-match
12957 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12958 old-date)
12959 (match-string 1 old-date))))
12960 (cond
12961 ((equal arg '(4))
12962 (progn
12963 (when (and old-date org-log-reschedule)
12964 (org-add-log-setup 'delschedule nil old-date 'findpos
12965 org-log-reschedule))
12966 (org-remove-timestamp-with-keyword org-scheduled-string)
12967 (message "Item is no longer scheduled.")))
12968 ((equal arg '(16))
12969 (save-excursion
12970 (if (re-search-forward
12971 org-scheduled-time-regexp
12972 (save-excursion (outline-next-heading) (point)) t)
12973 (let* ((rpl0 (match-string 1))
12974 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12975 (replace-match
12976 (concat org-scheduled-string
12977 " <" rpl
12978 (format " -%dd"
12979 (abs
12980 (- (time-to-days
12981 (save-match-data
12982 (org-read-date nil t nil "Delay until" old-date-time)))
12983 (time-to-days old-date-time))))
12984 ">") t t))
12985 (user-error "No scheduled information to update"))))
12987 (org-add-planning-info 'scheduled time 'closed)
12988 (when (and old-date org-log-reschedule
12989 (not (equal old-date
12990 (substring org-last-inserted-timestamp 1 -1))))
12991 (org-add-log-setup 'reschedule nil old-date 'findpos
12992 org-log-reschedule))
12993 (when repeater
12994 (save-excursion
12995 (org-back-to-heading t)
12996 (when (re-search-forward (concat org-scheduled-string " "
12997 org-last-inserted-timestamp)
12998 (save-excursion
12999 (outline-next-heading) (point)) t)
13000 (goto-char (1- (match-end 0)))
13001 (insert " " repeater)
13002 (setq org-last-inserted-timestamp
13003 (concat (substring org-last-inserted-timestamp 0 -1)
13004 " " repeater
13005 (substring org-last-inserted-timestamp -1))))))
13006 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13008 (defun org-get-scheduled-time (pom &optional inherit)
13009 "Get the scheduled time as a time tuple, of a format suitable
13010 for calling org-schedule with, or if there is no scheduling,
13011 returns nil."
13012 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13013 (when time
13014 (apply 'encode-time (org-parse-time-string time)))))
13016 (defun org-get-deadline-time (pom &optional inherit)
13017 "Get the deadline as a time tuple, of a format suitable for
13018 calling org-deadline with, or if there is no scheduling, returns
13019 nil."
13020 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13021 (when time
13022 (apply 'encode-time (org-parse-time-string time)))))
13024 (defun org-remove-timestamp-with-keyword (keyword)
13025 "Remove all time stamps with KEYWORD in the current entry."
13026 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13027 beg)
13028 (save-excursion
13029 (org-back-to-heading t)
13030 (setq beg (point))
13031 (outline-next-heading)
13032 (while (re-search-backward re beg t)
13033 (replace-match "")
13034 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13035 (equal (char-before) ?\ ))
13036 (backward-delete-char 1)
13037 (if (string-match "^[ \t]*$" (buffer-substring
13038 (point-at-bol) (point-at-eol)))
13039 (delete-region (point-at-bol)
13040 (min (point-max) (1+ (point-at-eol))))))))))
13042 (defun org-add-planning-info (what &optional time &rest remove)
13043 "Insert new timestamp with keyword in the line directly after the headline.
13044 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13045 If non is given, the user is prompted for a date.
13046 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13047 be removed."
13048 (interactive)
13049 (let (org-time-was-given org-end-time-was-given ts
13050 end default-time default-input)
13052 (catch 'exit
13053 (when (and (memq what '(scheduled deadline))
13054 (or (not time)
13055 (and (stringp time)
13056 (string-match "^[-+]+[0-9]" time))))
13057 ;; Try to get a default date/time from existing timestamp
13058 (save-excursion
13059 (org-back-to-heading t)
13060 (setq end (save-excursion (outline-next-heading) (point)))
13061 (when (re-search-forward (if (eq what 'scheduled)
13062 org-scheduled-time-regexp
13063 org-deadline-time-regexp)
13064 end t)
13065 (setq ts (match-string 1)
13066 default-time
13067 (apply 'encode-time (org-parse-time-string ts))
13068 default-input (and ts (org-get-compact-tod ts))))))
13069 (when what
13070 (setq time
13071 (if (stringp time)
13072 ;; This is a string (relative or absolute), set proper date
13073 (apply 'encode-time
13074 (org-read-date-analyze
13075 time default-time (decode-time default-time)))
13076 ;; If necessary, get the time from the user
13077 (or time (org-read-date nil 'to-time nil nil
13078 default-time default-input)))))
13080 (when (and org-insert-labeled-timestamps-at-point
13081 (member what '(scheduled deadline)))
13082 (insert
13083 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13084 (org-insert-time-stamp time org-time-was-given
13085 nil nil nil (list org-end-time-was-given))
13086 (setq what nil))
13087 (save-excursion
13088 (save-restriction
13089 (let (col list elt ts buffer-invisibility-spec)
13090 (org-back-to-heading t)
13091 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13092 (goto-char (match-end 1))
13093 (setq col (current-column))
13094 (goto-char (match-end 0))
13095 (if (eobp) (insert "\n") (forward-char 1))
13096 (when (and (not what)
13097 (not (looking-at
13098 (concat "[ \t]*"
13099 org-keyword-time-not-clock-regexp))))
13100 ;; Nothing to add, nothing to remove...... :-)
13101 (throw 'exit nil))
13102 (if (and (not (looking-at org-outline-regexp))
13103 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13104 "[^\r\n]*"))
13105 (not (equal (match-string 1) org-clock-string)))
13106 (narrow-to-region (match-beginning 0) (match-end 0))
13107 (insert-before-markers "\n")
13108 (backward-char 1)
13109 (narrow-to-region (point) (point))
13110 (and org-adapt-indentation (org-indent-to-column col)))
13111 ;; Check if we have to remove something.
13112 (setq list (cons what remove))
13113 (while list
13114 (setq elt (pop list))
13115 (when (or (and (eq elt 'scheduled)
13116 (re-search-forward org-scheduled-time-regexp nil t))
13117 (and (eq elt 'deadline)
13118 (re-search-forward org-deadline-time-regexp nil t))
13119 (and (eq elt 'closed)
13120 (re-search-forward org-closed-time-regexp nil t)))
13121 (replace-match "")
13122 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13123 (and (looking-at "[ \t]+") (replace-match ""))
13124 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13125 (when what
13126 (insert
13127 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13128 (cond ((eq what 'scheduled) org-scheduled-string)
13129 ((eq what 'deadline) org-deadline-string)
13130 ((eq what 'closed) org-closed-string))
13131 " ")
13132 (setq ts (org-insert-time-stamp
13133 time
13134 (or org-time-was-given
13135 (and (eq what 'closed) org-log-done-with-time))
13136 (eq what 'closed)
13137 nil nil (list org-end-time-was-given)))
13138 (insert
13139 (if (not (or (bolp) (eq (char-before) ?\ )
13140 (memq (char-after) '(32 10))
13141 (eobp))) " " ""))
13142 (end-of-line 1))
13143 (goto-char (point-min))
13144 (widen)
13145 (if (and (looking-at "[ \t]*\n")
13146 (equal (char-before) ?\n))
13147 (delete-region (1- (point)) (point-at-eol)))
13148 ts))))))
13150 (defvar org-log-note-marker (make-marker))
13151 (defvar org-log-note-purpose nil)
13152 (defvar org-log-note-state nil)
13153 (defvar org-log-note-previous-state nil)
13154 (defvar org-log-note-how nil)
13155 (defvar org-log-note-extra nil)
13156 (defvar org-log-note-window-configuration nil)
13157 (defvar org-log-note-return-to (make-marker))
13158 (defvar org-log-note-effective-time nil
13159 "Remembered current time so that dynamically scoped
13160 `org-extend-today-until' affects tha timestamps in state change
13161 log")
13163 (defvar org-log-post-message nil
13164 "Message to be displayed after a log note has been stored.
13165 The auto-repeater uses this.")
13167 (defun org-add-note ()
13168 "Add a note to the current entry.
13169 This is done in the same way as adding a state change note."
13170 (interactive)
13171 (org-add-log-setup 'note nil nil 'findpos nil))
13173 (defvar org-property-end-re)
13174 (defun org-add-log-setup (&optional purpose state prev-state
13175 findpos how extra)
13176 "Set up the post command hook to take a note.
13177 If this is about to TODO state change, the new state is expected in STATE.
13178 When FINDPOS is non-nil, find the correct position for the note in
13179 the current entry. If not, assume that it can be inserted at point.
13180 HOW is an indicator what kind of note should be created.
13181 EXTRA is additional text that will be inserted into the notes buffer."
13182 (let* ((org-log-into-drawer (org-log-into-drawer))
13183 (drawer (cond ((stringp org-log-into-drawer)
13184 org-log-into-drawer)
13185 (org-log-into-drawer "LOGBOOK"))))
13186 (save-restriction
13187 (save-excursion
13188 (when findpos
13189 (org-back-to-heading t)
13190 (narrow-to-region (point) (save-excursion
13191 (outline-next-heading) (point)))
13192 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13193 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13194 "[^\r\n]*\\)?"))
13195 (goto-char (match-end 0))
13196 (cond
13197 (drawer
13198 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13199 nil t)
13200 (progn
13201 (goto-char (match-end 0))
13202 (or org-log-states-order-reversed
13203 (and (re-search-forward org-property-end-re nil t)
13204 (goto-char (1- (match-beginning 0))))))
13205 (insert "\n:" drawer ":\n:END:")
13206 (beginning-of-line 0)
13207 (org-indent-line)
13208 (beginning-of-line 2)
13209 (org-indent-line)
13210 (end-of-line 0)))
13211 ((and org-log-state-notes-insert-after-drawers
13212 (save-excursion
13213 (forward-line) (looking-at org-drawer-regexp)))
13214 (forward-line)
13215 (while (looking-at org-drawer-regexp)
13216 (goto-char (match-end 0))
13217 (re-search-forward org-property-end-re (point-max) t)
13218 (forward-line))
13219 (forward-line -1)))
13220 (unless org-log-states-order-reversed
13221 (and (= (char-after) ?\n) (forward-char 1))
13222 (org-skip-over-state-notes)
13223 (skip-chars-backward " \t\n\r")))
13224 (move-marker org-log-note-marker (point))
13225 (setq org-log-note-purpose purpose
13226 org-log-note-state state
13227 org-log-note-previous-state prev-state
13228 org-log-note-how how
13229 org-log-note-extra extra
13230 org-log-note-effective-time (org-current-effective-time))
13231 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13233 (defun org-skip-over-state-notes ()
13234 "Skip past the list of State notes in an entry."
13235 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13236 (when (ignore-errors (goto-char (org-in-item-p)))
13237 (let* ((struct (org-list-struct))
13238 (prevs (org-list-prevs-alist struct)))
13239 (while (looking-at "[ \t]*- State")
13240 (goto-char (or (org-list-get-next-item (point) struct prevs)
13241 (org-list-get-item-end (point) struct)))))))
13243 (defun org-add-log-note (&optional purpose)
13244 "Pop up a window for taking a note, and add this note later at point."
13245 (remove-hook 'post-command-hook 'org-add-log-note)
13246 (setq org-log-note-window-configuration (current-window-configuration))
13247 (delete-other-windows)
13248 (move-marker org-log-note-return-to (point))
13249 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13250 (goto-char org-log-note-marker)
13251 (org-switch-to-buffer-other-window "*Org Note*")
13252 (erase-buffer)
13253 (if (memq org-log-note-how '(time state))
13254 (let (current-prefix-arg) (org-store-log-note))
13255 (let ((org-inhibit-startup t)) (org-mode))
13256 (insert (format "# Insert note for %s.
13257 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13258 (cond
13259 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13260 ((eq org-log-note-purpose 'done) "closed todo item")
13261 ((eq org-log-note-purpose 'state)
13262 (format "state change from \"%s\" to \"%s\""
13263 (or org-log-note-previous-state "")
13264 (or org-log-note-state "")))
13265 ((eq org-log-note-purpose 'reschedule)
13266 "rescheduling")
13267 ((eq org-log-note-purpose 'delschedule)
13268 "no longer scheduled")
13269 ((eq org-log-note-purpose 'redeadline)
13270 "changing deadline")
13271 ((eq org-log-note-purpose 'deldeadline)
13272 "removing deadline")
13273 ((eq org-log-note-purpose 'refile)
13274 "refiling")
13275 ((eq org-log-note-purpose 'note)
13276 "this entry")
13277 (t (error "This should not happen")))))
13278 (if org-log-note-extra (insert org-log-note-extra))
13279 (org-set-local 'org-finish-function 'org-store-log-note)
13280 (run-hooks 'org-log-buffer-setup-hook)))
13282 (defvar org-note-abort nil) ; dynamically scoped
13283 (defun org-store-log-note ()
13284 "Finish taking a log note, and insert it to where it belongs."
13285 (let ((txt (buffer-string)))
13286 (kill-buffer (current-buffer))
13287 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13288 lines ind bul)
13289 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13290 (setq txt (replace-match "" t t txt)))
13291 (if (string-match "\\s-+\\'" txt)
13292 (setq txt (replace-match "" t t txt)))
13293 (setq lines (org-split-string txt "\n"))
13294 (when (and note (string-match "\\S-" note))
13295 (setq note
13296 (org-replace-escapes
13297 note
13298 (list (cons "%u" (user-login-name))
13299 (cons "%U" user-full-name)
13300 (cons "%t" (format-time-string
13301 (org-time-stamp-format 'long 'inactive)
13302 org-log-note-effective-time))
13303 (cons "%T" (format-time-string
13304 (org-time-stamp-format 'long nil)
13305 org-log-note-effective-time))
13306 (cons "%d" (format-time-string
13307 (org-time-stamp-format nil 'inactive)
13308 org-log-note-effective-time))
13309 (cons "%D" (format-time-string
13310 (org-time-stamp-format nil nil)
13311 org-log-note-effective-time))
13312 (cons "%s" (if org-log-note-state
13313 (concat "\"" org-log-note-state "\"")
13314 ""))
13315 (cons "%S" (if org-log-note-previous-state
13316 (concat "\"" org-log-note-previous-state "\"")
13317 "\"\"")))))
13318 (if lines (setq note (concat note " \\\\")))
13319 (push note lines))
13320 (when (or current-prefix-arg org-note-abort)
13321 (when org-log-into-drawer
13322 (org-remove-empty-drawer-at
13323 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
13324 org-log-note-marker))
13325 (setq lines nil))
13326 (when lines
13327 (with-current-buffer (marker-buffer org-log-note-marker)
13328 (save-excursion
13329 (goto-char org-log-note-marker)
13330 (move-marker org-log-note-marker nil)
13331 (end-of-line 1)
13332 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13333 (setq ind (save-excursion
13334 (if (ignore-errors (goto-char (org-in-item-p)))
13335 (let ((struct (org-list-struct)))
13336 (org-list-get-ind
13337 (org-list-get-top-point struct) struct))
13338 (skip-chars-backward " \r\t\n")
13339 (cond
13340 ((and (org-at-heading-p)
13341 org-adapt-indentation)
13342 (1+ (org-current-level)))
13343 ((org-at-heading-p) 0)
13344 (t (org-get-indentation))))))
13345 (setq bul (org-list-bullet-string "-"))
13346 (org-indent-line-to ind)
13347 (insert bul (pop lines))
13348 (let ((ind-body (+ (length bul) ind)))
13349 (while lines
13350 (insert "\n")
13351 (org-indent-line-to ind-body)
13352 (insert (pop lines))))
13353 (message "Note stored")
13354 (org-back-to-heading t)
13355 (org-cycle-hide-drawers 'children))
13356 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13357 ;; from within `org-add-log-note' because `buffer-undo-list'
13358 ;; is then modified outside of `org-with-remote-undo'.
13359 (when (eq this-command 'org-agenda-todo)
13360 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13361 ;; Don't add undo information when called from `org-agenda-todo'
13362 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13363 (set-window-configuration org-log-note-window-configuration)
13364 (with-current-buffer (marker-buffer org-log-note-return-to)
13365 (goto-char org-log-note-return-to))
13366 (move-marker org-log-note-return-to nil)
13367 (and org-log-post-message (message "%s" org-log-post-message))))
13369 (defun org-remove-empty-drawer-at (drawer pos)
13370 "Remove an empty drawer DRAWER at position POS.
13371 POS may also be a marker."
13372 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13373 (save-excursion
13374 (save-restriction
13375 (widen)
13376 (goto-char pos)
13377 (if (org-in-regexp
13378 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13379 (replace-match ""))))))
13381 (defvar org-ts-type nil)
13382 (defun org-sparse-tree (&optional arg type)
13383 "Create a sparse tree, prompt for the details.
13384 This command can create sparse trees. You first need to select the type
13385 of match used to create the tree:
13387 t Show all TODO entries.
13388 T Show entries with a specific TODO keyword.
13389 m Show entries selected by a tags/property match.
13390 p Enter a property name and its value (both with completion on existing
13391 names/values) and show entries with that property.
13392 r Show entries matching a regular expression (`/' can be used as well).
13393 b Show deadlines and scheduled items before a date.
13394 a Show deadlines and scheduled items after a date.
13395 d Show deadlines due within `org-deadline-warning-days'.
13396 D Show deadlines and scheduled items between a date range."
13397 (interactive "P")
13398 (let (ans kwd value ts-type)
13399 (setq type (or type org-sparse-tree-default-date-type))
13400 (setq org-ts-type type)
13401 (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"
13402 (cond ((eq type 'all) "all timestamps")
13403 ((eq type 'scheduled) "only scheduled")
13404 ((eq type 'deadline) "only deadline")
13405 ((eq type 'active) "only active timestamps")
13406 ((eq type 'inactive) "only inactive timestamps")
13407 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13408 ((eq type 'closed) "with a closed time-stamp")
13409 (t "scheduled/deadline")))
13410 (setq ans (read-char-exclusive))
13411 (cond
13412 ((equal ans ?c)
13413 (org-sparse-tree
13414 arg (cadr (member type '(scheduled-or-deadline
13415 all scheduled deadline active inactive closed)))))
13416 ((equal ans ?d)
13417 (call-interactively 'org-check-deadlines))
13418 ((equal ans ?b)
13419 (call-interactively 'org-check-before-date))
13420 ((equal ans ?a)
13421 (call-interactively 'org-check-after-date))
13422 ((equal ans ?D)
13423 (call-interactively 'org-check-dates-range))
13424 ((equal ans ?t)
13425 (call-interactively 'org-show-todo-tree))
13426 ((equal ans ?T)
13427 (org-show-todo-tree '(4)))
13428 ((member ans '(?T ?m))
13429 (call-interactively 'org-match-sparse-tree))
13430 ((member ans '(?p ?P))
13431 (setq kwd (org-icompleting-read "Property: "
13432 (mapcar 'list (org-buffer-property-keys))))
13433 (setq value (org-icompleting-read "Value: "
13434 (mapcar 'list (org-property-values kwd))))
13435 (unless (string-match "\\`{.*}\\'" value)
13436 (setq value (concat "\"" value "\"")))
13437 (org-match-sparse-tree arg (concat kwd "=" value)))
13438 ((member ans '(?r ?R ?/))
13439 (call-interactively 'org-occur))
13440 (t (user-error "No such sparse tree command \"%c\"" ans)))))
13442 (defvar org-occur-highlights nil
13443 "List of overlays used for occur matches.")
13444 (make-variable-buffer-local 'org-occur-highlights)
13445 (defvar org-occur-parameters nil
13446 "Parameters of the active org-occur calls.
13447 This is a list, each call to org-occur pushes as cons cell,
13448 containing the regular expression and the callback, onto the list.
13449 The list can contain several entries if `org-occur' has been called
13450 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13451 will only contain one set of parameters. When the highlights are
13452 removed (for example with `C-c C-c', or with the next edit (depending
13453 on `org-remove-highlights-with-change'), this variable is emptied
13454 as well.")
13455 (make-variable-buffer-local 'org-occur-parameters)
13457 (defun org-occur (regexp &optional keep-previous callback)
13458 "Make a compact tree which shows all matches of REGEXP.
13459 The tree will show the lines where the regexp matches, and all higher
13460 headlines above the match. It will also show the heading after the match,
13461 to make sure editing the matching entry is easy.
13462 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13463 call to `org-occur' will be kept, to allow stacking of calls to this
13464 command.
13465 If CALLBACK is non-nil, it is a function which is called to confirm
13466 that the match should indeed be shown."
13467 (interactive "sRegexp: \nP")
13468 (when (equal regexp "")
13469 (user-error "Regexp cannot be empty"))
13470 (unless keep-previous
13471 (org-remove-occur-highlights nil nil t))
13472 (push (cons regexp callback) org-occur-parameters)
13473 (let ((cnt 0))
13474 (save-excursion
13475 (goto-char (point-min))
13476 (if (or (not keep-previous) ; do not want to keep
13477 (not org-occur-highlights)) ; no previous matches
13478 ;; hide everything
13479 (org-overview))
13480 (while (re-search-forward regexp nil t)
13481 (when (or (not callback)
13482 (save-match-data (funcall callback)))
13483 (setq cnt (1+ cnt))
13484 (when org-highlight-sparse-tree-matches
13485 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13486 (org-show-context 'occur-tree))))
13487 (when org-remove-highlights-with-change
13488 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13489 nil 'local))
13490 (unless org-sparse-tree-open-archived-trees
13491 (org-hide-archived-subtrees (point-min) (point-max)))
13492 (run-hooks 'org-occur-hook)
13493 (if (org-called-interactively-p 'interactive)
13494 (message "%d match(es) for regexp %s" cnt regexp))
13495 cnt))
13497 (defun org-occur-next-match (&optional n reset)
13498 "Function for `next-error-function' to find sparse tree matches.
13499 N is the number of matches to move, when negative move backwards.
13500 RESET is entirely ignored - this function always goes back to the
13501 starting point when no match is found."
13502 (let* ((limit (if (< n 0) (point-min) (point-max)))
13503 (search-func (if (< n 0)
13504 'previous-single-char-property-change
13505 'next-single-char-property-change))
13506 (n (abs n))
13507 (pos (point))
13509 (catch 'exit
13510 (while (setq p1 (funcall search-func (point) 'org-type))
13511 (when (equal p1 limit)
13512 (goto-char pos)
13513 (error "No more matches"))
13514 (when (equal (get-char-property p1 'org-type) 'org-occur)
13515 (setq n (1- n))
13516 (when (= n 0)
13517 (goto-char p1)
13518 (throw 'exit (point))))
13519 (goto-char p1))
13520 (goto-char p1)
13521 (error "No more matches"))))
13523 (defun org-show-context (&optional key)
13524 "Make sure point and context are visible.
13525 How much context is shown depends upon the variables
13526 `org-show-hierarchy-above', `org-show-following-heading',
13527 `org-show-entry-below' and `org-show-siblings'."
13528 (let ((heading-p (org-at-heading-p t))
13529 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13530 (following-p (org-get-alist-option org-show-following-heading key))
13531 (entry-p (org-get-alist-option org-show-entry-below key))
13532 (siblings-p (org-get-alist-option org-show-siblings key)))
13533 ;; Show heading or entry text
13534 (if (and heading-p (not entry-p))
13535 (org-flag-heading nil) ; only show the heading
13536 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13537 (org-show-hidden-entry))) ; show entire entry
13538 (when following-p
13539 ;; Show next sibling, or heading below text
13540 (save-excursion
13541 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13542 (org-flag-heading nil))))
13543 (when siblings-p (org-show-siblings))
13544 (when hierarchy-p
13545 ;; show all higher headings, possibly with siblings
13546 (save-excursion
13547 (while (and (condition-case nil
13548 (progn (org-up-heading-all 1) t)
13549 (error nil))
13550 (not (bobp)))
13551 (org-flag-heading nil)
13552 (when siblings-p (org-show-siblings)))))
13553 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13555 (defvar org-reveal-start-hook nil
13556 "Hook run before revealing a location.")
13558 (defun org-reveal (&optional siblings)
13559 "Show current entry, hierarchy above it, and the following headline.
13560 This can be used to show a consistent set of context around locations
13561 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13562 not t for the search context.
13564 With optional argument SIBLINGS, on each level of the hierarchy all
13565 siblings are shown. This repairs the tree structure to what it would
13566 look like when opened with hierarchical calls to `org-cycle'.
13567 With double optional argument \\[universal-argument] \\[universal-argument], \
13568 go to the parent and show the
13569 entire tree."
13570 (interactive "P")
13571 (run-hooks 'org-reveal-start-hook)
13572 (let ((org-show-hierarchy-above t)
13573 (org-show-following-heading t)
13574 (org-show-siblings (if siblings t org-show-siblings)))
13575 (org-show-context nil))
13576 (when (equal siblings '(16))
13577 (save-excursion
13578 (when (org-up-heading-safe)
13579 (org-show-subtree)
13580 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13582 (defun org-highlight-new-match (beg end)
13583 "Highlight from BEG to END and mark the highlight is an occur headline."
13584 (let ((ov (make-overlay beg end)))
13585 (overlay-put ov 'face 'secondary-selection)
13586 (overlay-put ov 'org-type 'org-occur)
13587 (push ov org-occur-highlights)))
13589 (defun org-remove-occur-highlights (&optional beg end noremove)
13590 "Remove the occur highlights from the buffer.
13591 BEG and END are ignored. If NOREMOVE is nil, remove this function
13592 from the `before-change-functions' in the current buffer."
13593 (interactive)
13594 (unless org-inhibit-highlight-removal
13595 (mapc 'delete-overlay org-occur-highlights)
13596 (setq org-occur-highlights nil)
13597 (setq org-occur-parameters nil)
13598 (unless noremove
13599 (remove-hook 'before-change-functions
13600 'org-remove-occur-highlights 'local))))
13602 ;;;; Priorities
13604 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13605 "Regular expression matching the priority indicator.")
13607 (defvar org-remove-priority-next-time nil)
13609 (defun org-priority-up ()
13610 "Increase the priority of the current item."
13611 (interactive)
13612 (org-priority 'up))
13614 (defun org-priority-down ()
13615 "Decrease the priority of the current item."
13616 (interactive)
13617 (org-priority 'down))
13619 (defun org-priority (&optional action show)
13620 "Change the priority of an item.
13621 ACTION can be `set', `up', `down', or a character."
13622 (interactive "P")
13623 (if (equal action '(4))
13624 (org-show-priority)
13625 (unless org-enable-priority-commands
13626 (user-error "Priority commands are disabled"))
13627 (setq action (or action 'set))
13628 (let (current new news have remove)
13629 (save-excursion
13630 (org-back-to-heading t)
13631 (if (looking-at org-priority-regexp)
13632 (setq current (string-to-char (match-string 2))
13633 have t))
13634 (cond
13635 ((eq action 'remove)
13636 (setq remove t new ?\ ))
13637 ((or (eq action 'set)
13638 (if (featurep 'xemacs) (characterp action) (integerp action)))
13639 (if (not (eq action 'set))
13640 (setq new action)
13641 (message "Priority %c-%c, SPC to remove: "
13642 org-highest-priority org-lowest-priority)
13643 (save-match-data
13644 (setq new (read-char-exclusive))))
13645 (if (and (= (upcase org-highest-priority) org-highest-priority)
13646 (= (upcase org-lowest-priority) org-lowest-priority))
13647 (setq new (upcase new)))
13648 (cond ((equal new ?\ ) (setq remove t))
13649 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13650 (user-error "Priority must be between `%c' and `%c'"
13651 org-highest-priority org-lowest-priority))))
13652 ((eq action 'up)
13653 (setq new (if have
13654 (1- current) ; normal cycling
13655 ;; last priority was empty
13656 (if (eq last-command this-command)
13657 org-lowest-priority ; wrap around empty to lowest
13658 ;; default
13659 (if org-priority-start-cycle-with-default
13660 org-default-priority
13661 (1- org-default-priority))))))
13662 ((eq action 'down)
13663 (setq new (if have
13664 (1+ current) ; normal cycling
13665 ;; last priority was empty
13666 (if (eq last-command this-command)
13667 org-highest-priority ; wrap around empty to highest
13668 ;; default
13669 (if org-priority-start-cycle-with-default
13670 org-default-priority
13671 (1+ org-default-priority))))))
13672 (t (user-error "Invalid action")))
13673 (if (or (< (upcase new) org-highest-priority)
13674 (> (upcase new) org-lowest-priority))
13675 (if (and (memq action '(up down))
13676 (not have) (not (eq last-command this-command)))
13677 ;; `new' is from default priority
13678 (error
13679 "The default can not be set, see `org-default-priority' why")
13680 ;; normal cycling: `new' is beyond highest/lowest priority
13681 ;; and is wrapped around to the empty priority
13682 (setq remove t)))
13683 (setq news (format "%c" new))
13684 (if have
13685 (if remove
13686 (replace-match "" t t nil 1)
13687 (replace-match news t t nil 2))
13688 (if remove
13689 (user-error "No priority cookie found in line")
13690 (let ((case-fold-search nil))
13691 (looking-at org-todo-line-regexp))
13692 (if (match-end 2)
13693 (progn
13694 (goto-char (match-end 2))
13695 (insert " [#" news "]"))
13696 (goto-char (match-beginning 3))
13697 (insert "[#" news "] "))))
13698 (org-preserve-lc (org-set-tags nil 'align)))
13699 (if remove
13700 (message "Priority removed")
13701 (message "Priority of current item set to %s" news)))))
13703 (defun org-show-priority ()
13704 "Show the priority of the current item.
13705 This priority is composed of the main priority given with the [#A] cookies,
13706 and by additional input from the age of a schedules or deadline entry."
13707 (interactive)
13708 (let ((pri (if (eq major-mode 'org-agenda-mode)
13709 (org-get-at-bol 'priority)
13710 (save-excursion
13711 (save-match-data
13712 (beginning-of-line)
13713 (and (looking-at org-heading-regexp)
13714 (org-get-priority (match-string 0))))))))
13715 (message "Priority is %d" (if pri pri -1000))))
13717 (defun org-get-priority (s)
13718 "Find priority cookie and return priority."
13719 (save-match-data
13720 (if (functionp org-get-priority-function)
13721 (funcall org-get-priority-function)
13722 (if (not (string-match org-priority-regexp s))
13723 (* 1000 (- org-lowest-priority org-default-priority))
13724 (* 1000 (- org-lowest-priority
13725 (string-to-char (match-string 2 s))))))))
13727 ;;;; Tags
13729 (defvar org-agenda-archives-mode)
13730 (defvar org-map-continue-from nil
13731 "Position from where mapping should continue.
13732 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13734 (defvar org-scanner-tags nil
13735 "The current tag list while the tags scanner is running.")
13736 (defvar org-trust-scanner-tags nil
13737 "Should `org-get-tags-at' use the tags for the scanner.
13738 This is for internal dynamical scoping only.
13739 When this is non-nil, the function `org-get-tags-at' will return the value
13740 of `org-scanner-tags' instead of building the list by itself. This
13741 can lead to large speed-ups when the tags scanner is used in a file with
13742 many entries, and when the list of tags is retrieved, for example to
13743 obtain a list of properties. Building the tags list for each entry in such
13744 a file becomes an N^2 operation - but with this variable set, it scales
13745 as N.")
13747 (defun org-scan-tags (action matcher todo-only &optional start-level)
13748 "Sca headline tags with inheritance and produce output ACTION.
13750 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13751 or `agenda' to produce an entry list for an agenda view. It can also be
13752 a Lisp form or a function that should be called at each matched headline, in
13753 this case the return value is a list of all return values from these calls.
13755 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13756 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13757 only lines with a not-done TODO keyword are included in the output.
13758 This should be the same variable that was scoped into
13759 and set by `org-make-tags-matcher' when it constructed MATCHER.
13761 START-LEVEL can be a string with asterisks, reducing the scope to
13762 headlines matching this string."
13763 (require 'org-agenda)
13764 (let* ((re (concat "^"
13765 (if start-level
13766 ;; Get the correct level to match
13767 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13768 org-outline-regexp)
13769 " *\\(\\<\\("
13770 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13771 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13772 (props (list 'face 'default
13773 'done-face 'org-agenda-done
13774 'undone-face 'default
13775 'mouse-face 'highlight
13776 'org-not-done-regexp org-not-done-regexp
13777 'org-todo-regexp org-todo-regexp
13778 'org-complex-heading-regexp org-complex-heading-regexp
13779 'help-echo
13780 (format "mouse-2 or RET jump to org file %s"
13781 (abbreviate-file-name
13782 (or (buffer-file-name (buffer-base-buffer))
13783 (buffer-name (buffer-base-buffer)))))))
13784 (org-map-continue-from nil)
13785 lspos tags tags-list
13786 (tags-alist (list (cons 0 org-file-tags)))
13787 (llast 0) rtn rtn1 level category i txt
13788 todo marker entry priority)
13789 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13790 (setq action (list 'lambda nil action)))
13791 (save-excursion
13792 (goto-char (point-min))
13793 (when (eq action 'sparse-tree)
13794 (org-overview)
13795 (org-remove-occur-highlights))
13796 (while (let (case-fold-search)
13797 (re-search-forward re nil t))
13798 (setq org-map-continue-from nil)
13799 (catch :skip
13800 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13801 tags (if (match-end 4) (org-match-string-no-properties 4)))
13802 (goto-char (setq lspos (match-beginning 0)))
13803 (setq level (org-reduced-level (org-outline-level))
13804 category (org-get-category))
13805 (setq i llast llast level)
13806 ;; remove tag lists from same and sublevels
13807 (while (>= i level)
13808 (when (setq entry (assoc i tags-alist))
13809 (setq tags-alist (delete entry tags-alist)))
13810 (setq i (1- i)))
13811 ;; add the next tags
13812 (when tags
13813 (setq tags (org-split-string tags ":")
13814 tags-alist
13815 (cons (cons level tags) tags-alist)))
13816 ;; compile tags for current headline
13817 (setq tags-list
13818 (if org-use-tag-inheritance
13819 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13820 tags)
13821 org-scanner-tags tags-list)
13822 (when org-use-tag-inheritance
13823 (setcdr (car tags-alist)
13824 (mapcar (lambda (x)
13825 (setq x (copy-sequence x))
13826 (org-add-prop-inherited x))
13827 (cdar tags-alist))))
13828 (when (and tags org-use-tag-inheritance
13829 (or (not (eq t org-use-tag-inheritance))
13830 org-tags-exclude-from-inheritance))
13831 ;; selective inheritance, remove uninherited ones
13832 (setcdr (car tags-alist)
13833 (org-remove-uninherited-tags (cdar tags-alist))))
13834 (when (and
13836 ;; eval matcher only when the todo condition is OK
13837 (and (or (not todo-only) (member todo org-not-done-keywords))
13838 (let ((case-fold-search t) (org-trust-scanner-tags t))
13839 (eval matcher)))
13841 ;; Call the skipper, but return t if it does not skip,
13842 ;; so that the `and' form continues evaluating
13843 (progn
13844 (unless (eq action 'sparse-tree) (org-agenda-skip))
13847 ;; Check if timestamps are deselecting this entry
13848 (or (not todo-only)
13849 (and (member todo org-not-done-keywords)
13850 (or (not org-agenda-tags-todo-honor-ignore-options)
13851 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13853 ;; select this headline
13854 (cond
13855 ((eq action 'sparse-tree)
13856 (and org-highlight-sparse-tree-matches
13857 (org-get-heading) (match-end 0)
13858 (org-highlight-new-match
13859 (match-beginning 1) (match-end 1)))
13860 (org-show-context 'tags-tree))
13861 ((eq action 'agenda)
13862 (setq txt (org-agenda-format-item
13864 (concat
13865 (if (eq org-tags-match-list-sublevels 'indented)
13866 (make-string (1- level) ?.) "")
13867 (org-get-heading))
13868 level category
13869 tags-list)
13870 priority (org-get-priority txt))
13871 (goto-char lspos)
13872 (setq marker (org-agenda-new-marker))
13873 (org-add-props txt props
13874 'org-marker marker 'org-hd-marker marker 'org-category category
13875 'todo-state todo
13876 'priority priority 'type "tagsmatch")
13877 (push txt rtn))
13878 ((functionp action)
13879 (setq org-map-continue-from nil)
13880 (save-excursion
13881 (setq rtn1 (funcall action))
13882 (push rtn1 rtn)))
13883 (t (user-error "Invalid action")))
13885 ;; if we are to skip sublevels, jump to end of subtree
13886 (unless org-tags-match-list-sublevels
13887 (org-end-of-subtree t)
13888 (backward-char 1))))
13889 ;; Get the correct position from where to continue
13890 (if org-map-continue-from
13891 (goto-char org-map-continue-from)
13892 (and (= (point) lspos) (end-of-line 1)))))
13893 (when (and (eq action 'sparse-tree)
13894 (not org-sparse-tree-open-archived-trees))
13895 (org-hide-archived-subtrees (point-min) (point-max)))
13896 (nreverse rtn)))
13898 (defun org-remove-uninherited-tags (tags)
13899 "Remove all tags that are not inherited from the list TAGS."
13900 (cond
13901 ((eq org-use-tag-inheritance t)
13902 (if org-tags-exclude-from-inheritance
13903 (org-delete-all org-tags-exclude-from-inheritance tags)
13904 tags))
13905 ((not org-use-tag-inheritance) nil)
13906 ((stringp org-use-tag-inheritance)
13907 (delq nil (mapcar
13908 (lambda (x)
13909 (if (and (string-match org-use-tag-inheritance x)
13910 (not (member x org-tags-exclude-from-inheritance)))
13911 x nil))
13912 tags)))
13913 ((listp org-use-tag-inheritance)
13914 (delq nil (mapcar
13915 (lambda (x)
13916 (if (member x org-use-tag-inheritance) x nil))
13917 tags)))))
13919 (defun org-match-sparse-tree (&optional todo-only match)
13920 "Create a sparse tree according to tags string MATCH.
13921 MATCH can contain positive and negative selection of tags, like
13922 \"+WORK+URGENT-WITHBOSS\".
13923 If optional argument TODO-ONLY is non-nil, only select lines that are
13924 also TODO lines."
13925 (interactive "P")
13926 (org-agenda-prepare-buffers (list (current-buffer)))
13927 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13929 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13931 (defvar org-cached-props nil)
13932 (defun org-cached-entry-get (pom property)
13933 (if (or (eq t org-use-property-inheritance)
13934 (and (stringp org-use-property-inheritance)
13935 (string-match org-use-property-inheritance property))
13936 (and (listp org-use-property-inheritance)
13937 (member property org-use-property-inheritance)))
13938 ;; Caching is not possible, check it directly
13939 (org-entry-get pom property 'inherit)
13940 ;; Get all properties, so that we can do complicated checks easily
13941 (cdr (assoc property (or org-cached-props
13942 (setq org-cached-props
13943 (org-entry-properties pom)))))))
13945 (defun org-global-tags-completion-table (&optional files)
13946 "Return the list of all tags in all agenda buffer/files.
13947 Optional FILES argument is a list of files which can be used
13948 instead of the agenda files."
13949 (save-excursion
13950 (org-uniquify
13951 (delq nil
13952 (apply 'append
13953 (mapcar
13954 (lambda (file)
13955 (set-buffer (find-file-noselect file))
13956 (append (org-get-buffer-tags)
13957 (mapcar (lambda (x) (if (stringp (car-safe x))
13958 (list (car-safe x)) nil))
13959 org-tag-alist)))
13960 (if (and files (car files))
13961 files
13962 (org-agenda-files))))))))
13964 (defun org-make-tags-matcher (match)
13965 "Create the TAGS/TODO matcher form for the selection string MATCH.
13967 The variable `todo-only' is scoped dynamically into this function.
13968 It will be set to t if the matcher restricts matching to TODO entries,
13969 otherwise will not be touched.
13971 Returns a cons of the selection string MATCH and the constructed
13972 lisp form implementing the matcher. The matcher is to be evaluated
13973 at an Org entry, with point on the headline, and returns t if the
13974 entry matches the selection string MATCH. The returned lisp form
13975 references two variables with information about the entry, which
13976 must be bound around the form's evaluation: todo, the TODO keyword
13977 at the entry (or nil of none); and tags-list, the list of all tags
13978 at the entry including inherited ones. Additionally, the category
13979 of the entry (if any) must be specified as the text property
13980 'org-category on the headline.
13982 See also `org-scan-tags'.
13984 (declare (special todo-only))
13985 (unless (boundp 'todo-only)
13986 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
13987 (unless match
13988 ;; Get a new match request, with completion against the global
13989 ;; tags table and the local tags in current buffer
13990 (let ((org-last-tags-completion-table
13991 (org-uniquify
13992 (delq nil (append (org-get-buffer-tags)
13993 (org-global-tags-completion-table))))))
13994 (setq match (org-completing-read-no-i
13995 "Match: " 'org-tags-completion-function nil nil nil
13996 'org-tags-history))))
13998 ;; Parse the string and create a lisp form
13999 (let ((match0 match)
14000 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14001 minus tag mm
14002 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14003 orterms term orlist re-p str-p level-p level-op time-p
14004 prop-p pn pv po gv rest)
14005 ;; Expand group tags
14006 (setq match (org-tags-expand match))
14007 (if (string-match "/+" match)
14008 ;; match contains also a todo-matching request
14009 (progn
14010 (setq tagsmatch (substring match 0 (match-beginning 0))
14011 todomatch (substring match (match-end 0)))
14012 (if (string-match "^!" todomatch)
14013 (setq todo-only t todomatch (substring todomatch 1)))
14014 (if (string-match "^\\s-*$" todomatch)
14015 (setq todomatch nil)))
14016 ;; only matching tags
14017 (setq tagsmatch match todomatch nil))
14019 ;; Make the tags matcher
14020 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14021 (setq tagsmatcher t)
14022 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14023 (while (setq term (pop orterms))
14024 (while (and (equal (substring term -1) "\\") orterms)
14025 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14026 (while (string-match re term)
14027 (setq rest (substring term (match-end 0))
14028 minus (and (match-end 1)
14029 (equal (match-string 1 term) "-"))
14030 tag (save-match-data (replace-regexp-in-string
14031 "\\\\-" "-"
14032 (match-string 2 term)))
14033 re-p (equal (string-to-char tag) ?{)
14034 level-p (match-end 4)
14035 prop-p (match-end 5)
14036 mm (cond
14037 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14038 (level-p
14039 (setq level-op (org-op-to-function (match-string 3 term)))
14040 `(,level-op level ,(string-to-number
14041 (match-string 4 term))))
14042 (prop-p
14043 (setq pn (match-string 5 term)
14044 po (match-string 6 term)
14045 pv (match-string 7 term)
14046 re-p (equal (string-to-char pv) ?{)
14047 str-p (equal (string-to-char pv) ?\")
14048 time-p (save-match-data
14049 (string-match "^\"[[<].*[]>]\"$" pv))
14050 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14051 (if time-p (setq pv (org-matcher-time pv)))
14052 (setq po (org-op-to-function po (if time-p 'time str-p)))
14053 (cond
14054 ((equal pn "CATEGORY")
14055 (setq gv '(get-text-property (point) 'org-category)))
14056 ((equal pn "TODO")
14057 (setq gv 'todo))
14059 (setq gv `(org-cached-entry-get nil ,pn))))
14060 (if re-p
14061 (if (eq po 'org<>)
14062 `(not (string-match ,pv (or ,gv "")))
14063 `(string-match ,pv (or ,gv "")))
14064 (if str-p
14065 `(,po (or ,gv "") ,pv)
14066 `(,po (string-to-number (or ,gv ""))
14067 ,(string-to-number pv) ))))
14068 (t `(member ,tag tags-list)))
14069 mm (if minus (list 'not mm) mm)
14070 term rest)
14071 (push mm tagsmatcher))
14072 (push (if (> (length tagsmatcher) 1)
14073 (cons 'and tagsmatcher)
14074 (car tagsmatcher))
14075 orlist)
14076 (setq tagsmatcher nil))
14077 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14078 (setq tagsmatcher
14079 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14080 ;; Make the todo matcher
14081 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14082 (setq todomatcher t)
14083 (setq orterms (org-split-string todomatch "|") orlist nil)
14084 (while (setq term (pop orterms))
14085 (while (string-match re term)
14086 (setq minus (and (match-end 1)
14087 (equal (match-string 1 term) "-"))
14088 kwd (match-string 2 term)
14089 re-p (equal (string-to-char kwd) ?{)
14090 term (substring term (match-end 0))
14091 mm (if re-p
14092 `(string-match ,(substring kwd 1 -1) todo)
14093 (list 'equal 'todo kwd))
14094 mm (if minus (list 'not mm) mm))
14095 (push mm todomatcher))
14096 (push (if (> (length todomatcher) 1)
14097 (cons 'and todomatcher)
14098 (car todomatcher))
14099 orlist)
14100 (setq todomatcher nil))
14101 (setq todomatcher (if (> (length orlist) 1)
14102 (cons 'or orlist) (car orlist))))
14104 ;; Return the string and lisp forms of the matcher
14105 (setq matcher (if todomatcher
14106 (list 'and tagsmatcher todomatcher)
14107 tagsmatcher))
14108 (when todo-only
14109 (setq matcher (list 'and '(member todo org-not-done-keywords)
14110 matcher)))
14111 (cons match0 matcher)))
14113 (defun org-tags-expand (match &optional single-as-list downcased)
14114 "Expand group tags in MATCH.
14116 This replaces every group tag in MATCH with a regexp tag search.
14117 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14118 will be replaced like this:
14120 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14121 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14122 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14124 Replacing by a regexp preserves the structure of the match.
14125 E.g., this expansion
14127 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14129 will match anything tagged with \"Lab\" and \"Home\", or tagged
14130 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14132 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14133 assumed to be a single group tag, and the function will return
14134 the list of tags in this group.
14136 When DOWNCASE is non-nil, expand downcased TAGS."
14137 (if org-group-tags
14138 (let* ((case-fold-search t)
14139 (stable org-mode-syntax-table)
14140 (tal (or org-tag-groups-alist-for-agenda
14141 org-tag-groups-alist))
14142 (tal (if downcased
14143 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14144 (tml (mapcar 'car tal))
14145 (rtnmatch match) rpl)
14146 ;; @ and _ are allowed as word-components in tags
14147 (modify-syntax-entry ?@ "w" stable)
14148 (modify-syntax-entry ?_ "w" stable)
14149 (while (and tml
14150 (string-match
14151 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14152 (regexp-opt tml) "\\>\\)") rtnmatch))
14153 (let* ((dir (match-string 1 rtnmatch))
14154 (tag (match-string 2 rtnmatch))
14155 (tag (if downcased (downcase tag) tag)))
14156 (setq tml (delete tag tml))
14157 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14158 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14159 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14160 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14161 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14162 (if single-as-list
14163 (or (reverse rpl) (list rtnmatch))
14164 rtnmatch))
14165 (if single-as-list (list (if downcased (downcase match) match))
14166 match)))
14168 (defun org-op-to-function (op &optional stringp)
14169 "Turn an operator into the appropriate function."
14170 (setq op
14171 (cond
14172 ((equal op "<" ) '(< string< org-time<))
14173 ((equal op ">" ) '(> org-string> org-time>))
14174 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14175 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14176 ((member op '("=" "==")) '(= string= org-time=))
14177 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14178 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14180 (defun org<> (a b) (not (= a b)))
14181 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14182 (defun org-string>= (a b) (not (string< a b)))
14183 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14184 (defun org-string<> (a b) (not (string= a b)))
14185 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14186 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14187 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14188 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14189 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14190 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14191 (defun org-2ft (s)
14192 "Convert S to a floating point time.
14193 If S is already a number, just return it. If it is a string, parse
14194 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14195 (cond
14196 ((numberp s) s)
14197 ((stringp s)
14198 (condition-case nil
14199 (float-time (apply 'encode-time (org-parse-time-string s)))
14200 (error 0.)))
14201 (t 0.)))
14203 (defun org-time-today ()
14204 "Time in seconds today at 0:00.
14205 Returns the float number of seconds since the beginning of the
14206 epoch to the beginning of today (00:00)."
14207 (float-time (apply 'encode-time
14208 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14210 (defun org-matcher-time (s)
14211 "Interpret a time comparison value."
14212 (save-match-data
14213 (cond
14214 ((string= s "<now>") (float-time))
14215 ((string= s "<today>") (org-time-today))
14216 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14217 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14218 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14219 (+ (org-time-today)
14220 (* (string-to-number (match-string 1 s))
14221 (cdr (assoc (match-string 2 s)
14222 '(("d" . 86400.0) ("w" . 604800.0)
14223 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14224 (t (org-2ft s)))))
14226 (defun org-match-any-p (re list)
14227 "Does re match any element of list?"
14228 (setq list (mapcar (lambda (x) (string-match re x)) list))
14229 (delq nil list))
14231 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14232 (defvar org-tags-overlay (make-overlay 1 1))
14233 (org-detach-overlay org-tags-overlay)
14235 (defun org-get-local-tags-at (&optional pos)
14236 "Get a list of tags defined in the current headline."
14237 (org-get-tags-at pos 'local))
14239 (defun org-get-local-tags ()
14240 "Get a list of tags defined in the current headline."
14241 (org-get-tags-at nil 'local))
14243 (defun org-get-tags-at (&optional pos local)
14244 "Get a list of all headline tags applicable at POS.
14245 POS defaults to point. If tags are inherited, the list contains
14246 the targets in the same sequence as the headlines appear, i.e.
14247 the tags of the current headline come last.
14248 When LOCAL is non-nil, only return tags from the current headline,
14249 ignore inherited ones."
14250 (interactive)
14251 (if (and org-trust-scanner-tags
14252 (or (not pos) (equal pos (point)))
14253 (not local))
14254 org-scanner-tags
14255 (let (tags ltags lastpos parent)
14256 (save-excursion
14257 (save-restriction
14258 (widen)
14259 (goto-char (or pos (point)))
14260 (save-match-data
14261 (catch 'done
14262 (condition-case nil
14263 (progn
14264 (org-back-to-heading t)
14265 (while (not (equal lastpos (point)))
14266 (setq lastpos (point))
14267 (when (looking-at
14268 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14269 (setq ltags (org-split-string
14270 (org-match-string-no-properties 1) ":"))
14271 (when parent
14272 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14273 (setq tags (append
14274 (if parent
14275 (org-remove-uninherited-tags ltags)
14276 ltags)
14277 tags)))
14278 (or org-use-tag-inheritance (throw 'done t))
14279 (if local (throw 'done t))
14280 (or (org-up-heading-safe) (error nil))
14281 (setq parent t)))
14282 (error nil)))))
14283 (if local
14284 tags
14285 (reverse (delete-dups
14286 (reverse (append
14287 (org-remove-uninherited-tags
14288 org-file-tags) tags)))))))))
14290 (defun org-add-prop-inherited (s)
14291 (add-text-properties 0 (length s) '(inherited t) s)
14294 (defun org-toggle-tag (tag &optional onoff)
14295 "Toggle the tag TAG for the current line.
14296 If ONOFF is `on' or `off', don't toggle but set to this state."
14297 (let (res current)
14298 (save-excursion
14299 (org-back-to-heading t)
14300 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14301 (point-at-eol) t)
14302 (progn
14303 (setq current (match-string 1))
14304 (replace-match ""))
14305 (setq current ""))
14306 (setq current (nreverse (org-split-string current ":")))
14307 (cond
14308 ((eq onoff 'on)
14309 (setq res t)
14310 (or (member tag current) (push tag current)))
14311 ((eq onoff 'off)
14312 (or (not (member tag current)) (setq current (delete tag current))))
14313 (t (if (member tag current)
14314 (setq current (delete tag current))
14315 (setq res t)
14316 (push tag current))))
14317 (end-of-line 1)
14318 (if current
14319 (progn
14320 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14321 (org-set-tags nil t))
14322 (delete-horizontal-space))
14323 (run-hooks 'org-after-tags-change-hook))
14324 res))
14326 (defun org-align-tags-here (to-col)
14327 ;; Assumes that this is a headline
14328 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14329 (beginning-of-line 1)
14330 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14331 (< pos (match-beginning 2)))
14332 (progn
14333 (setq tags-l (- (match-end 2) (match-beginning 2)))
14334 (goto-char (match-beginning 1))
14335 (insert " ")
14336 (delete-region (point) (1+ (match-beginning 2)))
14337 (setq ncol (max (current-column)
14338 (1+ col)
14339 (if (> to-col 0)
14340 to-col
14341 (- (abs to-col) tags-l))))
14342 (setq p (point))
14343 (insert (make-string (- ncol (current-column)) ?\ ))
14344 (setq ncol (current-column))
14345 (when indent-tabs-mode (tabify p (point-at-eol)))
14346 (org-move-to-column (min ncol col) t))
14347 (goto-char pos))))
14349 (defun org-set-tags-command (&optional arg just-align)
14350 "Call the set-tags command for the current entry."
14351 (interactive "P")
14352 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14353 (org-set-tags arg just-align)
14354 (save-excursion
14355 (unless (and (org-region-active-p)
14356 org-loop-over-headlines-in-active-region)
14357 (org-back-to-heading t))
14358 (org-set-tags arg just-align))))
14360 (defun org-set-tags-to (data)
14361 "Set the tags of the current entry to DATA, replacing the current tags.
14362 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14363 If DATA is nil or the empty string, any tags will be removed."
14364 (interactive "sTags: ")
14365 (setq data
14366 (cond
14367 ((eq data nil) "")
14368 ((equal data "") "")
14369 ((stringp data)
14370 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14371 ":"))
14372 ((listp data)
14373 (concat ":" (mapconcat 'identity data ":") ":"))))
14374 (when data
14375 (save-excursion
14376 (org-back-to-heading t)
14377 (when (looking-at org-complex-heading-regexp)
14378 (if (match-end 5)
14379 (progn
14380 (goto-char (match-beginning 5))
14381 (insert data)
14382 (delete-region (point) (point-at-eol))
14383 (org-set-tags nil 'align))
14384 (goto-char (point-at-eol))
14385 (insert " " data)
14386 (org-set-tags nil 'align)))
14387 (beginning-of-line 1)
14388 (if (looking-at ".*?\\([ \t]+\\)$")
14389 (delete-region (match-beginning 1) (match-end 1))))))
14391 (defun org-align-all-tags ()
14392 "Align the tags i all headings."
14393 (interactive)
14394 (save-excursion
14395 (or (ignore-errors (org-back-to-heading t))
14396 (outline-next-heading))
14397 (if (org-at-heading-p)
14398 (org-set-tags t)
14399 (message "No headings"))))
14401 (defvar org-indent-indentation-per-level)
14402 (defun org-set-tags (&optional arg just-align)
14403 "Set the tags for the current headline.
14404 With prefix ARG, realign all tags in headings in the current buffer."
14405 (interactive "P")
14406 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14407 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14408 'region-start-level 'region))
14409 org-loop-over-headlines-in-active-region)
14410 (org-map-entries
14411 ;; We don't use ARG and JUST-ALIGN here these args are not
14412 ;; useful when looping over headlines
14413 `(org-set-tags)
14414 org-loop-over-headlines-in-active-region
14415 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14416 (let* ((re org-outline-regexp-bol)
14417 (current (unless arg (org-get-tags-string)))
14418 (col (current-column))
14419 (org-setting-tags t)
14420 table current-tags inherited-tags ; computed below when needed
14421 tags p0 c0 c1 rpl di tc level)
14422 (if arg
14423 (save-excursion
14424 (goto-char (point-min))
14425 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14426 (while (re-search-forward re nil t)
14427 (org-set-tags nil t)
14428 (end-of-line 1)))
14429 (message "All tags realigned to column %d" org-tags-column))
14430 (if just-align
14431 (setq tags current)
14432 ;; Get a new set of tags from the user
14433 (save-excursion
14434 (setq table (append org-tag-persistent-alist
14435 (or org-tag-alist (org-get-buffer-tags))
14436 (and
14437 org-complete-tags-always-offer-all-agenda-tags
14438 (org-global-tags-completion-table
14439 (org-agenda-files))))
14440 org-last-tags-completion-table table
14441 current-tags (org-split-string current ":")
14442 inherited-tags (nreverse
14443 (nthcdr (length current-tags)
14444 (nreverse (org-get-tags-at))))
14445 tags
14446 (if (or (eq t org-use-fast-tag-selection)
14447 (and org-use-fast-tag-selection
14448 (delq nil (mapcar 'cdr table))))
14449 (org-fast-tag-selection
14450 current-tags inherited-tags table
14451 (if org-fast-tag-selection-include-todo
14452 org-todo-key-alist))
14453 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14454 (org-trim
14455 (org-icompleting-read "Tags: "
14456 'org-tags-completion-function
14457 nil nil current 'org-tags-history))))))
14458 (while (string-match "[-+&]+" tags)
14459 ;; No boolean logic, just a list
14460 (setq tags (replace-match ":" t t tags))))
14462 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14464 (if org-tags-sort-function
14465 (setq tags (mapconcat 'identity
14466 (sort (org-split-string
14467 tags (org-re "[^[:alnum:]_@#%]+"))
14468 org-tags-sort-function) ":")))
14470 (if (string-match "\\`[\t ]*\\'" tags)
14471 (setq tags "")
14472 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14473 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14475 ;; Insert new tags at the correct column
14476 (beginning-of-line 1)
14477 (setq level (or (and (looking-at org-outline-regexp)
14478 (- (match-end 0) (point) 1))
14480 (cond
14481 ((and (equal current "") (equal tags "")))
14482 ((re-search-forward
14483 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14484 (point-at-eol) t)
14485 (if (equal tags "")
14486 (setq rpl "")
14487 (goto-char (match-beginning 0))
14488 (setq c0 (current-column)
14489 ;; compute offset for the case of org-indent-mode active
14490 di (if org-indent-mode
14491 (* (1- org-indent-indentation-per-level) (1- level))
14493 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14494 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14495 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14496 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14497 (replace-match rpl t t)
14498 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14499 tags)
14500 (t (error "Tags alignment failed")))
14501 (org-move-to-column col)
14502 (unless just-align
14503 (run-hooks 'org-after-tags-change-hook))))))
14505 (defun org-change-tag-in-region (beg end tag off)
14506 "Add or remove TAG for each entry in the region.
14507 This works in the agenda, and also in an org-mode buffer."
14508 (interactive
14509 (list (region-beginning) (region-end)
14510 (let ((org-last-tags-completion-table
14511 (if (derived-mode-p 'org-mode)
14512 (org-uniquify
14513 (delq nil (append (org-get-buffer-tags)
14514 (org-global-tags-completion-table))))
14515 (org-global-tags-completion-table))))
14516 (org-icompleting-read
14517 "Tag: " 'org-tags-completion-function nil nil nil
14518 'org-tags-history))
14519 (progn
14520 (message "[s]et or [r]emove? ")
14521 (equal (read-char-exclusive) ?r))))
14522 (if (fboundp 'deactivate-mark) (deactivate-mark))
14523 (let ((agendap (equal major-mode 'org-agenda-mode))
14524 l1 l2 m buf pos newhead (cnt 0))
14525 (goto-char end)
14526 (setq l2 (1- (org-current-line)))
14527 (goto-char beg)
14528 (setq l1 (org-current-line))
14529 (loop for l from l1 to l2 do
14530 (org-goto-line l)
14531 (setq m (get-text-property (point) 'org-hd-marker))
14532 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14533 (and agendap m))
14534 (setq buf (if agendap (marker-buffer m) (current-buffer))
14535 pos (if agendap m (point)))
14536 (with-current-buffer buf
14537 (save-excursion
14538 (save-restriction
14539 (goto-char pos)
14540 (setq cnt (1+ cnt))
14541 (org-toggle-tag tag (if off 'off 'on))
14542 (setq newhead (org-get-heading)))))
14543 (and agendap (org-agenda-change-all-lines newhead m))))
14544 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14546 (defun org-tags-completion-function (string predicate &optional flag)
14547 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14548 (confirm (lambda (x) (stringp (car x)))))
14549 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14550 (setq s1 (match-string 1 string)
14551 s2 (match-string 2 string))
14552 (setq s1 "" s2 string))
14553 (cond
14554 ((eq flag nil)
14555 ;; try completion
14556 (setq rtn (try-completion s2 ctable confirm))
14557 (if (stringp rtn)
14558 (setq rtn
14559 (concat s1 s2 (substring rtn (length s2))
14560 (if (and org-add-colon-after-tag-completion
14561 (assoc rtn ctable))
14562 ":" ""))))
14563 rtn)
14564 ((eq flag t)
14565 ;; all-completions
14566 (all-completions s2 ctable confirm))
14567 ((eq flag 'lambda)
14568 ;; exact match?
14569 (assoc s2 ctable)))))
14571 (defun org-fast-tag-insert (kwd tags face &optional end)
14572 "Insert KDW, and the TAGS, the latter with face FACE.
14573 Also insert END."
14574 (insert (format "%-12s" (concat kwd ":"))
14575 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14576 (or end "")))
14578 (defun org-fast-tag-show-exit (flag)
14579 (save-excursion
14580 (org-goto-line 3)
14581 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14582 (replace-match ""))
14583 (when flag
14584 (end-of-line 1)
14585 (org-move-to-column (- (window-width) 19) t)
14586 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14588 (defun org-set-current-tags-overlay (current prefix)
14589 "Add an overlay to CURRENT tag with PREFIX."
14590 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14591 (if (featurep 'xemacs)
14592 (org-overlay-display org-tags-overlay (concat prefix s)
14593 'secondary-selection)
14594 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14595 (org-overlay-display org-tags-overlay (concat prefix s)))))
14597 (defvar org-last-tag-selection-key nil)
14598 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14599 "Fast tag selection with single keys.
14600 CURRENT is the current list of tags in the headline, INHERITED is the
14601 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14602 possibly with grouping information. TODO-TABLE is a similar table with
14603 TODO keywords, should these have keys assigned to them.
14604 If the keys are nil, a-z are automatically assigned.
14605 Returns the new tags string, or nil to not change the current settings."
14606 (let* ((fulltable (append table todo-table))
14607 (maxlen (apply 'max (mapcar
14608 (lambda (x)
14609 (if (stringp (car x)) (string-width (car x)) 0))
14610 fulltable)))
14611 (buf (current-buffer))
14612 (expert (eq org-fast-tag-selection-single-key 'expert))
14613 (buffer-tags nil)
14614 (fwidth (+ maxlen 3 1 3))
14615 (ncol (/ (- (window-width) 4) fwidth))
14616 (i-face 'org-done)
14617 (c-face 'org-todo)
14618 tg cnt e c char c1 c2 ntable tbl rtn
14619 ov-start ov-end ov-prefix
14620 (exit-after-next org-fast-tag-selection-single-key)
14621 (done-keywords org-done-keywords)
14622 groups ingroup)
14623 (save-excursion
14624 (beginning-of-line 1)
14625 (if (looking-at
14626 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14627 (setq ov-start (match-beginning 1)
14628 ov-end (match-end 1)
14629 ov-prefix "")
14630 (setq ov-start (1- (point-at-eol))
14631 ov-end (1+ ov-start))
14632 (skip-chars-forward "^\n\r")
14633 (setq ov-prefix
14634 (concat
14635 (buffer-substring (1- (point)) (point))
14636 (if (> (current-column) org-tags-column)
14638 (make-string (- org-tags-column (current-column)) ?\ ))))))
14639 (move-overlay org-tags-overlay ov-start ov-end)
14640 (save-window-excursion
14641 (if expert
14642 (set-buffer (get-buffer-create " *Org tags*"))
14643 (delete-other-windows)
14644 (split-window-vertically)
14645 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14646 (erase-buffer)
14647 (org-set-local 'org-done-keywords done-keywords)
14648 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14649 (org-fast-tag-insert "Current" current c-face "\n\n")
14650 (org-fast-tag-show-exit exit-after-next)
14651 (org-set-current-tags-overlay current ov-prefix)
14652 (setq tbl fulltable char ?a cnt 0)
14653 (while (setq e (pop tbl))
14654 (cond
14655 ((equal (car e) :startgroup)
14656 (push '() groups) (setq ingroup t)
14657 (when (not (= cnt 0))
14658 (setq cnt 0)
14659 (insert "\n"))
14660 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14661 ((equal (car e) :endgroup)
14662 (setq ingroup nil cnt 0)
14663 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14664 ((equal e '(:newline))
14665 (when (not (= cnt 0))
14666 (setq cnt 0)
14667 (insert "\n")
14668 (setq e (car tbl))
14669 (while (equal (car tbl) '(:newline))
14670 (insert "\n")
14671 (setq tbl (cdr tbl)))))
14672 ((equal e '(:grouptags)) nil)
14674 (setq tg (copy-sequence (car e)) c2 nil)
14675 (if (cdr e)
14676 (setq c (cdr e))
14677 ;; automatically assign a character.
14678 (setq c1 (string-to-char
14679 (downcase (substring
14680 tg (if (= (string-to-char tg) ?@) 1 0)))))
14681 (if (or (rassoc c1 ntable) (rassoc c1 table))
14682 (while (or (rassoc char ntable) (rassoc char table))
14683 (setq char (1+ char)))
14684 (setq c2 c1))
14685 (setq c (or c2 char)))
14686 (if ingroup (push tg (car groups)))
14687 (setq tg (org-add-props tg nil 'face
14688 (cond
14689 ((not (assoc tg table))
14690 (org-get-todo-face tg))
14691 ((member tg current) c-face)
14692 ((member tg inherited) i-face))))
14693 (if (equal (caar tbl) :grouptags)
14694 (org-add-props tg nil 'face 'org-tag-group))
14695 (if (and (= cnt 0) (not ingroup)) (insert " "))
14696 (insert "[" c "] " tg (make-string
14697 (- fwidth 4 (length tg)) ?\ ))
14698 (push (cons tg c) ntable)
14699 (when (= (setq cnt (1+ cnt)) ncol)
14700 (insert "\n")
14701 (if ingroup (insert " "))
14702 (setq cnt 0)))))
14703 (setq ntable (nreverse ntable))
14704 (insert "\n")
14705 (goto-char (point-min))
14706 (if (not expert) (org-fit-window-to-buffer))
14707 (setq rtn
14708 (catch 'exit
14709 (while t
14710 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14711 (if (not groups) "no " "")
14712 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14713 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14714 (setq org-last-tag-selection-key c)
14715 (cond
14716 ((= c ?\r) (throw 'exit t))
14717 ((= c ?!)
14718 (setq groups (not groups))
14719 (goto-char (point-min))
14720 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14721 ((= c ?\C-c)
14722 (if (not expert)
14723 (org-fast-tag-show-exit
14724 (setq exit-after-next (not exit-after-next)))
14725 (setq expert nil)
14726 (delete-other-windows)
14727 (set-window-buffer (split-window-vertically) " *Org tags*")
14728 (org-switch-to-buffer-other-window " *Org tags*")
14729 (org-fit-window-to-buffer)))
14730 ((or (= c ?\C-g)
14731 (and (= c ?q) (not (rassoc c ntable))))
14732 (org-detach-overlay org-tags-overlay)
14733 (setq quit-flag t))
14734 ((= c ?\ )
14735 (setq current nil)
14736 (if exit-after-next (setq exit-after-next 'now)))
14737 ((= c ?\t)
14738 (condition-case nil
14739 (setq tg (org-icompleting-read
14740 "Tag: "
14741 (or buffer-tags
14742 (with-current-buffer buf
14743 (org-get-buffer-tags)))))
14744 (quit (setq tg "")))
14745 (when (string-match "\\S-" tg)
14746 (add-to-list 'buffer-tags (list tg))
14747 (if (member tg current)
14748 (setq current (delete tg current))
14749 (push tg current)))
14750 (if exit-after-next (setq exit-after-next 'now)))
14751 ((setq e (rassoc c todo-table) tg (car e))
14752 (with-current-buffer buf
14753 (save-excursion (org-todo tg)))
14754 (if exit-after-next (setq exit-after-next 'now)))
14755 ((setq e (rassoc c ntable) tg (car e))
14756 (if (member tg current)
14757 (setq current (delete tg current))
14758 (loop for g in groups do
14759 (if (member tg g)
14760 (mapc (lambda (x)
14761 (setq current (delete x current)))
14762 g)))
14763 (push tg current))
14764 (if exit-after-next (setq exit-after-next 'now))))
14766 ;; Create a sorted list
14767 (setq current
14768 (sort current
14769 (lambda (a b)
14770 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14771 (if (eq exit-after-next 'now) (throw 'exit t))
14772 (goto-char (point-min))
14773 (beginning-of-line 2)
14774 (delete-region (point) (point-at-eol))
14775 (org-fast-tag-insert "Current" current c-face)
14776 (org-set-current-tags-overlay current ov-prefix)
14777 (while (re-search-forward
14778 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14779 (setq tg (match-string 1))
14780 (add-text-properties
14781 (match-beginning 1) (match-end 1)
14782 (list 'face
14783 (cond
14784 ((member tg current) c-face)
14785 ((member tg inherited) i-face)
14786 (t (get-text-property (match-beginning 1) 'face))))))
14787 (goto-char (point-min)))))
14788 (org-detach-overlay org-tags-overlay)
14789 (if rtn
14790 (mapconcat 'identity current ":")
14791 nil))))
14793 (defun org-get-tags-string ()
14794 "Get the TAGS string in the current headline."
14795 (unless (org-at-heading-p t)
14796 (user-error "Not on a heading"))
14797 (save-excursion
14798 (beginning-of-line 1)
14799 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14800 (org-match-string-no-properties 1)
14801 "")))
14803 (defun org-get-tags ()
14804 "Get the list of tags specified in the current headline."
14805 (org-split-string (org-get-tags-string) ":"))
14807 (defun org-get-buffer-tags ()
14808 "Get a table of all tags used in the buffer, for completion."
14809 (let (tags)
14810 (save-excursion
14811 (goto-char (point-min))
14812 (while (re-search-forward
14813 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14814 (when (equal (char-after (point-at-bol 0)) ?*)
14815 (mapc (lambda (x) (add-to-list 'tags x))
14816 (org-split-string (org-match-string-no-properties 1) ":")))))
14817 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14818 (mapcar 'list tags)))
14820 ;;;; The mapping API
14822 (defun org-map-entries (func &optional match scope &rest skip)
14823 "Call FUNC at each headline selected by MATCH in SCOPE.
14825 FUNC is a function or a lisp form. The function will be called without
14826 arguments, with the cursor positioned at the beginning of the headline.
14827 The return values of all calls to the function will be collected and
14828 returned as a list.
14830 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14831 does not need to preserve point. After evaluation, the cursor will be
14832 moved to the end of the line (presumably of the headline of the
14833 processed entry) and search continues from there. Under some
14834 circumstances, this may not produce the wanted results. For example,
14835 if you have removed (e.g. archived) the current (sub)tree it could
14836 mean that the next entry will be skipped entirely. In such cases, you
14837 can specify the position from where search should continue by making
14838 FUNC set the variable `org-map-continue-from' to the desired buffer
14839 position.
14841 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14842 Only headlines that are matched by this query will be considered during
14843 the iteration. When MATCH is nil or t, all headlines will be
14844 visited by the iteration.
14846 SCOPE determines the scope of this command. It can be any of:
14848 nil The current buffer, respecting the restriction if any
14849 tree The subtree started with the entry at point
14850 region The entries within the active region, if any
14851 region-start-level
14852 The entries within the active region, but only those at
14853 the same level than the first one.
14854 file The current buffer, without restriction
14855 file-with-archives
14856 The current buffer, and any archives associated with it
14857 agenda All agenda files
14858 agenda-with-archives
14859 All agenda files with any archive files associated with them
14860 \(file1 file2 ...)
14861 If this is a list, all files in the list will be scanned
14863 The remaining args are treated as settings for the skipping facilities of
14864 the scanner. The following items can be given here:
14866 archive skip trees with the archive tag
14867 comment skip trees with the COMMENT keyword
14868 function or Emacs Lisp form:
14869 will be used as value for `org-agenda-skip-function', so
14870 whenever the function returns a position, FUNC will not be
14871 called for that entry and search will continue from the
14872 position returned
14874 If your function needs to retrieve the tags including inherited tags
14875 at the *current* entry, you can use the value of the variable
14876 `org-scanner-tags' which will be much faster than getting the value
14877 with `org-get-tags-at'. If your function gets properties with
14878 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14879 to t around the call to `org-entry-properties' to get the same speedup.
14880 Note that if your function moves around to retrieve tags and properties at
14881 a *different* entry, you cannot use these techniques."
14882 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14883 (not (org-region-active-p)))
14884 (let* ((org-agenda-archives-mode nil) ; just to make sure
14885 (org-agenda-skip-archived-trees (memq 'archive skip))
14886 (org-agenda-skip-comment-trees (memq 'comment skip))
14887 (org-agenda-skip-function
14888 (car (org-delete-all '(comment archive) skip)))
14889 (org-tags-match-list-sublevels t)
14890 (start-level (eq scope 'region-start-level))
14891 matcher file res
14892 org-todo-keywords-for-agenda
14893 org-done-keywords-for-agenda
14894 org-todo-keyword-alist-for-agenda
14895 org-drawers-for-agenda
14896 org-tag-alist-for-agenda
14897 todo-only)
14899 (cond
14900 ((eq match t) (setq matcher t))
14901 ((eq match nil) (setq matcher t))
14902 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14904 (save-window-excursion
14905 (save-restriction
14906 (cond ((eq scope 'tree)
14907 (org-back-to-heading t)
14908 (org-narrow-to-subtree)
14909 (setq scope nil))
14910 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14911 (org-region-active-p))
14912 ;; If needed, set start-level to a string like "2"
14913 (when start-level
14914 (save-excursion
14915 (goto-char (region-beginning))
14916 (unless (org-at-heading-p) (outline-next-heading))
14917 (setq start-level (org-current-level))))
14918 (narrow-to-region (region-beginning)
14919 (save-excursion
14920 (goto-char (region-end))
14921 (unless (and (bolp) (org-at-heading-p))
14922 (outline-next-heading))
14923 (point)))
14924 (setq scope nil)))
14926 (if (not scope)
14927 (progn
14928 (org-agenda-prepare-buffers
14929 (list (buffer-file-name (current-buffer))))
14930 (setq res (org-scan-tags func matcher todo-only start-level)))
14931 ;; Get the right scope
14932 (cond
14933 ((and scope (listp scope) (symbolp (car scope)))
14934 (setq scope (eval scope)))
14935 ((eq scope 'agenda)
14936 (setq scope (org-agenda-files t)))
14937 ((eq scope 'agenda-with-archives)
14938 (setq scope (org-agenda-files t))
14939 (setq scope (org-add-archive-files scope)))
14940 ((eq scope 'file)
14941 (setq scope (list (buffer-file-name))))
14942 ((eq scope 'file-with-archives)
14943 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14944 (org-agenda-prepare-buffers scope)
14945 (while (setq file (pop scope))
14946 (with-current-buffer (org-find-base-buffer-visiting file)
14947 (save-excursion
14948 (save-restriction
14949 (widen)
14950 (goto-char (point-min))
14951 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14952 res)))
14954 ;;;; Properties
14956 ;;; Setting and retrieving properties
14958 (defconst org-special-properties
14959 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14960 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14961 "The special properties valid in Org-mode.
14963 These are properties that are not defined in the property drawer,
14964 but in some other way.")
14966 (defconst org-default-properties
14967 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14968 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14969 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14970 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14971 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14972 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14973 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14974 "Some properties that are used by Org-mode for various purposes.
14975 Being in this list makes sure that they are offered for completion.")
14977 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14978 "Regular expression matching the first line of a property drawer.")
14980 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14981 "Regular expression matching the last line of a property drawer.")
14983 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14984 "Regular expression matching the first line of a property drawer.")
14986 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14987 "Regular expression matching the first line of a property drawer.")
14989 (defconst org-property-drawer-re
14990 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14991 org-property-end-re "\\)\n?")
14992 "Matches an entire property drawer.")
14994 (defconst org-clock-drawer-re
14995 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14996 org-property-end-re "\\)\n?")
14997 "Matches an entire clock drawer.")
14999 (defsubst org-re-property (property)
15000 "Return a regexp matching a PROPERTY line.
15001 Match group 1 will be set to the value."
15002 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
15004 (defsubst org-re-property-keyword (property)
15005 "Return a regexp matching a PROPERTY line, possibly with no
15006 value for the property."
15007 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
15009 (defun org-property-action ()
15010 "Do an action on properties."
15011 (interactive)
15012 (let (c)
15013 (org-at-property-p)
15014 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15015 (setq c (read-char-exclusive))
15016 (cond
15017 ((equal c ?s)
15018 (call-interactively 'org-set-property))
15019 ((equal c ?d)
15020 (call-interactively 'org-delete-property))
15021 ((equal c ?D)
15022 (call-interactively 'org-delete-property-globally))
15023 ((equal c ?c)
15024 (call-interactively 'org-compute-property-at-point))
15025 (t (user-error "No such property action %c" c)))))
15027 (defun org-inc-effort ()
15028 "Increment the value of the effort property in the current entry."
15029 (interactive)
15030 (org-set-effort nil t))
15032 (defvar org-clock-effort) ;; Defined in org-clock.el
15033 (defvar org-clock-current-task) ;; Defined in org-clock.el
15034 (defun org-set-effort (&optional value increment)
15035 "Set the effort property of the current entry.
15036 With numerical prefix arg, use the nth allowed value, 0 stands for the
15037 10th allowed value.
15039 When INCREMENT is non-nil, set the property to the next allowed value."
15040 (interactive "P")
15041 (if (equal value 0) (setq value 10))
15042 (let* ((completion-ignore-case t)
15043 (prop org-effort-property)
15044 (cur (org-entry-get nil prop))
15045 (allowed (org-property-get-allowed-values nil prop 'table))
15046 (existing (mapcar 'list (org-property-values prop)))
15047 (heading (nth 4 (org-heading-components)))
15049 (val (cond
15050 ((stringp value) value)
15051 ((and allowed (integerp value))
15052 (or (car (nth (1- value) allowed))
15053 (car (org-last allowed))))
15054 ((and allowed increment)
15055 (or (caadr (member (list cur) allowed))
15056 (user-error "Allowed effort values are not set")))
15057 (allowed
15058 (message "Select 1-9,0, [RET%s]: %s"
15059 (if cur (concat "=" cur) "")
15060 (mapconcat 'car allowed " "))
15061 (setq rpl (read-char-exclusive))
15062 (if (equal rpl ?\r)
15064 (setq rpl (- rpl ?0))
15065 (if (equal rpl 0) (setq rpl 10))
15066 (if (and (> rpl 0) (<= rpl (length allowed)))
15067 (car (nth (1- rpl) allowed))
15068 (org-completing-read "Effort: " allowed nil))))
15070 (let (org-completion-use-ido org-completion-use-iswitchb)
15071 (org-completing-read
15072 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15073 (concat "[" cur "]") "")
15074 ": ")
15075 existing nil nil "" nil cur))))))
15076 (unless (equal (org-entry-get nil prop) val)
15077 (org-entry-put nil prop val))
15078 (save-excursion
15079 (org-back-to-heading t)
15080 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
15081 (when (string= heading org-clock-current-task)
15082 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
15083 (org-clock-update-mode-line))
15084 (message "%s is now %s" prop val)))
15086 (defun org-at-property-p ()
15087 "Is cursor inside a property drawer?"
15088 (save-excursion
15089 (beginning-of-line 1)
15090 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
15091 (save-match-data ;; Used by calling procedures
15092 (let ((p (point))
15093 (range (unless (org-before-first-heading-p)
15094 (org-get-property-block))))
15095 (and range (<= (car range) p) (< p (cdr range))))))))
15097 (defun org-get-property-block (&optional beg end force)
15098 "Return the (beg . end) range of the body of the property drawer.
15099 BEG and END are the beginning and end of the current subtree, or of
15100 the part before the first headline. If they are not given, they will
15101 be found. If the drawer does not exist and FORCE is non-nil, create
15102 the drawer."
15103 (catch 'exit
15104 (save-excursion
15105 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15106 (progn (org-back-to-heading t) (point))))
15107 (end (or end (and (not (outline-next-heading)) (point-max))
15108 (point))))
15109 (goto-char beg)
15110 (if (re-search-forward org-property-start-re end t)
15111 (setq beg (1+ (match-end 0)))
15112 (if force
15113 (save-excursion
15114 (org-insert-property-drawer)
15115 (setq end (progn (outline-next-heading) (point))))
15116 (throw 'exit nil))
15117 (goto-char beg)
15118 (if (re-search-forward org-property-start-re end t)
15119 (setq beg (1+ (match-end 0)))))
15120 (if (re-search-forward org-property-end-re end t)
15121 (setq end (match-beginning 0))
15122 (or force (throw 'exit nil))
15123 (goto-char beg)
15124 (setq end beg)
15125 (org-indent-line)
15126 (insert ":END:\n"))
15127 (cons beg end)))))
15129 (defun org-entry-properties (&optional pom which specific)
15130 "Get all properties of the entry at point-or-marker POM.
15131 This includes the TODO keyword, the tags, time strings for deadline,
15132 scheduled, and clocking, and any additional properties defined in the
15133 entry. The return value is an alist, keys may occur multiple times
15134 if the property key was used several times.
15135 POM may also be nil, in which case the current entry is used.
15136 If WHICH is nil or `all', get all properties. If WHICH is
15137 `special' or `standard', only get that subclass. If WHICH
15138 is a string only get exactly this property. SPECIFIC can be a string, the
15139 specific property we are interested in. Specifying it can speed
15140 things up because then unnecessary parsing is avoided."
15141 (setq which (or which 'all))
15142 (org-with-point-at pom
15143 (let ((clockstr (substring org-clock-string 0 -1))
15144 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15145 (case-fold-search nil)
15146 beg end range props sum-props key key1 value string clocksum clocksumt)
15147 (save-excursion
15148 (when (condition-case nil
15149 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
15150 (error nil))
15151 (setq beg (point))
15152 (setq sum-props (get-text-property (point) 'org-summaries))
15153 (setq clocksum (get-text-property (point) :org-clock-minutes)
15154 clocksumt (get-text-property (point) :org-clock-minutes-today))
15155 (outline-next-heading)
15156 (setq end (point))
15157 (when (memq which '(all special))
15158 ;; Get the special properties, like TODO and tags
15159 (goto-char beg)
15160 (when (and (or (not specific) (string= specific "TODO"))
15161 (looking-at org-todo-line-regexp) (match-end 2))
15162 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15163 (when (and (or (not specific) (string= specific "PRIORITY"))
15164 (looking-at org-priority-regexp))
15165 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15166 (when (or (not specific) (string= specific "FILE"))
15167 (push (cons "FILE" buffer-file-name) props))
15168 (when (and (or (not specific) (string= specific "TAGS"))
15169 (setq value (org-get-tags-string))
15170 (string-match "\\S-" value))
15171 (push (cons "TAGS" value) props))
15172 (when (and (or (not specific) (string= specific "ALLTAGS"))
15173 (setq value (org-get-tags-at)))
15174 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15175 ":"))
15176 props))
15177 (when (or (not specific) (string= specific "BLOCKED"))
15178 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15179 (when (or (not specific)
15180 (member specific
15181 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15182 "TIMESTAMP" "TIMESTAMP_IA")))
15183 (catch 'match
15184 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15185 (setq key (if (match-end 1)
15186 (substring (org-match-string-no-properties 1)
15187 0 -1))
15188 string (if (equal key clockstr)
15189 (org-trim
15190 (buffer-substring-no-properties
15191 (match-beginning 3) (goto-char
15192 (point-at-eol))))
15193 (substring (org-match-string-no-properties 3)
15194 1 -1)))
15195 ;; Get the correct property name from the key. This is
15196 ;; necessary if the user has configured time keywords.
15197 (setq key1 (concat key ":"))
15198 (cond
15199 ((not key)
15200 (setq key
15201 (if (= (char-after (match-beginning 3)) ?\[)
15202 "TIMESTAMP_IA" "TIMESTAMP")))
15203 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15204 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15205 ((equal key1 org-closed-string) (setq key "CLOSED"))
15206 ((equal key1 org-clock-string) (setq key "CLOCK")))
15207 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15208 (progn
15209 (push (cons key string) props)
15210 ;; no need to search further if match is found
15211 (throw 'match t))
15212 (when (or (equal key "CLOCK") (not (assoc key props)))
15213 (push (cons key string) props)))))))
15215 (when (memq which '(all standard))
15216 ;; Get the standard properties, like :PROP: ...
15217 (setq range (org-get-property-block beg end))
15218 (when range
15219 (goto-char (car range))
15220 (while (re-search-forward
15221 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
15222 (cdr range) t)
15223 (setq key (org-match-string-no-properties 1)
15224 value (org-trim (or (org-match-string-no-properties 2) "")))
15225 (unless (member key excluded)
15226 (push (cons key (or value "")) props)))))
15227 (if clocksum
15228 (push (cons "CLOCKSUM"
15229 (org-columns-number-to-string (/ (float clocksum) 60.)
15230 'add_times))
15231 props))
15232 (if clocksumt
15233 (push (cons "CLOCKSUM_T"
15234 (org-columns-number-to-string (/ (float clocksumt) 60.)
15235 'add_times))
15236 props))
15237 (unless (assoc "CATEGORY" props)
15238 (push (cons "CATEGORY" (org-get-category)) props))
15239 (append sum-props (nreverse props)))))))
15241 (defun org-entry-get (pom property &optional inherit literal-nil)
15242 "Get value of PROPERTY for entry or content at point-or-marker POM.
15243 If INHERIT is non-nil and the entry does not have the property,
15244 then also check higher levels of the hierarchy.
15245 If INHERIT is the symbol `selective', use inheritance only if the setting
15246 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15247 If the property is present but empty, the return value is the empty string.
15248 If the property is not present at all, nil is returned.
15250 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15251 do not interpret it as the list atom nil. This is used for inheritance
15252 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15253 (org-with-point-at pom
15254 (if (and inherit (if (eq inherit 'selective)
15255 (org-property-inherit-p property)
15257 (org-entry-get-with-inheritance property literal-nil)
15258 (if (member property org-special-properties)
15259 ;; We need a special property. Use `org-entry-properties' to
15260 ;; retrieve it, but specify the wanted property
15261 (cdr (assoc property (org-entry-properties nil 'special property)))
15262 (let ((range (org-get-property-block)))
15263 (when (and range (not (eq (car range) (cdr range))))
15264 (let* ((props (list (or (assoc property org-file-properties)
15265 (assoc property org-global-properties)
15266 (assoc property org-global-properties-fixed))))
15267 (ap (lambda (key)
15268 (when (re-search-forward
15269 (org-re-property key) (cdr range) t)
15270 (setq props
15271 (org-update-property-plist
15273 (if (match-end 1)
15274 (org-match-string-no-properties 1) "")
15275 props)))))
15276 val)
15277 (goto-char (car range))
15278 (funcall ap property)
15279 (goto-char (car range))
15280 (while (funcall ap (concat property "+")))
15281 (setq val (cdr (assoc property props)))
15282 (when val (if literal-nil val (org-not-nil val))))))))))
15284 (defun org-property-or-variable-value (var &optional inherit)
15285 "Check if there is a property fixing the value of VAR.
15286 If yes, return this value. If not, return the current value of the variable."
15287 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15288 (if (and prop (stringp prop) (string-match "\\S-" prop))
15289 (read prop)
15290 (symbol-value var))))
15292 (defun org-entry-delete (pom property &optional delete-empty-drawer)
15293 "Delete the property PROPERTY from entry at point-or-marker POM.
15294 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15295 an empty drawer to delete."
15296 (org-with-point-at pom
15297 (if (member property org-special-properties)
15298 nil ; cannot delete these properties.
15299 (let ((range (org-get-property-block)))
15300 (if (and range
15301 (goto-char (car range))
15302 (re-search-forward
15303 (org-re-property property)
15304 (cdr range) t))
15305 (progn
15306 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15307 (and delete-empty-drawer
15308 (org-remove-empty-drawer-at
15309 delete-empty-drawer (car range)))
15311 nil)))))
15313 ;; Multi-values properties are properties that contain multiple values
15314 ;; These values are assumed to be single words, separated by whitespace.
15315 (defun org-entry-add-to-multivalued-property (pom property value)
15316 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15317 (let* ((old (org-entry-get pom property))
15318 (values (and old (org-split-string old "[ \t]"))))
15319 (setq value (org-entry-protect-space value))
15320 (unless (member value values)
15321 (setq values (append values (list value)))
15322 (org-entry-put pom property
15323 (mapconcat 'identity values " ")))))
15325 (defun org-entry-remove-from-multivalued-property (pom property value)
15326 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15327 (let* ((old (org-entry-get pom property))
15328 (values (and old (org-split-string old "[ \t]"))))
15329 (setq value (org-entry-protect-space value))
15330 (when (member value values)
15331 (setq values (delete value values))
15332 (org-entry-put pom property
15333 (mapconcat 'identity values " ")))))
15335 (defun org-entry-member-in-multivalued-property (pom property value)
15336 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15337 (let* ((old (org-entry-get pom property))
15338 (values (and old (org-split-string old "[ \t]"))))
15339 (setq value (org-entry-protect-space value))
15340 (member value values)))
15342 (defun org-entry-get-multivalued-property (pom property)
15343 "Return a list of values in a multivalued property."
15344 (let* ((value (org-entry-get pom property))
15345 (values (and value (org-split-string value "[ \t]"))))
15346 (mapcar 'org-entry-restore-space values)))
15348 (defun org-entry-put-multivalued-property (pom property &rest values)
15349 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15350 VALUES should be a list of strings. Spaces will be protected."
15351 (org-entry-put pom property
15352 (mapconcat 'org-entry-protect-space values " "))
15353 (let* ((value (org-entry-get pom property))
15354 (values (and value (org-split-string value "[ \t]"))))
15355 (mapcar 'org-entry-restore-space values)))
15357 (defun org-entry-protect-space (s)
15358 "Protect spaces and newline in string S."
15359 (while (string-match " " s)
15360 (setq s (replace-match "%20" t t s)))
15361 (while (string-match "\n" s)
15362 (setq s (replace-match "%0A" t t s)))
15365 (defun org-entry-restore-space (s)
15366 "Restore spaces and newline in string S."
15367 (while (string-match "%20" s)
15368 (setq s (replace-match " " t t s)))
15369 (while (string-match "%0A" s)
15370 (setq s (replace-match "\n" t t s)))
15373 (defvar org-entry-property-inherited-from (make-marker)
15374 "Marker pointing to the entry from where a property was inherited.
15375 Each call to `org-entry-get-with-inheritance' will set this marker to the
15376 location of the entry where the inheritance search matched. If there was
15377 no match, the marker will point nowhere.
15378 Note that also `org-entry-get' calls this function, if the INHERIT flag
15379 is set.")
15381 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15382 "Get PROPERTY of entry or content at point, search higher levels if needed.
15383 The search will stop at the first ancestor which has the property defined.
15384 If the value found is \"nil\", return nil to show that the property
15385 should be considered as undefined (this is the meaning of nil here).
15386 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15387 (move-marker org-entry-property-inherited-from nil)
15388 (let (tmp)
15389 (save-excursion
15390 (save-restriction
15391 (widen)
15392 (catch 'ex
15393 (while t
15394 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
15395 (or (ignore-errors (org-back-to-heading t))
15396 (goto-char (point-min)))
15397 (move-marker org-entry-property-inherited-from (point))
15398 (throw 'ex tmp))
15399 (or (ignore-errors (org-up-heading-safe))
15400 (throw 'ex nil))))))
15401 (setq tmp (or tmp
15402 (cdr (assoc property org-file-properties))
15403 (cdr (assoc property org-global-properties))
15404 (cdr (assoc property org-global-properties-fixed))))
15405 (if literal-nil tmp (org-not-nil tmp))))
15407 (defvar org-property-changed-functions nil
15408 "Hook called when the value of a property has changed.
15409 Each hook function should accept two arguments, the name of the property
15410 and the new value.")
15412 (defun org-entry-put (pom property value)
15413 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15414 (org-with-point-at pom
15415 (org-back-to-heading t)
15416 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15417 range)
15418 (cond
15419 ((equal property "TODO")
15420 (when (and (stringp value) (string-match "\\S-" value)
15421 (not (member value org-todo-keywords-1)))
15422 (user-error "\"%s\" is not a valid TODO state" value))
15423 (if (or (not value)
15424 (not (string-match "\\S-" value)))
15425 (setq value 'none))
15426 (org-todo value)
15427 (org-set-tags nil 'align))
15428 ((equal property "PRIORITY")
15429 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15430 (string-to-char value) ?\ ))
15431 (org-set-tags nil 'align))
15432 ((equal property "CLOCKSUM")
15433 (if (not (re-search-forward
15434 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15435 (error "Cannot find a clock log")
15436 (goto-char (- (match-end 1) 2))
15437 (cond
15438 ((eq value 'earlier) (org-timestamp-down))
15439 ((eq value 'later) (org-timestamp-up)))
15440 (org-clock-sum-current-item)))
15441 ((equal property "SCHEDULED")
15442 (if (re-search-forward org-scheduled-time-regexp end t)
15443 (cond
15444 ((eq value 'earlier) (org-timestamp-change -1 'day))
15445 ((eq value 'later) (org-timestamp-change 1 'day))
15446 (t (call-interactively 'org-schedule)))
15447 (call-interactively 'org-schedule)))
15448 ((equal property "DEADLINE")
15449 (if (re-search-forward org-deadline-time-regexp end t)
15450 (cond
15451 ((eq value 'earlier) (org-timestamp-change -1 'day))
15452 ((eq value 'later) (org-timestamp-change 1 'day))
15453 (t (call-interactively 'org-deadline)))
15454 (call-interactively 'org-deadline)))
15455 ((member property org-special-properties)
15456 (error "The %s property can not yet be set with `org-entry-put'"
15457 property))
15458 (t ; a non-special property
15459 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15460 (setq range (org-get-property-block beg end 'force))
15461 (goto-char (car range))
15462 (if (re-search-forward
15463 (org-re-property-keyword property) (cdr range) t)
15464 (progn
15465 (delete-region (match-beginning 0) (match-end 0))
15466 (goto-char (match-beginning 0)))
15467 (goto-char (cdr range))
15468 (insert "\n")
15469 (backward-char 1)
15470 (org-indent-line))
15471 (insert ":" property ":")
15472 (and value (insert " " value))
15473 (org-indent-line)))))
15474 (run-hook-with-args 'org-property-changed-functions property value)))
15476 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15477 "Get all property keys in the current buffer.
15478 With INCLUDE-SPECIALS, also list the special properties that reflect things
15479 like tags and TODO state.
15480 With INCLUDE-DEFAULTS, also include properties that has special meaning
15481 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15482 and others.
15483 With INCLUDE-COLUMNS, also include property names given in COLUMN
15484 formats in the current buffer."
15485 (let (rtn range cfmt s p)
15486 (save-excursion
15487 (save-restriction
15488 (widen)
15489 (goto-char (point-min))
15490 (while (re-search-forward org-property-start-re nil t)
15491 (setq range (org-get-property-block))
15492 (goto-char (car range))
15493 (while (re-search-forward
15494 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
15495 (cdr range) t)
15496 (add-to-list 'rtn (org-match-string-no-properties 1)))
15497 (outline-next-heading))))
15499 (when include-specials
15500 (setq rtn (append org-special-properties rtn)))
15502 (when include-defaults
15503 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15504 (add-to-list 'rtn org-effort-property))
15506 (when include-columns
15507 (save-excursion
15508 (save-restriction
15509 (widen)
15510 (goto-char (point-min))
15511 (while (re-search-forward
15512 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15513 nil t)
15514 (setq cfmt (match-string 2) s 0)
15515 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15516 cfmt s)
15517 (setq s (match-end 0)
15518 p (match-string 1 cfmt))
15519 (unless (or (equal p "ITEM")
15520 (member p org-special-properties))
15521 (add-to-list 'rtn (match-string 1 cfmt))))))))
15523 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15525 (defun org-property-values (key)
15526 "Return a list of all values of property KEY in the current buffer."
15527 (save-excursion
15528 (save-restriction
15529 (widen)
15530 (goto-char (point-min))
15531 (let ((re (org-re-property key))
15532 values)
15533 (while (re-search-forward re nil t)
15534 (add-to-list 'values (org-trim (match-string 1))))
15535 (delete "" values)))))
15537 (defun org-insert-property-drawer ()
15538 "Insert a property drawer into the current entry."
15539 (org-back-to-heading t)
15540 (looking-at org-outline-regexp)
15541 (let ((indent (if org-adapt-indentation
15542 (- (match-end 0) (match-beginning 0))
15544 (beg (point))
15545 (re (concat "^[ \t]*" org-keyword-time-regexp))
15546 end hiddenp)
15547 (outline-next-heading)
15548 (setq end (point))
15549 (goto-char beg)
15550 (while (re-search-forward re end t))
15551 (setq hiddenp (outline-invisible-p))
15552 (end-of-line 1)
15553 (and (equal (char-after) ?\n) (forward-char 1))
15554 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15555 (if (member (match-string 1) '("CLOCK:" ":END:"))
15556 ;; just skip this line
15557 (beginning-of-line 2)
15558 ;; Drawer start, find the end
15559 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15560 (beginning-of-line 1)))
15561 (org-skip-over-state-notes)
15562 (skip-chars-backward " \t\n\r")
15563 (if (eq (char-before) ?*) (forward-char 1))
15564 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15565 (beginning-of-line 0)
15566 (org-indent-to-column indent)
15567 (beginning-of-line 2)
15568 (org-indent-to-column indent)
15569 (beginning-of-line 0)
15570 (if hiddenp
15571 (save-excursion
15572 (org-back-to-heading t)
15573 (hide-entry))
15574 (org-flag-drawer t))))
15576 (defun org-insert-drawer (&optional arg drawer)
15577 "Insert a drawer at point.
15579 Optional argument DRAWER, when non-nil, is a string representing
15580 drawer's name. Otherwise, the user is prompted for a name.
15582 If a region is active, insert the drawer around that region
15583 instead.
15585 Point is left between drawer's boundaries."
15586 (interactive "P")
15587 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15588 "LOGBOOK"))
15589 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15590 ;; internally by Org. They are meant to be inserted
15591 ;; automatically.
15592 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15593 ;; Remove system drawers from list. Note: For some reason,
15594 ;; `org-completing-read' ignores the predicate while
15595 ;; `completing-read' handles it fine.
15596 (drawer (if arg "PROPERTIES"
15597 (or drawer
15598 (completing-read
15599 "Drawer: " org-drawers
15600 (lambda (d) (not (member d system-drawers))))))))
15601 (cond
15602 ;; With C-u, fall back on `org-insert-property-drawer'
15603 (arg (org-insert-property-drawer))
15604 ;; With an active region, insert a drawer at point.
15605 ((not (org-region-active-p))
15606 (progn
15607 (unless (bolp) (insert "\n"))
15608 (insert (format ":%s:\n\n:END:\n" drawer))
15609 (forward-line -2)))
15610 ;; Otherwise, insert the drawer at point
15612 (let ((rbeg (region-beginning))
15613 (rend (copy-marker (region-end))))
15614 (unwind-protect
15615 (progn
15616 (goto-char rbeg)
15617 (beginning-of-line)
15618 (when (save-excursion
15619 (re-search-forward org-outline-regexp-bol rend t))
15620 (user-error "Drawers cannot contain headlines"))
15621 ;; Position point at the beginning of the first
15622 ;; non-blank line in region. Insert drawer's opening
15623 ;; there, then indent it.
15624 (org-skip-whitespace)
15625 (beginning-of-line)
15626 (insert ":" drawer ":\n")
15627 (forward-line -1)
15628 (indent-for-tab-command)
15629 ;; Move point to the beginning of the first blank line
15630 ;; after the last non-blank line in region. Insert
15631 ;; drawer's closing, then indent it.
15632 (goto-char rend)
15633 (skip-chars-backward " \r\t\n")
15634 (insert "\n:END:")
15635 (deactivate-mark t)
15636 (indent-for-tab-command)
15637 (unless (eolp) (insert "\n")))
15638 ;; Clear marker, whatever the outcome of insertion is.
15639 (set-marker rend nil)))))))
15641 (defvar org-property-set-functions-alist nil
15642 "Property set function alist.
15643 Each entry should have the following format:
15645 (PROPERTY . READ-FUNCTION)
15647 The read function will be called with the same argument as
15648 `org-completing-read'.")
15650 (defun org-set-property-function (property)
15651 "Get the function that should be used to set PROPERTY.
15652 This is computed according to `org-property-set-functions-alist'."
15653 (or (cdr (assoc property org-property-set-functions-alist))
15654 'org-completing-read))
15656 (defun org-read-property-value (property)
15657 "Read PROPERTY value from user."
15658 (let* ((completion-ignore-case t)
15659 (allowed (org-property-get-allowed-values nil property 'table))
15660 (cur (org-entry-get nil property))
15661 (prompt (concat property " value"
15662 (if (and cur (string-match "\\S-" cur))
15663 (concat " [" cur "]") "") ": "))
15664 (set-function (org-set-property-function property))
15665 (val (if allowed
15666 (funcall set-function prompt allowed nil
15667 (not (get-text-property 0 'org-unrestricted
15668 (caar allowed))))
15669 (let (org-completion-use-ido org-completion-use-iswitchb)
15670 (funcall set-function prompt
15671 (mapcar 'list (org-property-values property))
15672 nil nil "" nil cur)))))
15673 (if (equal val "")
15675 val)))
15677 (defvar org-last-set-property nil)
15678 (defvar org-last-set-property-value nil)
15679 (defun org-read-property-name ()
15680 "Read a property name."
15681 (let* ((completion-ignore-case t)
15682 (keys (org-buffer-property-keys nil t t))
15683 (default-prop (or (save-excursion
15684 (save-match-data
15685 (beginning-of-line)
15686 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15687 (null (string= (match-string 1) "END"))
15688 (match-string 1))))
15689 org-last-set-property))
15690 (property (org-icompleting-read
15691 (concat "Property"
15692 (if default-prop (concat " [" default-prop "]") "")
15693 ": ")
15694 (mapcar 'list keys)
15695 nil nil nil nil
15696 default-prop)))
15697 (if (member property keys)
15698 property
15699 (or (cdr (assoc (downcase property)
15700 (mapcar (lambda (x) (cons (downcase x) x))
15701 keys)))
15702 property))))
15704 (defun org-set-property-and-value (use-last)
15705 "Allow to set [PROPERTY]: [value] direction from prompt.
15706 When use-default, don't even ask, just use the last
15707 \"[PROPERTY]: [value]\" string from the history."
15708 (interactive "P")
15709 (let* ((completion-ignore-case t)
15710 (pv (or (and use-last org-last-set-property-value)
15711 (org-completing-read
15712 "Enter a \"[Property]: [value]\" pair: "
15713 nil nil nil nil nil
15714 org-last-set-property-value)))
15715 prop val)
15716 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15717 (setq prop (match-string 1 pv)
15718 val (match-string 2 pv))
15719 (org-set-property prop val))))
15721 (defun org-set-property (property value)
15722 "In the current entry, set PROPERTY to VALUE.
15723 When called interactively, this will prompt for a property name, offering
15724 completion on existing and default properties. And then it will prompt
15725 for a value, offering completion either on allowed values (via an inherited
15726 xxx_ALL property) or on existing values in other instances of this property
15727 in the current file."
15728 (interactive (list nil nil))
15729 (let* ((property (or property (org-read-property-name)))
15730 (value (or value (org-read-property-value property)))
15731 (fn (cdr (assoc property org-properties-postprocess-alist))))
15732 (setq org-last-set-property property)
15733 (setq org-last-set-property-value (concat property ": " value))
15734 ;; Possibly postprocess the inserted value:
15735 (when fn (setq value (funcall fn value)))
15736 (unless (equal (org-entry-get nil property) value)
15737 (org-entry-put nil property value))))
15739 (defun org-delete-property (property &optional delete-empty-drawer)
15740 "In the current entry, delete PROPERTY.
15741 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15742 an empty drawer to delete."
15743 (interactive
15744 (let* ((completion-ignore-case t)
15745 (prop (org-icompleting-read "Property: "
15746 (org-entry-properties nil 'standard))))
15747 (list prop)))
15748 (message "Property %s %s" property
15749 (if (org-entry-delete nil property delete-empty-drawer)
15750 "deleted"
15751 "was not present in the entry")))
15753 (defun org-delete-property-globally (property)
15754 "Remove PROPERTY globally, from all entries."
15755 (interactive
15756 (let* ((completion-ignore-case t)
15757 (prop (org-icompleting-read
15758 "Globally remove property: "
15759 (mapcar 'list (org-buffer-property-keys)))))
15760 (list prop)))
15761 (save-excursion
15762 (save-restriction
15763 (widen)
15764 (goto-char (point-min))
15765 (let ((cnt 0))
15766 (while (re-search-forward
15767 (org-re-property property)
15768 nil t)
15769 (setq cnt (1+ cnt))
15770 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15771 (message "Property \"%s\" removed from %d entries" property cnt)))))
15773 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15775 (defun org-compute-property-at-point ()
15776 "Compute the property at point.
15777 This looks for an enclosing column format, extracts the operator and
15778 then applies it to the property in the column format's scope."
15779 (interactive)
15780 (unless (org-at-property-p)
15781 (user-error "Not at a property"))
15782 (let ((prop (org-match-string-no-properties 2)))
15783 (org-columns-get-format-and-top-level)
15784 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15785 (user-error "No operator defined for property %s" prop))
15786 (org-columns-compute prop)))
15788 (defvar org-property-allowed-value-functions nil
15789 "Hook for functions supplying allowed values for a specific property.
15790 The functions must take a single argument, the name of the property, and
15791 return a flat list of allowed values. If \":ETC\" is one of
15792 the values, this means that these values are intended as defaults for
15793 completion, but that other values should be allowed too.
15794 The functions must return nil if they are not responsible for this
15795 property.")
15797 (defun org-property-get-allowed-values (pom property &optional table)
15798 "Get allowed values for the property PROPERTY.
15799 When TABLE is non-nil, return an alist that can directly be used for
15800 completion."
15801 (let (vals)
15802 (cond
15803 ((equal property "TODO")
15804 (setq vals (org-with-point-at pom
15805 (append org-todo-keywords-1 '("")))))
15806 ((equal property "PRIORITY")
15807 (let ((n org-lowest-priority))
15808 (while (>= n org-highest-priority)
15809 (push (char-to-string n) vals)
15810 (setq n (1- n)))))
15811 ((member property org-special-properties))
15812 ((setq vals (run-hook-with-args-until-success
15813 'org-property-allowed-value-functions property)))
15815 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15816 (when (and vals (string-match "\\S-" vals))
15817 (setq vals (car (read-from-string (concat "(" vals ")"))))
15818 (setq vals (mapcar (lambda (x)
15819 (cond ((stringp x) x)
15820 ((numberp x) (number-to-string x))
15821 ((symbolp x) (symbol-name x))
15822 (t "???")))
15823 vals)))))
15824 (when (member ":ETC" vals)
15825 (setq vals (remove ":ETC" vals))
15826 (org-add-props (car vals) '(org-unrestricted t)))
15827 (if table (mapcar 'list vals) vals)))
15829 (defun org-property-previous-allowed-value (&optional previous)
15830 "Switch to the next allowed value for this property."
15831 (interactive)
15832 (org-property-next-allowed-value t))
15834 (defun org-property-next-allowed-value (&optional previous)
15835 "Switch to the next allowed value for this property."
15836 (interactive)
15837 (unless (org-at-property-p)
15838 (user-error "Not at a property"))
15839 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15840 (key (match-string 2))
15841 (value (match-string 3))
15842 (allowed (or (org-property-get-allowed-values (point) key)
15843 (and (member value '("[ ]" "[-]" "[X]"))
15844 '("[ ]" "[X]"))))
15845 (heading (save-match-data (nth 4 (org-heading-components))))
15846 nval)
15847 (unless allowed
15848 (user-error "Allowed values for this property have not been defined"))
15849 (if previous (setq allowed (reverse allowed)))
15850 (if (member value allowed)
15851 (setq nval (car (cdr (member value allowed)))))
15852 (setq nval (or nval (car allowed)))
15853 (if (equal nval value)
15854 (user-error "Only one allowed value for this property"))
15855 (org-at-property-p)
15856 (replace-match (concat " :" key ": " nval) t t)
15857 (org-indent-line)
15858 (beginning-of-line 1)
15859 (skip-chars-forward " \t")
15860 (when (equal prop org-effort-property)
15861 (save-excursion
15862 (org-back-to-heading t)
15863 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
15864 (when (string= org-clock-current-task heading)
15865 (setq org-clock-effort nval)
15866 (org-clock-update-mode-line)))
15867 (run-hook-with-args 'org-property-changed-functions key nval)))
15869 (defun org-find-olp (path &optional this-buffer)
15870 "Return a marker pointing to the entry at outline path OLP.
15871 If anything goes wrong, throw an error.
15872 You can wrap this call to catch the error like this:
15874 (condition-case msg
15875 (org-mobile-locate-entry (match-string 4))
15876 (error (nth 1 msg)))
15878 The return value will then be either a string with the error message,
15879 or a marker if everything is OK.
15881 If THIS-BUFFER is set, the outline path does not contain a file,
15882 only headings."
15883 (let* ((file (if this-buffer buffer-file-name (pop path)))
15884 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15885 (level 1)
15886 (lmin 1)
15887 (lmax 1)
15888 limit re end found pos heading cnt flevel)
15889 (unless buffer (error "File not found :%s" file))
15890 (with-current-buffer buffer
15891 (save-excursion
15892 (save-restriction
15893 (widen)
15894 (setq limit (point-max))
15895 (goto-char (point-min))
15896 (while (setq heading (pop path))
15897 (setq re (format org-complex-heading-regexp-format
15898 (regexp-quote heading)))
15899 (setq cnt 0 pos (point))
15900 (while (re-search-forward re end t)
15901 (setq level (- (match-end 1) (match-beginning 1)))
15902 (if (and (>= level lmin) (<= level lmax))
15903 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15904 (when (= cnt 0) (error "Heading not found on level %d: %s"
15905 lmax heading))
15906 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15907 lmax heading))
15908 (goto-char found)
15909 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15910 (setq end (save-excursion (org-end-of-subtree t t))))
15911 (when (org-at-heading-p)
15912 (point-marker)))))))
15914 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15915 "Find node HEADING in BUFFER.
15916 Return a marker to the heading if it was found, or nil if not.
15917 If POS-ONLY is set, return just the position instead of a marker.
15919 The heading text must match exact, but it may have a TODO keyword,
15920 a priority cookie and tags in the standard locations."
15921 (with-current-buffer (or buffer (current-buffer))
15922 (save-excursion
15923 (save-restriction
15924 (widen)
15925 (goto-char (point-min))
15926 (let (case-fold-search)
15927 (if (re-search-forward
15928 (format org-complex-heading-regexp-format
15929 (regexp-quote heading)) nil t)
15930 (if pos-only
15931 (match-beginning 0)
15932 (move-marker (make-marker) (match-beginning 0)))))))))
15934 (defun org-find-exact-heading-in-directory (heading &optional dir)
15935 "Find Org node headline HEADING in all .org files in directory DIR.
15936 When the target headline is found, return a marker to this location."
15937 (let ((files (directory-files (or dir default-directory)
15938 nil "\\`[^.#].*\\.org\\'"))
15939 file visiting m buffer)
15940 (catch 'found
15941 (while (setq file (pop files))
15942 (message "trying %s" file)
15943 (setq visiting (org-find-base-buffer-visiting file))
15944 (setq buffer (or visiting (find-file-noselect file)))
15945 (setq m (org-find-exact-headline-in-buffer
15946 heading buffer))
15947 (when (and (not m) (not visiting)) (kill-buffer buffer))
15948 (and m (throw 'found m))))))
15950 (defun org-find-entry-with-id (ident)
15951 "Locate the entry that contains the ID property with exact value IDENT.
15952 IDENT can be a string, a symbol or a number, this function will search for
15953 the string representation of it.
15954 Return the position where this entry starts, or nil if there is no such entry."
15955 (interactive "sID: ")
15956 (let ((id (cond
15957 ((stringp ident) ident)
15958 ((symbol-name ident) (symbol-name ident))
15959 ((numberp ident) (number-to-string ident))
15960 (t (error "IDENT %s must be a string, symbol or number" ident))))
15961 (case-fold-search nil))
15962 (save-excursion
15963 (save-restriction
15964 (widen)
15965 (goto-char (point-min))
15966 (when (re-search-forward
15967 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15968 nil t)
15969 (org-back-to-heading t)
15970 (point))))))
15972 ;;;; Timestamps
15974 (defvar org-last-changed-timestamp nil)
15975 (defvar org-last-inserted-timestamp nil
15976 "The last time stamp inserted with `org-insert-time-stamp'.")
15977 (defvar org-time-was-given) ; dynamically scoped parameter
15978 (defvar org-end-time-was-given) ; dynamically scoped parameter
15979 (defvar org-ts-what) ; dynamically scoped parameter
15981 (defun org-time-stamp (arg &optional inactive)
15982 "Prompt for a date/time and insert a time stamp.
15983 If the user specifies a time like HH:MM or if this command is
15984 called with at least one prefix argument, the time stamp contains
15985 the date and the time. Otherwise, only the date is be included.
15987 All parts of a date not specified by the user is filled in from
15988 the current date/time. So if you just press return without
15989 typing anything, the time stamp will represent the current
15990 date/time.
15992 If there is already a timestamp at the cursor, it will be
15993 modified.
15995 With two universal prefix arguments, insert an active timestamp
15996 with the current time without prompting the user."
15997 (interactive "P")
15998 (let* ((ts nil)
15999 (default-time
16000 ;; Default time is either today, or, when entering a range,
16001 ;; the range start.
16002 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16003 (save-excursion
16004 (re-search-backward
16005 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16006 (- (point) 20) t)))
16007 (apply 'encode-time (org-parse-time-string (match-string 1)))
16008 (current-time)))
16009 (default-input (and ts (org-get-compact-tod ts)))
16010 (repeater (save-excursion
16011 (save-match-data
16012 (beginning-of-line)
16013 (when (re-search-forward
16014 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16015 (save-excursion (progn (end-of-line) (point))) t)
16016 (match-string 0)))))
16017 org-time-was-given org-end-time-was-given time)
16018 (cond
16019 ((and (org-at-timestamp-p t)
16020 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16021 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16022 (insert "--")
16023 (setq time (let ((this-command this-command))
16024 (org-read-date arg 'totime nil nil
16025 default-time default-input inactive)))
16026 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16027 ((org-at-timestamp-p t)
16028 (setq time (let ((this-command this-command))
16029 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16030 (when (org-at-timestamp-p t) ; just to get the match data
16031 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16032 (replace-match "")
16033 (setq org-last-changed-timestamp
16034 (org-insert-time-stamp
16035 time (or org-time-was-given arg)
16036 inactive nil nil (list org-end-time-was-given)))
16037 (when repeater (goto-char (1- (point))) (insert " " repeater)
16038 (setq org-last-changed-timestamp
16039 (concat (substring org-last-inserted-timestamp 0 -1)
16040 " " repeater ">"))))
16041 (message "Timestamp updated"))
16042 ((equal arg '(16))
16043 (org-insert-time-stamp (current-time) t))
16045 (setq time (let ((this-command this-command))
16046 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16047 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16048 nil nil (list org-end-time-was-given))))))
16050 ;; FIXME: can we use this for something else, like computing time differences?
16051 (defun org-get-compact-tod (s)
16052 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16053 (let* ((t1 (match-string 1 s))
16054 (h1 (string-to-number (match-string 2 s)))
16055 (m1 (string-to-number (match-string 3 s)))
16056 (t2 (and (match-end 4) (match-string 5 s)))
16057 (h2 (and t2 (string-to-number (match-string 6 s))))
16058 (m2 (and t2 (string-to-number (match-string 7 s))))
16059 dh dm)
16060 (if (not t2)
16062 (setq dh (- h2 h1) dm (- m2 m1))
16063 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16064 (concat t1 "+" (number-to-string dh)
16065 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
16067 (defun org-time-stamp-inactive (&optional arg)
16068 "Insert an inactive time stamp.
16069 An inactive time stamp is enclosed in square brackets instead of angle
16070 brackets. It is inactive in the sense that it does not trigger agenda entries,
16071 does not link to the calendar and cannot be changed with the S-cursor keys.
16072 So these are more for recording a certain time/date."
16073 (interactive "P")
16074 (org-time-stamp arg 'inactive))
16076 (defvar org-date-ovl (make-overlay 1 1))
16077 (overlay-put org-date-ovl 'face 'org-date-selected)
16078 (org-detach-overlay org-date-ovl)
16080 (defvar org-ans1) ; dynamically scoped parameter
16081 (defvar org-ans2) ; dynamically scoped parameter
16083 (defvar org-plain-time-of-day-regexp) ; defined below
16085 (defvar org-overriding-default-time nil) ; dynamically scoped
16086 (defvar org-read-date-overlay nil)
16087 (defvar org-dcst nil) ; dynamically scoped
16088 (defvar org-read-date-history nil)
16089 (defvar org-read-date-final-answer nil)
16090 (defvar org-read-date-analyze-futurep nil)
16091 (defvar org-read-date-analyze-forced-year nil)
16092 (defvar org-read-date-inactive)
16094 (defvar org-read-date-minibuffer-local-map
16095 (let ((map (make-sparse-keymap)))
16096 (set-keymap-parent map minibuffer-local-map)
16097 (org-defkey map (kbd ".")
16098 (lambda () (interactive)
16099 ;; Are we at the beginning of the prompt?
16100 (if (looking-back "^[^:]+: ")
16101 (org-eval-in-calendar '(calendar-goto-today))
16102 (insert "."))))
16103 (org-defkey map (kbd "C-.")
16104 (lambda () (interactive)
16105 (org-eval-in-calendar '(calendar-goto-today))))
16106 (org-defkey map [(meta shift left)]
16107 (lambda () (interactive)
16108 (org-eval-in-calendar '(calendar-backward-month 1))))
16109 (org-defkey map [(meta shift right)]
16110 (lambda () (interactive)
16111 (org-eval-in-calendar '(calendar-forward-month 1))))
16112 (org-defkey map [(meta shift up)]
16113 (lambda () (interactive)
16114 (org-eval-in-calendar '(calendar-backward-year 1))))
16115 (org-defkey map [(meta shift down)]
16116 (lambda () (interactive)
16117 (org-eval-in-calendar '(calendar-forward-year 1))))
16118 (org-defkey map [?\e (shift left)]
16119 (lambda () (interactive)
16120 (org-eval-in-calendar '(calendar-backward-month 1))))
16121 (org-defkey map [?\e (shift right)]
16122 (lambda () (interactive)
16123 (org-eval-in-calendar '(calendar-forward-month 1))))
16124 (org-defkey map [?\e (shift up)]
16125 (lambda () (interactive)
16126 (org-eval-in-calendar '(calendar-backward-year 1))))
16127 (org-defkey map [?\e (shift down)]
16128 (lambda () (interactive)
16129 (org-eval-in-calendar '(calendar-forward-year 1))))
16130 (org-defkey map [(shift up)]
16131 (lambda () (interactive)
16132 (org-eval-in-calendar '(calendar-backward-week 1))))
16133 (org-defkey map [(shift down)]
16134 (lambda () (interactive)
16135 (org-eval-in-calendar '(calendar-forward-week 1))))
16136 (org-defkey map [(shift left)]
16137 (lambda () (interactive)
16138 (org-eval-in-calendar '(calendar-backward-day 1))))
16139 (org-defkey map [(shift right)]
16140 (lambda () (interactive)
16141 (org-eval-in-calendar '(calendar-forward-day 1))))
16142 (org-defkey map "!"
16143 (lambda () (interactive)
16144 (org-eval-in-calendar '(diary-view-entries))
16145 (message "")))
16146 (org-defkey map ">"
16147 (lambda () (interactive)
16148 (org-eval-in-calendar '(scroll-calendar-left 1))))
16149 (org-defkey map "<"
16150 (lambda () (interactive)
16151 (org-eval-in-calendar '(scroll-calendar-right 1))))
16152 (org-defkey map "\C-v"
16153 (lambda () (interactive)
16154 (org-eval-in-calendar
16155 '(calendar-scroll-left-three-months 1))))
16156 (org-defkey map "\M-v"
16157 (lambda () (interactive)
16158 (org-eval-in-calendar
16159 '(calendar-scroll-right-three-months 1))))
16160 map)
16161 "Keymap for minibuffer commands when using `org-read-date'.")
16163 (defun org-read-date (&optional org-with-time to-time from-string prompt
16164 default-time default-input inactive)
16165 "Read a date, possibly a time, and make things smooth for the user.
16166 The prompt will suggest to enter an ISO date, but you can also enter anything
16167 which will at least partially be understood by `parse-time-string'.
16168 Unrecognized parts of the date will default to the current day, month, year,
16169 hour and minute. If this command is called to replace a timestamp at point,
16170 or to enter the second timestamp of a range, the default time is taken
16171 from the existing stamp. Furthermore, the command prefers the future,
16172 so if you are giving a date where the year is not given, and the day-month
16173 combination is already past in the current year, it will assume you
16174 mean next year. For details, see the manual. A few examples:
16176 3-2-5 --> 2003-02-05
16177 feb 15 --> currentyear-02-15
16178 2/15 --> currentyear-02-15
16179 sep 12 9 --> 2009-09-12
16180 12:45 --> today 12:45
16181 22 sept 0:34 --> currentyear-09-22 0:34
16182 12 --> currentyear-currentmonth-12
16183 Fri --> nearest Friday after today
16184 -Tue --> last Tuesday
16185 etc.
16187 Furthermore you can specify a relative date by giving, as the *first* thing
16188 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16189 change in days weeks, months, years.
16190 With a single plus or minus, the date is relative to today. With a double
16191 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16192 +4d --> four days from today
16193 +4 --> same as above
16194 +2w --> two weeks from today
16195 ++5 --> five days from default date
16197 The function understands only English month and weekday abbreviations.
16199 While prompting, a calendar is popped up - you can also select the
16200 date with the mouse (button 1). The calendar shows a period of three
16201 months. To scroll it to other months, use the keys `>' and `<'.
16202 If you don't like the calendar, turn it off with
16203 \(setq org-read-date-popup-calendar nil)
16205 With optional argument TO-TIME, the date will immediately be converted
16206 to an internal time.
16207 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16208 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16209 still enter a time, and this function will inform the calling routine
16210 about this change. The calling routine may then choose to change the
16211 format used to insert the time stamp into the buffer to include the time.
16212 With optional argument FROM-STRING, read from this string instead from
16213 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16214 the time/date that is used for everything that is not specified by the
16215 user."
16216 (require 'parse-time)
16217 (let* ((org-time-stamp-rounding-minutes
16218 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16219 (org-dcst org-display-custom-times)
16220 (ct (org-current-time))
16221 (org-def (or org-overriding-default-time default-time ct))
16222 (org-defdecode (decode-time org-def))
16223 (dummy (progn
16224 (when (< (nth 2 org-defdecode) org-extend-today-until)
16225 (setcar (nthcdr 2 org-defdecode) -1)
16226 (setcar (nthcdr 1 org-defdecode) 59)
16227 (setq org-def (apply 'encode-time org-defdecode)
16228 org-defdecode (decode-time org-def)))))
16229 (mouse-autoselect-window nil) ; Don't let the mouse jump
16230 (calendar-frame-setup nil)
16231 (calendar-setup nil)
16232 (calendar-move-hook nil)
16233 (calendar-view-diary-initially-flag nil)
16234 (calendar-view-holidays-initially-flag nil)
16235 (timestr (format-time-string
16236 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16237 (prompt (concat (if prompt (concat prompt " ") "")
16238 (format "Date+time [%s]: " timestr)))
16239 ans (org-ans0 "") org-ans1 org-ans2 final)
16241 (cond
16242 (from-string (setq ans from-string))
16243 (org-read-date-popup-calendar
16244 (save-excursion
16245 (save-window-excursion
16246 (calendar)
16247 (org-eval-in-calendar '(setq cursor-type nil) t)
16248 (unwind-protect
16249 (progn
16250 (calendar-forward-day (- (time-to-days org-def)
16251 (calendar-absolute-from-gregorian
16252 (calendar-current-date))))
16253 (org-eval-in-calendar nil t)
16254 (let* ((old-map (current-local-map))
16255 (map (copy-keymap calendar-mode-map))
16256 (minibuffer-local-map
16257 (copy-keymap org-read-date-minibuffer-local-map)))
16258 (org-defkey map (kbd "RET") 'org-calendar-select)
16259 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16260 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16261 (unwind-protect
16262 (progn
16263 (use-local-map map)
16264 (setq org-read-date-inactive inactive)
16265 (add-hook 'post-command-hook 'org-read-date-display)
16266 (setq org-ans0 (read-string prompt default-input
16267 'org-read-date-history nil))
16268 ;; org-ans0: from prompt
16269 ;; org-ans1: from mouse click
16270 ;; org-ans2: from calendar motion
16271 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16272 (remove-hook 'post-command-hook 'org-read-date-display)
16273 (use-local-map old-map)
16274 (when org-read-date-overlay
16275 (delete-overlay org-read-date-overlay)
16276 (setq org-read-date-overlay nil)))))
16277 (bury-buffer "*Calendar*")))))
16279 (t ; Naked prompt only
16280 (unwind-protect
16281 (setq ans (read-string prompt default-input
16282 'org-read-date-history timestr))
16283 (when org-read-date-overlay
16284 (delete-overlay org-read-date-overlay)
16285 (setq org-read-date-overlay nil)))))
16287 (setq final (org-read-date-analyze ans org-def org-defdecode))
16289 (when org-read-date-analyze-forced-year
16290 (message "Year was forced into %s"
16291 (if org-read-date-force-compatible-dates
16292 "compatible range (1970-2037)"
16293 "range representable on this machine"))
16294 (ding))
16296 ;; One round trip to get rid of 34th of August and stuff like that....
16297 (setq final (decode-time (apply 'encode-time final)))
16299 (setq org-read-date-final-answer ans)
16301 (if to-time
16302 (apply 'encode-time final)
16303 (if (and (boundp 'org-time-was-given) org-time-was-given)
16304 (format "%04d-%02d-%02d %02d:%02d"
16305 (nth 5 final) (nth 4 final) (nth 3 final)
16306 (nth 2 final) (nth 1 final))
16307 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16309 (defvar org-def)
16310 (defvar org-defdecode)
16311 (defvar org-with-time)
16312 (defun org-read-date-display ()
16313 "Display the current date prompt interpretation in the minibuffer."
16314 (when org-read-date-display-live
16315 (when org-read-date-overlay
16316 (delete-overlay org-read-date-overlay))
16317 (when (minibufferp (current-buffer))
16318 (save-excursion
16319 (end-of-line 1)
16320 (while (not (equal (buffer-substring
16321 (max (point-min) (- (point) 4)) (point))
16322 " "))
16323 (insert " ")))
16324 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16325 " " (or org-ans1 org-ans2)))
16326 (org-end-time-was-given nil)
16327 (f (org-read-date-analyze ans org-def org-defdecode))
16328 (fmts (if org-dcst
16329 org-time-stamp-custom-formats
16330 org-time-stamp-formats))
16331 (fmt (if (or org-with-time
16332 (and (boundp 'org-time-was-given) org-time-was-given))
16333 (cdr fmts)
16334 (car fmts)))
16335 (txt (format-time-string fmt (apply 'encode-time f)))
16336 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16337 (txt (concat "=> " txt)))
16338 (when (and org-end-time-was-given
16339 (string-match org-plain-time-of-day-regexp txt))
16340 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16341 org-end-time-was-given
16342 (substring txt (match-end 0)))))
16343 (when org-read-date-analyze-futurep
16344 (setq txt (concat txt " (=>F)")))
16345 (setq org-read-date-overlay
16346 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16347 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16349 (defun org-read-date-analyze (ans org-def org-defdecode)
16350 "Analyze the combined answer of the date prompt."
16351 ;; FIXME: cleanup and comment
16352 (let ((nowdecode (decode-time (current-time)))
16353 delta deltan deltaw deltadef year month day
16354 hour minute second wday pm h2 m2 tl wday1
16355 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16356 (setq org-read-date-analyze-futurep nil
16357 org-read-date-analyze-forced-year nil)
16358 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16359 (setq ans "+0"))
16361 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16362 (setq ans (replace-match "" t t ans)
16363 deltan (car delta)
16364 deltaw (nth 1 delta)
16365 deltadef (nth 2 delta)))
16367 ;; Check if there is an iso week date in there. If yes, store the
16368 ;; info and postpone interpreting it until the rest of the parsing
16369 ;; is done.
16370 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16371 (setq iso-year (if (match-end 1)
16372 (org-small-year-to-year
16373 (string-to-number (match-string 1 ans))))
16374 iso-weekday (if (match-end 3)
16375 (string-to-number (match-string 3 ans)))
16376 iso-week (string-to-number (match-string 2 ans)))
16377 (setq ans (replace-match "" t t ans)))
16379 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16380 (when (string-match
16381 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16382 (setq year (if (match-end 2)
16383 (string-to-number (match-string 2 ans))
16384 (progn (setq kill-year t)
16385 (string-to-number (format-time-string "%Y"))))
16386 month (string-to-number (match-string 3 ans))
16387 day (string-to-number (match-string 4 ans)))
16388 (if (< year 100) (setq year (+ 2000 year)))
16389 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16390 t nil ans)))
16392 ;; Help matching dotted european dates
16393 (when (string-match
16394 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16395 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16396 (setq kill-year t)
16397 (string-to-number (format-time-string "%Y")))
16398 day (string-to-number (match-string 1 ans))
16399 month (string-to-number (match-string 2 ans))
16400 ans (replace-match (format "%04d-%02d-%02d" year month day)
16401 t nil ans)))
16403 ;; Help matching american dates, like 5/30 or 5/30/7
16404 (when (string-match
16405 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16406 (setq year (if (match-end 4)
16407 (string-to-number (match-string 4 ans))
16408 (progn (setq kill-year t)
16409 (string-to-number (format-time-string "%Y"))))
16410 month (string-to-number (match-string 1 ans))
16411 day (string-to-number (match-string 2 ans)))
16412 (if (< year 100) (setq year (+ 2000 year)))
16413 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16414 t nil ans)))
16415 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16416 ;; If there is a time with am/pm, and *no* time without it, we convert
16417 ;; so that matching will be successful.
16418 (loop for i from 1 to 2 do ; twice, for end time as well
16419 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16420 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16421 (setq hour (string-to-number (match-string 1 ans))
16422 minute (if (match-end 3)
16423 (string-to-number (match-string 3 ans))
16425 pm (equal ?p
16426 (string-to-char (downcase (match-string 4 ans)))))
16427 (if (and (= hour 12) (not pm))
16428 (setq hour 0)
16429 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16430 (setq ans (replace-match (format "%02d:%02d" hour minute)
16431 t t ans))))
16433 ;; Check if a time range is given as a duration
16434 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16435 (setq hour (string-to-number (match-string 1 ans))
16436 h2 (+ hour (string-to-number (match-string 3 ans)))
16437 minute (string-to-number (match-string 2 ans))
16438 m2 (+ minute (if (match-end 5) (string-to-number
16439 (match-string 5 ans))0)))
16440 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16441 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16442 t t ans)))
16444 ;; Check if there is a time range
16445 (when (boundp 'org-end-time-was-given)
16446 (setq org-time-was-given nil)
16447 (when (and (string-match org-plain-time-of-day-regexp ans)
16448 (match-end 8))
16449 (setq org-end-time-was-given (match-string 8 ans))
16450 (setq ans (concat (substring ans 0 (match-beginning 7))
16451 (substring ans (match-end 7))))))
16453 (setq tl (parse-time-string ans)
16454 day (or (nth 3 tl) (nth 3 org-defdecode))
16455 month (or (nth 4 tl)
16456 (if (and org-read-date-prefer-future
16457 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16458 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16459 (nth 4 org-defdecode)))
16460 year (or (and (not kill-year) (nth 5 tl))
16461 (if (and org-read-date-prefer-future
16462 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16463 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16464 (nth 5 org-defdecode)))
16465 hour (or (nth 2 tl) (nth 2 org-defdecode))
16466 minute (or (nth 1 tl) (nth 1 org-defdecode))
16467 second (or (nth 0 tl) 0)
16468 wday (nth 6 tl))
16470 (when (and (eq org-read-date-prefer-future 'time)
16471 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16472 (equal day (nth 3 nowdecode))
16473 (equal month (nth 4 nowdecode))
16474 (equal year (nth 5 nowdecode))
16475 (nth 2 tl)
16476 (or (< (nth 2 tl) (nth 2 nowdecode))
16477 (and (= (nth 2 tl) (nth 2 nowdecode))
16478 (nth 1 tl)
16479 (< (nth 1 tl) (nth 1 nowdecode)))))
16480 (setq day (1+ day)
16481 futurep t))
16483 ;; Special date definitions below
16484 (cond
16485 (iso-week
16486 ;; There was an iso week
16487 (require 'cal-iso)
16488 (setq futurep nil)
16489 (setq year (or iso-year year)
16490 day (or iso-weekday wday 1)
16491 wday nil ; to make sure that the trigger below does not match
16492 iso-date (calendar-gregorian-from-absolute
16493 (calendar-absolute-from-iso
16494 (list iso-week day year))))
16495 ; FIXME: Should we also push ISO weeks into the future?
16496 ; (when (and org-read-date-prefer-future
16497 ; (not iso-year)
16498 ; (< (calendar-absolute-from-gregorian iso-date)
16499 ; (time-to-days (current-time))))
16500 ; (setq year (1+ year)
16501 ; iso-date (calendar-gregorian-from-absolute
16502 ; (calendar-absolute-from-iso
16503 ; (list iso-week day year)))))
16504 (setq month (car iso-date)
16505 year (nth 2 iso-date)
16506 day (nth 1 iso-date)))
16507 (deltan
16508 (setq futurep nil)
16509 (unless deltadef
16510 (let ((now (decode-time (current-time))))
16511 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16512 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16513 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16514 ((equal deltaw "m") (setq month (+ month deltan)))
16515 ((equal deltaw "y") (setq year (+ year deltan)))))
16516 ((and wday (not (nth 3 tl)))
16517 ;; Weekday was given, but no day, so pick that day in the week
16518 ;; on or after the derived date.
16519 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16520 (unless (equal wday wday1)
16521 (setq day (+ day (% (- wday wday1 -7) 7))))))
16522 (if (and (boundp 'org-time-was-given)
16523 (nth 2 tl))
16524 (setq org-time-was-given t))
16525 (if (< year 100) (setq year (+ 2000 year)))
16526 ;; Check of the date is representable
16527 (if org-read-date-force-compatible-dates
16528 (progn
16529 (if (< year 1970)
16530 (setq year 1970 org-read-date-analyze-forced-year t))
16531 (if (> year 2037)
16532 (setq year 2037 org-read-date-analyze-forced-year t)))
16533 (condition-case nil
16534 (ignore (encode-time second minute hour day month year))
16535 (error
16536 (setq year (nth 5 org-defdecode))
16537 (setq org-read-date-analyze-forced-year t))))
16538 (setq org-read-date-analyze-futurep futurep)
16539 (list second minute hour day month year)))
16541 (defvar parse-time-weekdays)
16542 (defun org-read-date-get-relative (s today default)
16543 "Check string S for special relative date string.
16544 TODAY and DEFAULT are internal times, for today and for a default.
16545 Return shift list (N what def-flag)
16546 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16547 N is the number of WHATs to shift.
16548 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16549 the DEFAULT date rather than TODAY."
16550 (require 'parse-time)
16551 (when (and
16552 (string-match
16553 (concat
16554 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16555 "\\([0-9]+\\)?"
16556 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16557 "\\([ \t]\\|$\\)") s)
16558 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16559 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16560 (string-to-char (substring (match-string 1 s) -1))
16561 ?+))
16562 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16563 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16564 (what (if (match-end 3) (match-string 3 s) "d"))
16565 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16566 (date (if rel default today))
16567 (wday (nth 6 (decode-time date)))
16568 delta)
16569 (if wday1
16570 (progn
16571 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16572 (if (= delta 0) (setq delta 7))
16573 (if (= dir ?-)
16574 (progn
16575 (setq delta (- delta 7))
16576 (if (= delta 0) (setq delta -7))))
16577 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16578 (list delta "d" rel))
16579 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16581 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16582 "Turn a user-specified date into the internal representation.
16583 The internal representation needed by the calendar is (month day year).
16584 This is a wrapper to handle the brain-dead convention in calendar that
16585 user function argument order change dependent on argument order."
16586 (if (boundp 'calendar-date-style)
16587 (cond
16588 ((eq calendar-date-style 'american)
16589 (list arg1 arg2 arg3))
16590 ((eq calendar-date-style 'european)
16591 (list arg2 arg1 arg3))
16592 ((eq calendar-date-style 'iso)
16593 (list arg2 arg3 arg1)))
16594 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16595 (if (org-bound-and-true-p european-calendar-style)
16596 (list arg2 arg1 arg3)
16597 (list arg1 arg2 arg3)))))
16599 (defun org-eval-in-calendar (form &optional keepdate)
16600 "Eval FORM in the calendar window and return to current window.
16601 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16602 otherwise stick to the current value of `org-ans2'."
16603 (let ((sf (selected-frame))
16604 (sw (selected-window)))
16605 (select-window (get-buffer-window "*Calendar*" t))
16606 (eval form)
16607 (when (and (not keepdate) (calendar-cursor-to-date))
16608 (let* ((date (calendar-cursor-to-date))
16609 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16610 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16611 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16612 (select-window sw)
16613 (org-select-frame-set-input-focus sf)))
16615 (defun org-calendar-select ()
16616 "Return to `org-read-date' with the date currently selected.
16617 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16618 (interactive)
16619 (when (calendar-cursor-to-date)
16620 (let* ((date (calendar-cursor-to-date))
16621 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16622 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16623 (if (active-minibuffer-window) (exit-minibuffer))))
16625 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16626 "Insert a date stamp for the date given by the internal TIME.
16627 WITH-HM means use the stamp format that includes the time of the day.
16628 INACTIVE means use square brackets instead of angular ones, so that the
16629 stamp will not contribute to the agenda.
16630 PRE and POST are optional strings to be inserted before and after the
16631 stamp.
16632 The command returns the inserted time stamp."
16633 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16634 stamp)
16635 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16636 (insert-before-markers (or pre ""))
16637 (when (listp extra)
16638 (setq extra (car extra))
16639 (if (and (stringp extra)
16640 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16641 (setq extra (format "-%02d:%02d"
16642 (string-to-number (match-string 1 extra))
16643 (string-to-number (match-string 2 extra))))
16644 (setq extra nil)))
16645 (when extra
16646 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16647 (insert-before-markers (setq stamp (format-time-string fmt time)))
16648 (insert-before-markers (or post ""))
16649 (setq org-last-inserted-timestamp stamp)))
16651 (defun org-toggle-time-stamp-overlays ()
16652 "Toggle the use of custom time stamp formats."
16653 (interactive)
16654 (setq org-display-custom-times (not org-display-custom-times))
16655 (unless org-display-custom-times
16656 (let ((p (point-min)) (bmp (buffer-modified-p)))
16657 (while (setq p (next-single-property-change p 'display))
16658 (if (and (get-text-property p 'display)
16659 (eq (get-text-property p 'face) 'org-date))
16660 (remove-text-properties
16661 p (setq p (next-single-property-change p 'display))
16662 '(display t))))
16663 (set-buffer-modified-p bmp)))
16664 (if (featurep 'xemacs)
16665 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16666 (org-restart-font-lock)
16667 (setq org-table-may-need-update t)
16668 (if org-display-custom-times
16669 (message "Time stamps are overlaid with custom format")
16670 (message "Time stamp overlays removed")))
16672 (defun org-display-custom-time (beg end)
16673 "Overlay modified time stamp format over timestamp between BEG and END."
16674 (let* ((ts (buffer-substring beg end))
16675 t1 w1 with-hm tf time str w2 (off 0))
16676 (save-match-data
16677 (setq t1 (org-parse-time-string ts t))
16678 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16679 (setq off (- (match-end 0) (match-beginning 0)))))
16680 (setq end (- end off))
16681 (setq w1 (- end beg)
16682 with-hm (and (nth 1 t1) (nth 2 t1))
16683 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16684 time (org-fix-decoded-time t1)
16685 str (org-add-props
16686 (format-time-string
16687 (substring tf 1 -1) (apply 'encode-time time))
16688 nil 'mouse-face 'highlight)
16689 w2 (length str))
16690 (if (not (= w2 w1))
16691 (add-text-properties (1+ beg) (+ 2 beg)
16692 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16693 (if (featurep 'xemacs)
16694 (progn
16695 (put-text-property beg end 'invisible t)
16696 (put-text-property beg end 'end-glyph (make-glyph str)))
16697 (put-text-property beg end 'display str))))
16699 (defun org-translate-time (string)
16700 "Translate all timestamps in STRING to custom format.
16701 But do this only if the variable `org-display-custom-times' is set."
16702 (when org-display-custom-times
16703 (save-match-data
16704 (let* ((start 0)
16705 (re org-ts-regexp-both)
16706 t1 with-hm inactive tf time str beg end)
16707 (while (setq start (string-match re string start))
16708 (setq beg (match-beginning 0)
16709 end (match-end 0)
16710 t1 (save-match-data
16711 (org-parse-time-string (substring string beg end) t))
16712 with-hm (and (nth 1 t1) (nth 2 t1))
16713 inactive (equal (substring string beg (1+ beg)) "[")
16714 tf (funcall (if with-hm 'cdr 'car)
16715 org-time-stamp-custom-formats)
16716 time (org-fix-decoded-time t1)
16717 str (format-time-string
16718 (concat
16719 (if inactive "[" "<") (substring tf 1 -1)
16720 (if inactive "]" ">"))
16721 (apply 'encode-time time))
16722 string (replace-match str t t string)
16723 start (+ start (length str)))))))
16724 string)
16726 (defun org-fix-decoded-time (time)
16727 "Set 0 instead of nil for the first 6 elements of time.
16728 Don't touch the rest."
16729 (let ((n 0))
16730 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16732 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16734 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16735 "Difference between TIMESTAMP-STRING and now in days.
16736 If SECONDS is non-nil, return the difference in seconds."
16737 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16738 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16739 (funcall fdiff (current-time)))))
16741 (defun org-deadline-close (timestamp-string &optional ndays)
16742 "Is the time in TIMESTAMP-STRING close to the current date?"
16743 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16744 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16745 (not (org-entry-is-done-p))))
16747 (defun org-get-wdays (ts &optional delay zero-delay)
16748 "Get the deadline lead time appropriate for timestring TS.
16749 When DELAY is non-nil, get the delay time for scheduled items
16750 instead of the deadline lead time. When ZERO-DELAY is non-nil
16751 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16752 don't try to find the delay cookie in the scheduled timestamp."
16753 (let ((tv (if delay org-scheduled-delay-days
16754 org-deadline-warning-days)))
16755 (cond
16756 ((or (and delay (< tv 0))
16757 (and delay zero-delay (<= tv 0))
16758 (and (not delay) (<= tv 0)))
16759 ;; Enforce this value no matter what
16760 (- tv))
16761 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16762 ;; lead time is specified.
16763 (floor (* (string-to-number (match-string 1 ts))
16764 (cdr (assoc (match-string 2 ts)
16765 '(("d" . 1) ("w" . 7)
16766 ("m" . 30.4) ("y" . 365.25)
16767 ("h" . 0.041667)))))))
16768 ;; go for the default.
16769 (t tv))))
16771 (defun org-calendar-select-mouse (ev)
16772 "Return to `org-read-date' with the date currently selected.
16773 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16774 (interactive "e")
16775 (mouse-set-point ev)
16776 (when (calendar-cursor-to-date)
16777 (let* ((date (calendar-cursor-to-date))
16778 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16779 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16780 (if (active-minibuffer-window) (exit-minibuffer))))
16782 (defun org-check-deadlines (ndays)
16783 "Check if there are any deadlines due or past due.
16784 A deadline is considered due if it happens within `org-deadline-warning-days'
16785 days from today's date. If the deadline appears in an entry marked DONE,
16786 it is not shown. The prefix arg NDAYS can be used to test that many
16787 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16788 (interactive "P")
16789 (let* ((org-warn-days
16790 (cond
16791 ((equal ndays '(4)) 100000)
16792 (ndays (prefix-numeric-value ndays))
16793 (t (abs org-deadline-warning-days))))
16794 (case-fold-search nil)
16795 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16796 (callback
16797 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16799 (message "%d deadlines past-due or due within %d days"
16800 (org-occur regexp nil callback)
16801 org-warn-days)))
16803 (defsubst org-re-timestamp (type)
16804 "Return a regexp for timestamp TYPE.
16805 Allowed values for TYPE are:
16807 all: all timestamps
16808 active: only active timestamps (<...>)
16809 inactive: only inactive timestamps ([...])
16810 scheduled: only scheduled timestamps
16811 deadline: only deadline timestamps
16812 closed: only closed time-stamps
16814 When TYPE is nil, fall back on returning a regexp that matches
16815 both scheduled and deadline timestamps."
16816 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16817 ((eq type 'active) org-ts-regexp)
16818 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16819 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16820 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16821 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
16822 ((eq type 'scheduled-or-deadline)
16823 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16825 (defun org-check-before-date (date)
16826 "Check if there are deadlines or scheduled entries before DATE."
16827 (interactive (list (org-read-date)))
16828 (let ((case-fold-search nil)
16829 (regexp (org-re-timestamp org-ts-type))
16830 (callback
16831 (lambda () (time-less-p
16832 (org-time-string-to-time (match-string 1))
16833 (org-time-string-to-time date)))))
16834 (message "%d entries before %s"
16835 (org-occur regexp nil callback) date)))
16837 (defun org-check-after-date (date)
16838 "Check if there are deadlines or scheduled entries after DATE."
16839 (interactive (list (org-read-date)))
16840 (let ((case-fold-search nil)
16841 (regexp (org-re-timestamp org-ts-type))
16842 (callback
16843 (lambda () (not
16844 (time-less-p
16845 (org-time-string-to-time (match-string 1))
16846 (org-time-string-to-time date))))))
16847 (message "%d entries after %s"
16848 (org-occur regexp nil callback) date)))
16850 (defun org-check-dates-range (start-date end-date)
16851 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16852 (interactive (list (org-read-date nil nil nil "Range starts")
16853 (org-read-date nil nil nil "Range end")))
16854 (let ((case-fold-search nil)
16855 (regexp (org-re-timestamp org-ts-type))
16856 (callback
16857 (lambda ()
16858 (let ((match (match-string 1)))
16859 (and
16860 (not (time-less-p
16861 (org-time-string-to-time match)
16862 (org-time-string-to-time start-date)))
16863 (time-less-p
16864 (org-time-string-to-time match)
16865 (org-time-string-to-time end-date)))))))
16866 (message "%d entries between %s and %s"
16867 (org-occur regexp nil callback) start-date end-date)))
16869 (defun org-evaluate-time-range (&optional to-buffer)
16870 "Evaluate a time range by computing the difference between start and end.
16871 Normally the result is just printed in the echo area, but with prefix arg
16872 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16873 If the time range is actually in a table, the result is inserted into the
16874 next column.
16875 For time difference computation, a year is assumed to be exactly 365
16876 days in order to avoid rounding problems."
16877 (interactive "P")
16879 (org-clock-update-time-maybe)
16880 (save-excursion
16881 (unless (org-at-date-range-p t)
16882 (goto-char (point-at-bol))
16883 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16884 (if (not (org-at-date-range-p t))
16885 (user-error "Not at a time-stamp range, and none found in current line")))
16886 (let* ((ts1 (match-string 1))
16887 (ts2 (match-string 2))
16888 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16889 (match-end (match-end 0))
16890 (time1 (org-time-string-to-time ts1))
16891 (time2 (org-time-string-to-time ts2))
16892 (t1 (org-float-time time1))
16893 (t2 (org-float-time time2))
16894 (diff (abs (- t2 t1)))
16895 (negative (< (- t2 t1) 0))
16896 ;; (ys (floor (* 365 24 60 60)))
16897 (ds (* 24 60 60))
16898 (hs (* 60 60))
16899 (fy "%dy %dd %02d:%02d")
16900 (fy1 "%dy %dd")
16901 (fd "%dd %02d:%02d")
16902 (fd1 "%dd")
16903 (fh "%02d:%02d")
16904 y d h m align)
16905 (if havetime
16906 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16908 d (floor (/ diff ds)) diff (mod diff ds)
16909 h (floor (/ diff hs)) diff (mod diff hs)
16910 m (floor (/ diff 60)))
16911 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16913 d (floor (+ (/ diff ds) 0.5))
16914 h 0 m 0))
16915 (if (not to-buffer)
16916 (message "%s" (org-make-tdiff-string y d h m))
16917 (if (org-at-table-p)
16918 (progn
16919 (goto-char match-end)
16920 (setq align t)
16921 (and (looking-at " *|") (goto-char (match-end 0))))
16922 (goto-char match-end))
16923 (if (looking-at
16924 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16925 (replace-match ""))
16926 (if negative (insert " -"))
16927 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16928 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16929 (insert " " (format fh h m))))
16930 (if align (org-table-align))
16931 (message "Time difference inserted")))))
16933 (defun org-make-tdiff-string (y d h m)
16934 (let ((fmt "")
16935 (l nil))
16936 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16937 l (push y l)))
16938 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16939 l (push d l)))
16940 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16941 l (push h l)))
16942 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16943 l (push m l)))
16944 (apply 'format fmt (nreverse l))))
16946 (defun org-time-string-to-time (s &optional buffer pos)
16947 "Convert a timestamp string into internal time."
16948 (condition-case errdata
16949 (apply 'encode-time (org-parse-time-string s))
16950 (error (error "Bad timestamp `%s'%s\nError was: %s"
16951 s (if (not (and buffer pos))
16953 (format " at %d in buffer `%s'" pos buffer))
16954 (cdr errdata)))))
16956 (defun org-time-string-to-seconds (s)
16957 "Convert a timestamp string to a number of seconds."
16958 (org-float-time (org-time-string-to-time s)))
16960 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16961 "Convert a time stamp to an absolute day number.
16962 If there is a specifier for a cyclic time stamp, get the closest
16963 date to DAYNR.
16964 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16965 The variable `date' is bound by the calendar when this is called."
16966 (cond
16967 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16968 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16969 daynr
16970 (+ daynr 1000)))
16971 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16972 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16973 (time-to-days (current-time))) (match-string 0 s)
16974 prefer show-all))
16975 (t (time-to-days
16976 (condition-case errdata
16977 (apply 'encode-time (org-parse-time-string s))
16978 (error (error "Bad timestamp `%s'%s\nError was: %s"
16979 s (if (not (and buffer pos))
16981 (format " at %d in buffer `%s'" pos buffer))
16982 (cdr errdata))))))))
16984 (defun org-days-to-iso-week (days)
16985 "Return the iso week number."
16986 (require 'cal-iso)
16987 (car (calendar-iso-from-absolute days)))
16989 (defun org-small-year-to-year (year)
16990 "Convert 2-digit years into 4-digit years.
16991 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
16992 The year 2000 cannot be abbreviated. Any year larger than 99
16993 is returned unchanged."
16994 (if (< year 38)
16995 (setq year (+ 2000 year))
16996 (if (< year 100)
16997 (setq year (+ 1900 year))))
16998 year)
17000 (defun org-time-from-absolute (d)
17001 "Return the time corresponding to date D.
17002 D may be an absolute day number, or a calendar-type list (month day year)."
17003 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17004 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17006 (defun org-calendar-holiday ()
17007 "List of holidays, for Diary display in Org-mode."
17008 (require 'holidays)
17009 (let ((hl (funcall
17010 (if (fboundp 'calendar-check-holidays)
17011 'calendar-check-holidays 'check-calendar-holidays) date)))
17012 (if hl (mapconcat 'identity hl "; "))))
17014 (defun org-diary-sexp-entry (sexp entry date)
17015 "Process a SEXP diary ENTRY for DATE."
17016 (require 'diary-lib)
17017 (let ((result (if calendar-debug-sexp
17018 (let ((stack-trace-on-error t))
17019 (eval (car (read-from-string sexp))))
17020 (condition-case nil
17021 (eval (car (read-from-string sexp)))
17022 (error
17023 (beep)
17024 (message "Bad sexp at line %d in %s: %s"
17025 (org-current-line)
17026 (buffer-file-name) sexp)
17027 (sleep-for 2))))))
17028 (cond ((stringp result) (split-string result "; "))
17029 ((and (consp result)
17030 (not (consp (cdr result)))
17031 (stringp (cdr result))) (cdr result))
17032 ((and (consp result)
17033 (stringp (car result))) result)
17034 (result entry))))
17036 (defun org-diary-to-ical-string (frombuf)
17037 "Get iCalendar entries from diary entries in buffer FROMBUF.
17038 This uses the icalendar.el library."
17039 (let* ((tmpdir (if (featurep 'xemacs)
17040 (temp-directory)
17041 temporary-file-directory))
17042 (tmpfile (make-temp-name
17043 (expand-file-name "orgics" tmpdir)))
17044 buf rtn b e)
17045 (with-current-buffer frombuf
17046 (icalendar-export-region (point-min) (point-max) tmpfile)
17047 (setq buf (find-buffer-visiting tmpfile))
17048 (set-buffer buf)
17049 (goto-char (point-min))
17050 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17051 (setq b (match-beginning 0)))
17052 (goto-char (point-max))
17053 (if (re-search-backward "^END:VEVENT" nil t)
17054 (setq e (match-end 0)))
17055 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17056 (kill-buffer buf)
17057 (delete-file tmpfile)
17058 rtn))
17060 (defun org-closest-date (start current change prefer show-all)
17061 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17062 When PREFER is `past', return a date that is either CURRENT or past.
17063 When PREFER is `future', return a date that is either CURRENT or future.
17064 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17065 ;; Make the proper lists from the dates
17066 (catch 'exit
17067 (let ((a1 '(("h" . hour)
17068 ("d" . day)
17069 ("w" . week)
17070 ("m" . month)
17071 ("y" . year)))
17072 (shour (nth 2 (org-parse-time-string start)))
17073 dn dw sday cday n1 n2 n0
17074 d m y y1 y2 date1 date2 nmonths nm ny m2)
17076 (setq start (org-date-to-gregorian start)
17077 current (org-date-to-gregorian
17078 (if show-all
17079 current
17080 (time-to-days (current-time))))
17081 sday (calendar-absolute-from-gregorian start)
17082 cday (calendar-absolute-from-gregorian current))
17084 (if (<= cday sday) (throw 'exit sday))
17086 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17087 (setq dn (string-to-number (match-string 1 change))
17088 dw (cdr (assoc (match-string 2 change) a1)))
17089 (user-error "Invalid change specifier: %s" change))
17090 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17091 (cond
17092 ((eq dw 'hour)
17093 (let ((missing-hours
17094 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17095 dn)))
17096 (setq n1 (if (zerop missing-hours) cday
17097 (- cday (1+ (floor (/ missing-hours 24)))))
17098 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17099 ((eq dw 'day)
17100 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17101 n2 (+ n1 dn)))
17102 ((eq dw 'year)
17103 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17104 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17105 (setq date1 (list m d y1)
17106 n1 (calendar-absolute-from-gregorian date1)
17107 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17108 n2 (calendar-absolute-from-gregorian date2)))
17109 ((eq dw 'month)
17110 ;; approx number of month between the two dates
17111 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17112 ;; How often does dn fit in there?
17113 (setq d (nth 1 start) m (car start) y (nth 2 start)
17114 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17115 m (+ m nm)
17116 ny (floor (/ m 12))
17117 y (+ y ny)
17118 m (- m (* ny 12)))
17119 (while (> m 12) (setq m (- m 12) y (1+ y)))
17120 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17121 (setq m2 (+ m dn) y2 y)
17122 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17123 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17124 (while (<= n2 cday)
17125 (setq n1 n2 m m2 y y2)
17126 (setq m2 (+ m dn) y2 y)
17127 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17128 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17129 ;; Make sure n1 is the earlier date
17130 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17131 (if show-all
17132 (cond
17133 ((eq prefer 'past) (if (= cday n2) n2 n1))
17134 ((eq prefer 'future) (if (= cday n1) n1 n2))
17135 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17136 (cond
17137 ((eq prefer 'past) (if (= cday n2) n2 n1))
17138 ((eq prefer 'future) (if (= cday n1) n1 n2))
17139 (t (if (= cday n1) n1 n2)))))))
17141 (defun org-date-to-gregorian (date)
17142 "Turn any specification of DATE into a Gregorian date for the calendar."
17143 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17144 ((and (listp date) (= (length date) 3)) date)
17145 ((stringp date)
17146 (setq date (org-parse-time-string date))
17147 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17148 ((listp date)
17149 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17151 (defun org-parse-time-string (s &optional nodefault)
17152 "Parse the standard Org-mode time string.
17153 This should be a lot faster than the normal `parse-time-string'.
17154 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17155 hour and minute fields will be nil if not given."
17156 (cond ((string-match org-ts-regexp0 s)
17157 (list 0
17158 (if (or (match-beginning 8) (not nodefault))
17159 (string-to-number (or (match-string 8 s) "0")))
17160 (if (or (match-beginning 7) (not nodefault))
17161 (string-to-number (or (match-string 7 s) "0")))
17162 (string-to-number (match-string 4 s))
17163 (string-to-number (match-string 3 s))
17164 (string-to-number (match-string 2 s))
17165 nil nil nil))
17166 ((string-match "^<[^>]+>$" s)
17167 (decode-time (seconds-to-time (org-matcher-time s))))
17168 (t (error "Not a standard Org-mode time string: %s" s))))
17170 (defun org-timestamp-up (&optional arg)
17171 "Increase the date item at the cursor by one.
17172 If the cursor is on the year, change the year. If it is on the month,
17173 the day or the time, change that.
17174 With prefix ARG, change by that many units."
17175 (interactive "p")
17176 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17178 (defun org-timestamp-down (&optional arg)
17179 "Decrease the date item at the cursor by one.
17180 If the cursor is on the year, change the year. If it is on the month,
17181 the day or the time, change that.
17182 With prefix ARG, change by that many units."
17183 (interactive "p")
17184 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17186 (defun org-timestamp-up-day (&optional arg)
17187 "Increase the date in the time stamp by one day.
17188 With prefix ARG, change that many days."
17189 (interactive "p")
17190 (if (and (not (org-at-timestamp-p t))
17191 (org-at-heading-p))
17192 (org-todo 'up)
17193 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17195 (defun org-timestamp-down-day (&optional arg)
17196 "Decrease the date in the time stamp by one day.
17197 With prefix ARG, change that many days."
17198 (interactive "p")
17199 (if (and (not (org-at-timestamp-p t))
17200 (org-at-heading-p))
17201 (org-todo 'down)
17202 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17204 (defun org-at-timestamp-p (&optional inactive-ok)
17205 "Determine if the cursor is in or at a timestamp."
17206 (interactive)
17207 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17208 (pos (point))
17209 (ans (or (looking-at tsr)
17210 (save-excursion
17211 (skip-chars-backward "^[<\n\r\t")
17212 (if (> (point) (point-min)) (backward-char 1))
17213 (and (looking-at tsr)
17214 (> (- (match-end 0) pos) -1))))))
17215 (and ans
17216 (boundp 'org-ts-what)
17217 (setq org-ts-what
17218 (cond
17219 ((= pos (match-beginning 0)) 'bracket)
17220 ;; Point is considered to be "on the bracket" whether
17221 ;; it's really on it or right after it.
17222 ((= pos (1- (match-end 0))) 'bracket)
17223 ((= pos (match-end 0)) 'after)
17224 ((org-pos-in-match-range pos 2) 'year)
17225 ((org-pos-in-match-range pos 3) 'month)
17226 ((org-pos-in-match-range pos 7) 'hour)
17227 ((org-pos-in-match-range pos 8) 'minute)
17228 ((or (org-pos-in-match-range pos 4)
17229 (org-pos-in-match-range pos 5)) 'day)
17230 ((and (> pos (or (match-end 8) (match-end 5)))
17231 (< pos (match-end 0)))
17232 (- pos (or (match-end 8) (match-end 5))))
17233 (t 'day))))
17234 ans))
17236 (defun org-toggle-timestamp-type ()
17237 "Toggle the type (<active> or [inactive]) of a time stamp."
17238 (interactive)
17239 (when (org-at-timestamp-p t)
17240 (let ((beg (match-beginning 0)) (end (match-end 0))
17241 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17242 (save-excursion
17243 (goto-char beg)
17244 (while (re-search-forward "[][<>]" end t)
17245 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17246 t t)))
17247 (message "Timestamp is now %sactive"
17248 (if (equal (char-after beg) ?<) "" "in")))))
17250 (defun org-at-clock-log-p nil
17251 "Is the cursor on the clock log line?"
17252 (save-excursion
17253 (move-beginning-of-line 1)
17254 (looking-at "^[ \t]*CLOCK:")))
17256 (defvar org-clock-history) ; defined in org-clock.el
17257 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17258 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17259 "Change the date in the time stamp at point.
17260 The date will be changed by N times WHAT. WHAT can be `day', `month',
17261 `year', `minute', `second'. If WHAT is not given, the cursor position
17262 in the timestamp determines what will be changed.
17263 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17264 (let ((origin (point)) origin-cat
17265 with-hm inactive
17266 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17267 org-ts-what
17268 extra rem
17269 ts time time0 fixnext clrgx)
17270 (if (not (org-at-timestamp-p t))
17271 (user-error "Not at a timestamp"))
17272 (if (and (not what) (eq org-ts-what 'bracket))
17273 (org-toggle-timestamp-type)
17274 ;; Point isn't on brackets. Remember the part of the time-stamp
17275 ;; the point was in. Indeed, size of time-stamps may change,
17276 ;; but point must be kept in the same category nonetheless.
17277 (setq origin-cat org-ts-what)
17278 (if (and (not what) (not (eq org-ts-what 'day))
17279 org-display-custom-times
17280 (get-text-property (point) 'display)
17281 (not (get-text-property (1- (point)) 'display)))
17282 (setq org-ts-what 'day))
17283 (setq org-ts-what (or what org-ts-what)
17284 inactive (= (char-after (match-beginning 0)) ?\[)
17285 ts (match-string 0))
17286 (replace-match "")
17287 (when (string-match
17288 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17290 (setq extra (match-string 1 ts))
17291 (if suppress-tmp-delay
17292 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17293 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17294 (setq with-hm t))
17295 (setq time0 (org-parse-time-string ts))
17296 (when (and updown
17297 (eq org-ts-what 'minute)
17298 (not current-prefix-arg))
17299 ;; This looks like s-up and s-down. Change by one rounding step.
17300 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17301 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17302 (setcar (cdr time0) (+ (nth 1 time0)
17303 (if (> n 0) (- rem) (- dm rem))))))
17304 (setq time
17305 (encode-time (or (car time0) 0)
17306 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17307 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17308 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17309 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17310 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17311 (nthcdr 6 time0)))
17312 (when (and (member org-ts-what '(hour minute))
17313 extra
17314 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17315 (setq extra (org-modify-ts-extra
17316 extra
17317 (if (eq org-ts-what 'hour) 2 5)
17318 n dm)))
17319 (when (integerp org-ts-what)
17320 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17321 (if (eq what 'calendar)
17322 (let ((cal-date (org-get-date-from-calendar)))
17323 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17324 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17325 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17326 (setcar time0 (or (car time0) 0))
17327 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17328 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17329 (setq time (apply 'encode-time time0))))
17330 ;; Insert the new time-stamp, and ensure point stays in the same
17331 ;; category as before (i.e. not after the last position in that
17332 ;; category).
17333 (let ((pos (point)))
17334 ;; Stay before inserted string. `save-excursion' is of no use.
17335 (setq org-last-changed-timestamp
17336 (org-insert-time-stamp time with-hm inactive nil nil extra))
17337 (goto-char pos))
17338 (save-match-data
17339 (looking-at org-ts-regexp3)
17340 (goto-char (cond
17341 ;; `day' category ends before `hour' if any, or at
17342 ;; the end of the day name.
17343 ((eq origin-cat 'day)
17344 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17345 ((eq origin-cat 'hour) (min (match-end 7) origin))
17346 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17347 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17348 ;; `year' and `month' have both fixed size: point
17349 ;; couldn't have moved into another part.
17350 (t origin))))
17351 ;; Update clock if on a CLOCK line.
17352 (org-clock-update-time-maybe)
17353 ;; Maybe adjust the closest clock in `org-clock-history'
17354 (when org-clock-adjust-closest
17355 (if (not (and (org-at-clock-log-p)
17356 (< 1 (length (delq nil (mapcar 'marker-position
17357 org-clock-history))))))
17358 (message "No clock to adjust")
17359 (cond ((save-excursion ; fix previous clock?
17360 (re-search-backward org-ts-regexp0 nil t)
17361 (org-looking-back (concat org-clock-string " \\[")))
17362 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17363 ((save-excursion ; fix next clock?
17364 (re-search-backward org-ts-regexp0 nil t)
17365 (looking-at (concat org-ts-regexp0 "\\] =>")))
17366 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17367 (save-window-excursion
17368 ;; Find closest clock to point, adjust the previous/next one in history
17369 (let* ((p (save-excursion (org-back-to-heading t)))
17370 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17371 (clfixnth
17372 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17373 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17374 (if (not clfixpos)
17375 (message "No clock to adjust")
17376 (save-excursion
17377 (org-goto-marker-or-bmk clfixpos)
17378 (org-show-subtree)
17379 (when (re-search-forward clrgx nil t)
17380 (goto-char (match-beginning 1))
17381 (let (org-clock-adjust-closest)
17382 (org-timestamp-change n org-ts-what updown))
17383 (message "Clock adjusted in %s for heading: %s"
17384 (file-name-nondirectory (buffer-file-name))
17385 (org-get-heading t t)))))))))
17386 ;; Try to recenter the calendar window, if any.
17387 (if (and org-calendar-follow-timestamp-change
17388 (get-buffer-window "*Calendar*" t)
17389 (memq org-ts-what '(day month year)))
17390 (org-recenter-calendar (time-to-days time))))))
17392 (defun org-modify-ts-extra (s pos n dm)
17393 "Change the different parts of the lead-time and repeat fields in timestamp."
17394 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17395 ng h m new rem)
17396 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17397 (cond
17398 ((or (org-pos-in-match-range pos 2)
17399 (org-pos-in-match-range pos 3))
17400 (setq m (string-to-number (match-string 3 s))
17401 h (string-to-number (match-string 2 s)))
17402 (if (org-pos-in-match-range pos 2)
17403 (setq h (+ h n))
17404 (setq n (* dm (org-no-warnings (signum n))))
17405 (when (not (= 0 (setq rem (% m dm))))
17406 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17407 (setq m (+ m n)))
17408 (if (< m 0) (setq m (+ m 60) h (1- h)))
17409 (if (> m 59) (setq m (- m 60) h (1+ h)))
17410 (setq h (min 24 (max 0 h)))
17411 (setq ng 1 new (format "-%02d:%02d" h m)))
17412 ((org-pos-in-match-range pos 6)
17413 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17414 ((org-pos-in-match-range pos 5)
17415 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17417 ((org-pos-in-match-range pos 9)
17418 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17419 ((org-pos-in-match-range pos 8)
17420 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17422 (when ng
17423 (setq s (concat
17424 (substring s 0 (match-beginning ng))
17426 (substring s (match-end ng))))))
17429 (defun org-recenter-calendar (date)
17430 "If the calendar is visible, recenter it to DATE."
17431 (let ((cwin (get-buffer-window "*Calendar*" t)))
17432 (when cwin
17433 (let ((calendar-move-hook nil))
17434 (with-selected-window cwin
17435 (calendar-goto-date (if (listp date) date
17436 (calendar-gregorian-from-absolute date))))))))
17438 (defun org-goto-calendar (&optional arg)
17439 "Go to the Emacs calendar at the current date.
17440 If there is a time stamp in the current line, go to that date.
17441 A prefix ARG can be used to force the current date."
17442 (interactive "P")
17443 (let ((tsr org-ts-regexp) diff
17444 (calendar-move-hook nil)
17445 (calendar-view-holidays-initially-flag nil)
17446 (calendar-view-diary-initially-flag nil))
17447 (if (or (org-at-timestamp-p)
17448 (save-excursion
17449 (beginning-of-line 1)
17450 (looking-at (concat ".*" tsr))))
17451 (let ((d1 (time-to-days (current-time)))
17452 (d2 (time-to-days
17453 (org-time-string-to-time (match-string 1)))))
17454 (setq diff (- d2 d1))))
17455 (calendar)
17456 (calendar-goto-today)
17457 (if (and diff (not arg)) (calendar-forward-day diff))))
17459 (defun org-get-date-from-calendar ()
17460 "Return a list (month day year) of date at point in calendar."
17461 (with-current-buffer "*Calendar*"
17462 (save-match-data
17463 (calendar-cursor-to-date))))
17465 (defun org-date-from-calendar ()
17466 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17467 If there is already a time stamp at the cursor position, update it."
17468 (interactive)
17469 (if (org-at-timestamp-p t)
17470 (org-timestamp-change 0 'calendar)
17471 (let ((cal-date (org-get-date-from-calendar)))
17472 (org-insert-time-stamp
17473 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17475 (defcustom org-effort-durations
17476 `(("h" . 60)
17477 ("d" . ,(* 60 8))
17478 ("w" . ,(* 60 8 5))
17479 ("m" . ,(* 60 8 5 4))
17480 ("y" . ,(* 60 8 5 40)))
17481 "Conversion factor to minutes for an effort modifier.
17483 Each entry has the form (MODIFIER . MINUTES).
17485 In an effort string, a number followed by MODIFIER is multiplied
17486 by the specified number of MINUTES to obtain an effort in
17487 minutes.
17489 For example, if the value of this variable is ((\"hours\" . 60)), then an
17490 effort string \"2hours\" is equivalent to 120 minutes."
17491 :group 'org-agenda
17492 :version "24.1"
17493 :type '(alist :key-type (string :tag "Modifier")
17494 :value-type (number :tag "Minutes")))
17496 (defun org-minutes-to-clocksum-string (m)
17497 "Format number of minutes as a clocksum string.
17498 The format is determined by `org-time-clocksum-format',
17499 `org-time-clocksum-use-fractional' and
17500 `org-time-clocksum-fractional-format' and
17501 `org-time-clocksum-use-effort-durations'."
17502 (let ((clocksum "")
17503 (m (round m)) ; Don't allow fractions of minutes
17504 h d w mo y fmt n)
17505 (setq h (if org-time-clocksum-use-effort-durations
17506 (cdr (assoc "h" org-effort-durations)) 60)
17507 d (if org-time-clocksum-use-effort-durations
17508 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17509 w (if org-time-clocksum-use-effort-durations
17510 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17511 mo (if org-time-clocksum-use-effort-durations
17512 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17513 y (if org-time-clocksum-use-effort-durations
17514 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17515 ;; fractional format
17516 (if org-time-clocksum-use-fractional
17517 (cond
17518 ;; single format string
17519 ((stringp org-time-clocksum-fractional-format)
17520 (format org-time-clocksum-fractional-format (/ m (float h))))
17521 ;; choice of fractional formats for different time units
17522 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17523 (> (/ (truncate m) (* y d h)) 0))
17524 (format fmt (/ m (* y d (float h)))))
17525 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17526 (> (/ (truncate m) (* mo d h)) 0))
17527 (format fmt (/ m (* mo d (float h)))))
17528 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17529 (> (/ (truncate m) (* w d h)) 0))
17530 (format fmt (/ m (* w d (float h)))))
17531 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17532 (> (/ (truncate m) (* d h)) 0))
17533 (format fmt (/ m (* d (float h)))))
17534 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17535 (> (/ (truncate m) h) 0))
17536 (format fmt (/ m (float h))))
17537 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17538 (format fmt m))
17539 ;; fall back to smallest time unit with a format
17540 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17541 (format fmt (/ m (float h))))
17542 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17543 (format fmt (/ m (* d (float h)))))
17544 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17545 (format fmt (/ m (* w d (float h)))))
17546 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17547 (format fmt (/ m (* mo d (float h)))))
17548 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17549 (format fmt (/ m (* y d (float h))))))
17550 ;; standard (non-fractional) format, with single format string
17551 (if (stringp org-time-clocksum-format)
17552 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17553 ;; separate formats components
17554 (and (setq fmt (plist-get org-time-clocksum-format :years))
17555 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17556 (plist-get org-time-clocksum-format :require-years))
17557 (setq clocksum (concat clocksum (format fmt n))
17558 m (- m (* n y d h))))
17559 (and (setq fmt (plist-get org-time-clocksum-format :months))
17560 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17561 (plist-get org-time-clocksum-format :require-months))
17562 (setq clocksum (concat clocksum (format fmt n))
17563 m (- m (* n mo d h))))
17564 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17565 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17566 (plist-get org-time-clocksum-format :require-weeks))
17567 (setq clocksum (concat clocksum (format fmt n))
17568 m (- m (* n w d h))))
17569 (and (setq fmt (plist-get org-time-clocksum-format :days))
17570 (or (> (setq n (/ (truncate m) (* d h))) 0)
17571 (plist-get org-time-clocksum-format :require-days))
17572 (setq clocksum (concat clocksum (format fmt n))
17573 m (- m (* n d h))))
17574 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17575 (or (> (setq n (/ (truncate m) h)) 0)
17576 (plist-get org-time-clocksum-format :require-hours))
17577 (setq clocksum (concat clocksum (format fmt n))
17578 m (- m (* n h))))
17579 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17580 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17581 (setq clocksum (concat clocksum (format fmt m))))
17582 ;; return formatted time duration
17583 clocksum))))
17585 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17586 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17587 "Org mode version 8.0")
17589 (defun org-hours-to-clocksum-string (n)
17590 (org-minutes-to-clocksum-string (* n 60)))
17592 (defun org-hh:mm-string-to-minutes (s)
17593 "Convert a string H:MM to a number of minutes.
17594 If the string is just a number, interpret it as minutes.
17595 In fact, the first hh:mm or number in the string will be taken,
17596 there can be extra stuff in the string.
17597 If no number is found, the return value is 0."
17598 (cond
17599 ((integerp s) s)
17600 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17601 (+ (* (string-to-number (match-string 1 s)) 60)
17602 (string-to-number (match-string 2 s))))
17603 ((string-match "\\([0-9]+\\)" s)
17604 (string-to-number (match-string 1 s)))
17605 (t 0)))
17607 (defcustom org-image-actual-width t
17608 "Should we use the actual width of images when inlining them?
17610 When set to `t', always use the image width.
17612 When set to a number, use imagemagick (when available) to set
17613 the image's width to this value.
17615 When set to a number in a list, try to get the width from any
17616 #+ATTR.* keyword if it matches a width specification like
17618 #+ATTR_HTML: :width 300px
17620 and fall back on that number if none is found.
17622 When set to nil, try to get the width from an #+ATTR.* keyword
17623 and fall back on the original width if none is found.
17625 This requires Emacs >= 24.1, build with imagemagick support."
17626 :group 'org-appearance
17627 :version "24.4"
17628 :package-version '(Org . "8.0")
17629 :type '(choice
17630 (const :tag "Use the image width" t)
17631 (integer :tag "Use a number of pixels")
17632 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17633 (const :tag "Use #+ATTR* or don't resize" nil)))
17635 (defcustom org-agenda-inhibit-startup nil
17636 "Inhibit startup when preparing agenda buffers.
17637 When this variable is `t' (the default), the initialization of
17638 the Org agenda buffers is inhibited: e.g. the visibility state
17639 is not set, the tables are not re-aligned, etc."
17640 :type 'boolean
17641 :version "24.3"
17642 :group 'org-agenda)
17644 (defun org-duration-string-to-minutes (s &optional output-to-string)
17645 "Convert a duration string S to minutes.
17647 A bare number is interpreted as minutes, modifiers can be set by
17648 customizing `org-effort-durations' (which see).
17650 Entries containing a colon are interpreted as H:MM by
17651 `org-hh:mm-string-to-minutes'."
17652 (let ((result 0)
17653 (re (concat "\\([0-9.]+\\) *\\("
17654 (regexp-opt (mapcar 'car org-effort-durations))
17655 "\\)")))
17656 (while (string-match re s)
17657 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17658 (string-to-number (match-string 1 s))))
17659 (setq s (replace-match "" nil t s)))
17660 (setq result (floor result))
17661 (incf result (org-hh:mm-string-to-minutes s))
17662 (if output-to-string (number-to-string result) result)))
17664 ;;;; Files
17666 (defun org-save-all-org-buffers ()
17667 "Save all Org-mode buffers without user confirmation."
17668 (interactive)
17669 (message "Saving all Org-mode buffers...")
17670 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17671 (when (featurep 'org-id) (org-id-locations-save))
17672 (message "Saving all Org-mode buffers... done"))
17674 (defun org-revert-all-org-buffers ()
17675 "Revert all Org-mode buffers.
17676 Prompt for confirmation when there are unsaved changes.
17677 Be sure you know what you are doing before letting this function
17678 overwrite your changes.
17680 This function is useful in a setup where one tracks org files
17681 with a version control system, to revert on one machine after pulling
17682 changes from another. I believe the procedure must be like this:
17684 1. M-x org-save-all-org-buffers
17685 2. Pull changes from the other machine, resolve conflicts
17686 3. M-x org-revert-all-org-buffers"
17687 (interactive)
17688 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17689 (user-error "Abort"))
17690 (save-excursion
17691 (save-window-excursion
17692 (mapc
17693 (lambda (b)
17694 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17695 (with-current-buffer b buffer-file-name))
17696 (org-pop-to-buffer-same-window b)
17697 (revert-buffer t 'no-confirm)))
17698 (buffer-list))
17699 (when (and (featurep 'org-id) org-id-track-globally)
17700 (org-id-locations-load)))))
17702 ;;;; Agenda files
17704 ;;;###autoload
17705 (defun org-switchb (&optional arg)
17706 "Switch between Org buffers.
17707 With one prefix argument, restrict available buffers to files.
17708 With two prefix arguments, restrict available buffers to agenda files.
17710 Defaults to `iswitchb' for buffer name completion.
17711 Set `org-completion-use-ido' to make it use ido instead."
17712 (interactive "P")
17713 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17714 ((equal arg '(16)) (org-buffer-list 'agenda))
17715 (t (org-buffer-list))))
17716 (org-completion-use-iswitchb org-completion-use-iswitchb)
17717 (org-completion-use-ido org-completion-use-ido))
17718 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17719 (setq org-completion-use-iswitchb t))
17720 (org-pop-to-buffer-same-window
17721 (org-icompleting-read "Org buffer: "
17722 (mapcar 'list (mapcar 'buffer-name blist))
17723 nil t))))
17725 ;;; Define some older names previously used for this functionality
17726 ;;;###autoload
17727 (defalias 'org-ido-switchb 'org-switchb)
17728 ;;;###autoload
17729 (defalias 'org-iswitchb 'org-switchb)
17731 (defun org-buffer-list (&optional predicate exclude-tmp)
17732 "Return a list of Org buffers.
17733 PREDICATE can be `export', `files' or `agenda'.
17735 export restrict the list to Export buffers.
17736 files restrict the list to buffers visiting Org files.
17737 agenda restrict the list to buffers visiting agenda files.
17739 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17740 (let* ((bfn nil)
17741 (agenda-files (and (eq predicate 'agenda)
17742 (mapcar 'file-truename (org-agenda-files t))))
17743 (filter
17744 (cond
17745 ((eq predicate 'files)
17746 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17747 ((eq predicate 'export)
17748 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17749 ((eq predicate 'agenda)
17750 (lambda (b)
17751 (with-current-buffer b
17752 (and (derived-mode-p 'org-mode)
17753 (setq bfn (buffer-file-name b))
17754 (member (file-truename bfn) agenda-files)))))
17755 (t (lambda (b) (with-current-buffer b
17756 (or (derived-mode-p 'org-mode)
17757 (string-match "\*Org .*Export"
17758 (buffer-name b)))))))))
17759 (delq nil
17760 (mapcar
17761 (lambda(b)
17762 (if (and (funcall filter b)
17763 (or (not exclude-tmp)
17764 (not (string-match "tmp" (buffer-name b)))))
17766 nil))
17767 (buffer-list)))))
17769 (defun org-agenda-files (&optional unrestricted archives)
17770 "Get the list of agenda files.
17771 Optional UNRESTRICTED means return the full list even if a restriction
17772 is currently in place.
17773 When ARCHIVES is t, include all archive files that are really being
17774 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17775 `org-agenda-archives-mode' is t."
17776 (let ((files
17777 (cond
17778 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17779 ((stringp org-agenda-files) (org-read-agenda-file-list))
17780 ((listp org-agenda-files) org-agenda-files)
17781 (t (error "Invalid value of `org-agenda-files'")))))
17782 (setq files (apply 'append
17783 (mapcar (lambda (f)
17784 (if (file-directory-p f)
17785 (directory-files
17786 f t org-agenda-file-regexp)
17787 (list f)))
17788 files)))
17789 (when org-agenda-skip-unavailable-files
17790 (setq files (delq nil
17791 (mapcar (function
17792 (lambda (file)
17793 (and (file-readable-p file) file)))
17794 files))))
17795 (when (or (eq archives t)
17796 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17797 (setq files (org-add-archive-files files)))
17798 files))
17800 (defun org-agenda-file-p (&optional file)
17801 "Return non-nil, if FILE is an agenda file.
17802 If FILE is omitted, use the file associated with the current
17803 buffer."
17804 (member (or file (buffer-file-name))
17805 (org-agenda-files t)))
17807 (defun org-edit-agenda-file-list ()
17808 "Edit the list of agenda files.
17809 Depending on setup, this either uses customize to edit the variable
17810 `org-agenda-files', or it visits the file that is holding the list. In the
17811 latter case, the buffer is set up in a way that saving it automatically kills
17812 the buffer and restores the previous window configuration."
17813 (interactive)
17814 (if (stringp org-agenda-files)
17815 (let ((cw (current-window-configuration)))
17816 (find-file org-agenda-files)
17817 (org-set-local 'org-window-configuration cw)
17818 (org-add-hook 'after-save-hook
17819 (lambda ()
17820 (set-window-configuration
17821 (prog1 org-window-configuration
17822 (kill-buffer (current-buffer))))
17823 (org-install-agenda-files-menu)
17824 (message "New agenda file list installed"))
17825 nil 'local)
17826 (message "%s" (substitute-command-keys
17827 "Edit list and finish with \\[save-buffer]")))
17828 (customize-variable 'org-agenda-files)))
17830 (defun org-store-new-agenda-file-list (list)
17831 "Set new value for the agenda file list and save it correctly."
17832 (if (stringp org-agenda-files)
17833 (let ((fe (org-read-agenda-file-list t)) b u)
17834 (while (setq b (find-buffer-visiting org-agenda-files))
17835 (kill-buffer b))
17836 (with-temp-file org-agenda-files
17837 (insert
17838 (mapconcat
17839 (lambda (f) ;; Keep un-expanded entries.
17840 (if (setq u (assoc f fe))
17841 (cdr u)
17843 list "\n")
17844 "\n")))
17845 (let ((org-mode-hook nil) (org-inhibit-startup t)
17846 (org-insert-mode-line-in-empty-file nil))
17847 (setq org-agenda-files list)
17848 (customize-save-variable 'org-agenda-files org-agenda-files))))
17850 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17851 "Read the list of agenda files from a file.
17852 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17853 filenames, used by `org-store-new-agenda-file-list' to write back
17854 un-expanded file names."
17855 (when (file-directory-p org-agenda-files)
17856 (error "`org-agenda-files' cannot be a single directory"))
17857 (when (stringp org-agenda-files)
17858 (with-temp-buffer
17859 (insert-file-contents org-agenda-files)
17860 (mapcar
17861 (lambda (f)
17862 (let ((e (expand-file-name (substitute-in-file-name f)
17863 org-directory)))
17864 (if pair-with-expansion
17865 (cons e f)
17866 e)))
17867 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17869 ;;;###autoload
17870 (defun org-cycle-agenda-files ()
17871 "Cycle through the files in `org-agenda-files'.
17872 If the current buffer visits an agenda file, find the next one in the list.
17873 If the current buffer does not, find the first agenda file."
17874 (interactive)
17875 (let* ((fs (org-agenda-files t))
17876 (files (append fs (list (car fs))))
17877 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17878 file)
17879 (unless files (user-error "No agenda files"))
17880 (catch 'exit
17881 (while (setq file (pop files))
17882 (if (equal (file-truename file) tcf)
17883 (when (car files)
17884 (find-file (car files))
17885 (throw 'exit t))))
17886 (find-file (car fs)))
17887 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17889 (defun org-agenda-file-to-front (&optional to-end)
17890 "Move/add the current file to the top of the agenda file list.
17891 If the file is not present in the list, it is added to the front. If it is
17892 present, it is moved there. With optional argument TO-END, add/move to the
17893 end of the list."
17894 (interactive "P")
17895 (let ((org-agenda-skip-unavailable-files nil)
17896 (file-alist (mapcar (lambda (x)
17897 (cons (file-truename x) x))
17898 (org-agenda-files t)))
17899 (ctf (file-truename
17900 (or buffer-file-name
17901 (user-error "Please save the current buffer to a file"))))
17902 x had)
17903 (setq x (assoc ctf file-alist) had x)
17905 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17906 (if to-end
17907 (setq file-alist (append (delq x file-alist) (list x)))
17908 (setq file-alist (cons x (delq x file-alist))))
17909 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17910 (org-install-agenda-files-menu)
17911 (message "File %s to %s of agenda file list"
17912 (if had "moved" "added") (if to-end "end" "front"))))
17914 (defun org-remove-file (&optional file)
17915 "Remove current file from the list of files in variable `org-agenda-files'.
17916 These are the files which are being checked for agenda entries.
17917 Optional argument FILE means use this file instead of the current."
17918 (interactive)
17919 (let* ((org-agenda-skip-unavailable-files nil)
17920 (file (or file buffer-file-name
17921 (user-error "Current buffer does not visit a file")))
17922 (true-file (file-truename file))
17923 (afile (abbreviate-file-name file))
17924 (files (delq nil (mapcar
17925 (lambda (x)
17926 (if (equal true-file
17927 (file-truename x))
17928 nil x))
17929 (org-agenda-files t)))))
17930 (if (not (= (length files) (length (org-agenda-files t))))
17931 (progn
17932 (org-store-new-agenda-file-list files)
17933 (org-install-agenda-files-menu)
17934 (message "Removed file: %s" afile))
17935 (message "File was not in list: %s (not removed)" afile))))
17937 (defun org-file-menu-entry (file)
17938 (vector file (list 'find-file file) t))
17940 (defun org-check-agenda-file (file)
17941 "Make sure FILE exists. If not, ask user what to do."
17942 (when (not (file-exists-p file))
17943 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17944 (abbreviate-file-name file))
17945 (let ((r (downcase (read-char-exclusive))))
17946 (cond
17947 ((equal r ?r)
17948 (org-remove-file file)
17949 (throw 'nextfile t))
17950 (t (error "Abort"))))))
17952 (defun org-get-agenda-file-buffer (file)
17953 "Get a buffer visiting FILE. If the buffer needs to be created, add
17954 it to the list of buffers which might be released later."
17955 (let ((buf (org-find-base-buffer-visiting file)))
17956 (if buf
17957 buf ; just return it
17958 ;; Make a new buffer and remember it
17959 (setq buf (find-file-noselect file))
17960 (if buf (push buf org-agenda-new-buffers))
17961 buf)))
17963 (defun org-release-buffers (blist)
17964 "Release all buffers in list, asking the user for confirmation when needed.
17965 When a buffer is unmodified, it is just killed. When modified, it is saved
17966 \(if the user agrees) and then killed."
17967 (let (buf file)
17968 (while (setq buf (pop blist))
17969 (setq file (buffer-file-name buf))
17970 (when (and (buffer-modified-p buf)
17971 file
17972 (y-or-n-p (format "Save file %s? " file)))
17973 (with-current-buffer buf (save-buffer)))
17974 (kill-buffer buf))))
17976 (defun org-agenda-prepare-buffers (files)
17977 "Create buffers for all agenda files, protect archived trees and comments."
17978 (interactive)
17979 (let ((pa '(:org-archived t))
17980 (pc '(:org-comment t))
17981 (pall '(:org-archived t :org-comment t))
17982 (inhibit-read-only t)
17983 (org-inhibit-startup org-agenda-inhibit-startup)
17984 (rea (concat ":" org-archive-tag ":"))
17985 file re)
17986 (setq org-tag-alist-for-agenda nil
17987 org-tag-groups-alist-for-agenda nil)
17988 (save-excursion
17989 (save-restriction
17990 (while (setq file (pop files))
17991 (catch 'nextfile
17992 (if (bufferp file)
17993 (set-buffer file)
17994 (org-check-agenda-file file)
17995 (set-buffer (org-get-agenda-file-buffer file)))
17996 (widen)
17997 (org-set-regexps-and-options-for-tags)
17998 (goto-char (point-min))
17999 (let ((case-fold-search t))
18000 (when (search-forward "#+setupfile" nil t)
18001 ;; Don't set all regexps and options systematically as
18002 ;; this is only run for setting agenda tags from setup
18003 ;; file
18004 (org-set-regexps-and-options)))
18005 (org-refresh-category-properties)
18006 (org-refresh-properties org-effort-property 'org-effort)
18007 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
18008 (setq org-todo-keywords-for-agenda
18009 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18010 (setq org-done-keywords-for-agenda
18011 (append org-done-keywords-for-agenda org-done-keywords))
18012 (setq org-todo-keyword-alist-for-agenda
18013 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18014 (setq org-drawers-for-agenda
18015 (append org-drawers-for-agenda org-drawers))
18016 (setq org-tag-alist-for-agenda
18017 (org-uniquify
18018 (append org-tag-alist-for-agenda
18019 org-tag-alist
18020 org-tag-persistent-alist)))
18021 (if org-group-tags
18022 (setq org-tag-groups-alist-for-agenda
18023 (org-uniquify-alist
18024 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18025 (org-with-silent-modifications
18026 (save-excursion
18027 (remove-text-properties (point-min) (point-max) pall)
18028 (when org-agenda-skip-archived-trees
18029 (goto-char (point-min))
18030 (while (re-search-forward rea nil t)
18031 (if (org-at-heading-p t)
18032 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18033 (goto-char (point-min))
18034 (setq re (format org-heading-keyword-regexp-format
18035 org-comment-string))
18036 (while (re-search-forward re nil t)
18037 (add-text-properties
18038 (match-beginning 0) (org-end-of-subtree t) pc))))))))
18039 (setq org-todo-keywords-for-agenda
18040 (org-uniquify org-todo-keywords-for-agenda))
18041 (setq org-todo-keyword-alist-for-agenda
18042 (org-uniquify org-todo-keyword-alist-for-agenda))))
18045 ;;;; CDLaTeX minor mode
18047 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18048 "Keymap for the minor `org-cdlatex-mode'.")
18050 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18051 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18052 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18053 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18054 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
18056 (defvar org-cdlatex-texmathp-advice-is-done nil
18057 "Flag remembering if we have applied the advice to texmathp already.")
18059 (define-minor-mode org-cdlatex-mode
18060 "Toggle the minor `org-cdlatex-mode'.
18061 This mode supports entering LaTeX environment and math in LaTeX fragments
18062 in Org-mode.
18063 \\{org-cdlatex-mode-map}"
18064 nil " OCDL" nil
18065 (when org-cdlatex-mode
18066 (require 'cdlatex)
18067 (run-hooks 'cdlatex-mode-hook)
18068 (cdlatex-compute-tables))
18069 (unless org-cdlatex-texmathp-advice-is-done
18070 (setq org-cdlatex-texmathp-advice-is-done t)
18071 (defadvice texmathp (around org-math-always-on activate)
18072 "Always return t in org-mode buffers.
18073 This is because we want to insert math symbols without dollars even outside
18074 the LaTeX math segments. If Orgmode thinks that point is actually inside
18075 an embedded LaTeX fragment, let texmathp do its job.
18076 \\[org-cdlatex-mode-map]"
18077 (interactive)
18078 (let (p)
18079 (cond
18080 ((not (derived-mode-p 'org-mode)) ad-do-it)
18081 ((eq this-command 'cdlatex-math-symbol)
18082 (setq ad-return-value t
18083 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18085 (let ((p (org-inside-LaTeX-fragment-p)))
18086 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18087 (setq ad-return-value t
18088 texmathp-why '("Org-mode embedded math" . 0))
18089 (if p ad-do-it)))))))))
18091 (defun turn-on-org-cdlatex ()
18092 "Unconditionally turn on `org-cdlatex-mode'."
18093 (org-cdlatex-mode 1))
18095 (defun org-try-cdlatex-tab ()
18096 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18097 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18098 - inside a LaTeX fragment, or
18099 - after the first word in a line, where an abbreviation expansion could
18100 insert a LaTeX environment."
18101 (when org-cdlatex-mode
18102 (cond
18103 ;; Before any word on the line: No expansion possible.
18104 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18105 ;; Just after first word on the line: Expand it. Make sure it
18106 ;; cannot happen on headlines, though.
18107 ((save-excursion
18108 (skip-chars-backward "a-zA-Z0-9*")
18109 (skip-chars-backward " \t")
18110 (and (bolp) (not (org-at-heading-p))))
18111 (cdlatex-tab) t)
18112 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18114 (defun org-cdlatex-underscore-caret (&optional arg)
18115 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18116 Revert to the normal definition outside of these fragments."
18117 (interactive "P")
18118 (if (org-inside-LaTeX-fragment-p)
18119 (call-interactively 'cdlatex-sub-superscript)
18120 (let (org-cdlatex-mode)
18121 (call-interactively (key-binding (vector last-input-event))))))
18123 (defun org-cdlatex-math-modify (&optional arg)
18124 "Execute `cdlatex-math-modify' in LaTeX fragments.
18125 Revert to the normal definition outside of these fragments."
18126 (interactive "P")
18127 (if (org-inside-LaTeX-fragment-p)
18128 (call-interactively 'cdlatex-math-modify)
18129 (let (org-cdlatex-mode)
18130 (call-interactively (key-binding (vector last-input-event))))))
18134 ;;;; LaTeX fragments
18136 (defvar org-latex-regexps
18137 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
18138 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
18139 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
18140 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18141 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18142 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
18143 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
18144 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
18145 "Regular expressions for matching embedded LaTeX.")
18147 (defun org-inside-LaTeX-fragment-p ()
18148 "Test if point is inside a LaTeX fragment.
18149 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18150 sequence appearing also before point.
18151 Even though the matchers for math are configurable, this function assumes
18152 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18153 delimiters are skipped when they have been removed by customization.
18154 The return value is nil, or a cons cell with the delimiter and the
18155 position of this delimiter.
18157 This function does a reasonably good job, but can locally be fooled by
18158 for example currency specifications. For example it will assume being in
18159 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18160 fragments that are properly closed, but during editing, we have to live
18161 with the uncertainty caused by missing closing delimiters. This function
18162 looks only before point, not after."
18163 (catch 'exit
18164 (let ((pos (point))
18165 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18166 (lim (progn
18167 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18168 (point)))
18169 dd-on str (start 0) m re)
18170 (goto-char pos)
18171 (when dodollar
18172 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18173 re (nth 1 (assoc "$" org-latex-regexps)))
18174 (while (string-match re str start)
18175 (cond
18176 ((= (match-end 0) (length str))
18177 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18178 ((= (match-end 0) (- (length str) 5))
18179 (throw 'exit nil))
18180 (t (setq start (match-end 0))))))
18181 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18182 (goto-char pos)
18183 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18184 (and (match-beginning 2) (throw 'exit nil))
18185 ;; count $$
18186 (while (re-search-backward "\\$\\$" lim t)
18187 (setq dd-on (not dd-on)))
18188 (goto-char pos)
18189 (if dd-on (cons "$$" m))))))
18191 (defun org-inside-latex-macro-p ()
18192 "Is point inside a LaTeX macro or its arguments?"
18193 (save-match-data
18194 (org-in-regexp
18195 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18197 (defvar org-latex-fragment-image-overlays nil
18198 "List of overlays carrying the images of latex fragments.")
18199 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18201 (defun org-remove-latex-fragment-image-overlays ()
18202 "Remove all overlays with LaTeX fragment images in current buffer."
18203 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18204 (setq org-latex-fragment-image-overlays nil))
18206 (defun org-preview-latex-fragment (&optional subtree)
18207 "Preview the LaTeX fragment at point, or all locally or globally.
18208 If the cursor is in a LaTeX fragment, create the image and overlay
18209 it over the source code. If there is no fragment at point, display
18210 all fragments in the current text, from one headline to the next. With
18211 prefix SUBTREE, display all fragments in the current subtree. With a
18212 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18213 the cursor is before the first headline,
18214 display all fragments in the buffer.
18215 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18216 (interactive "P")
18217 (unless buffer-file-name
18218 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18219 (org-remove-latex-fragment-image-overlays)
18220 (save-excursion
18221 (save-restriction
18222 (let (beg end at msg)
18223 (cond
18224 ((or (equal subtree '(16))
18225 (not (save-excursion
18226 (re-search-backward org-outline-regexp-bol nil t))))
18227 (setq beg (point-min) end (point-max)
18228 msg "Creating images for buffer...%s"))
18229 ((equal subtree '(4))
18230 (org-back-to-heading)
18231 (setq beg (point) end (org-end-of-subtree t)
18232 msg "Creating images for subtree...%s"))
18234 (if (setq at (org-inside-LaTeX-fragment-p))
18235 (goto-char (max (point-min) (- (cdr at) 2)))
18236 (org-back-to-heading))
18237 (setq beg (point) end (progn (outline-next-heading) (point))
18238 msg (if at "Creating image...%s"
18239 "Creating images for entry...%s"))))
18240 (message msg "")
18241 (narrow-to-region beg end)
18242 (goto-char beg)
18243 (org-format-latex
18244 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18245 (file-name-nondirectory
18246 buffer-file-name)))
18247 default-directory 'overlays msg at 'forbuffer
18248 org-latex-create-formula-image-program)
18249 (message msg "done. Use `C-c C-c' to remove images.")))))
18251 (defun org-format-latex (prefix &optional dir overlays msg at
18252 forbuffer processing-type)
18253 "Replace LaTeX fragments with links to an image, and produce images.
18254 Some of the options can be changed using the variable
18255 `org-format-latex-options'."
18256 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18257 (let* ((prefixnodir (file-name-nondirectory prefix))
18258 (absprefix (expand-file-name prefix dir))
18259 (todir (file-name-directory absprefix))
18260 (opt org-format-latex-options)
18261 (optnew org-format-latex-options)
18262 (matchers (plist-get opt :matchers))
18263 (re-list org-latex-regexps)
18264 (cnt 0) txt hash link beg end re e checkdir
18265 string
18266 m n block-type block linkfile movefile ov)
18267 ;; Check the different regular expressions
18268 (while (setq e (pop re-list))
18269 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18270 block (if block-type "\n\n" ""))
18271 (when (member m matchers)
18272 (goto-char (point-min))
18273 (while (re-search-forward re nil t)
18274 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18275 (or (not overlays)
18276 (not (eq (get-char-property (match-beginning n)
18277 'org-overlay-type)
18278 'org-latex-overlay))))
18279 (cond
18280 ((eq processing-type 'verbatim))
18281 ((eq processing-type 'mathjax)
18282 ;; Prepare for MathJax processing.
18283 (setq string (match-string n))
18284 (when (member m '("$" "$1"))
18285 (save-excursion
18286 (delete-region (match-beginning n) (match-end n))
18287 (goto-char (match-beginning n))
18288 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18289 ((or (eq processing-type 'dvipng)
18290 (eq processing-type 'imagemagick))
18291 ;; Process to an image.
18292 (setq txt (match-string n)
18293 beg (match-beginning n) end (match-end n)
18294 cnt (1+ cnt))
18295 (let ((face (face-at-point))
18296 (fg (plist-get opt :foreground))
18297 (bg (plist-get opt :background))
18298 ;; Ensure full list is printed.
18299 print-length print-level)
18300 (when forbuffer
18301 ;; Get the colors from the face at point.
18302 (goto-char beg)
18303 (when (eq fg 'auto)
18304 (setq fg (face-attribute face :foreground nil 'default)))
18305 (when (eq bg 'auto)
18306 (setq bg (face-attribute face :background nil 'default)))
18307 (setq optnew (copy-sequence opt))
18308 (plist-put optnew :foreground fg)
18309 (plist-put optnew :background bg))
18310 (setq hash (sha1 (prin1-to-string
18311 (list org-format-latex-header
18312 org-latex-default-packages-alist
18313 org-latex-packages-alist
18314 org-format-latex-options
18315 forbuffer txt fg bg)))
18316 linkfile (format "%s_%s.png" prefix hash)
18317 movefile (format "%s_%s.png" absprefix hash)))
18318 (setq link (concat block "[[file:" linkfile "]]" block))
18319 (if msg (message msg cnt))
18320 (goto-char beg)
18321 (unless checkdir ; Ensure the directory exists.
18322 (setq checkdir t)
18323 (or (file-directory-p todir) (make-directory todir t)))
18324 (unless (file-exists-p movefile)
18325 (org-create-formula-image
18326 txt movefile optnew forbuffer processing-type))
18327 (if overlays
18328 (progn
18329 (mapc (lambda (o)
18330 (if (eq (overlay-get o 'org-overlay-type)
18331 'org-latex-overlay)
18332 (delete-overlay o)))
18333 (overlays-in beg end))
18334 (setq ov (make-overlay beg end))
18335 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18336 (if (featurep 'xemacs)
18337 (progn
18338 (overlay-put ov 'invisible t)
18339 (overlay-put
18340 ov 'end-glyph
18341 (make-glyph (vector 'png :file movefile))))
18342 (overlay-put
18343 ov 'display
18344 (list 'image :type 'png :file movefile :ascent 'center)))
18345 (push ov org-latex-fragment-image-overlays)
18346 (goto-char end))
18347 (delete-region beg end)
18348 (insert (org-add-props link
18349 (list 'org-latex-src
18350 (replace-regexp-in-string
18351 "\"" "" txt)
18352 'org-latex-src-embed-type
18353 (if block-type 'paragraph 'character))))))
18354 ((eq processing-type 'mathml)
18355 ;; Process to MathML
18356 (unless (save-match-data (org-format-latex-mathml-available-p))
18357 (user-error "LaTeX to MathML converter not configured"))
18358 (setq txt (match-string n)
18359 beg (match-beginning n) end (match-end n)
18360 cnt (1+ cnt))
18361 (if msg (message msg cnt))
18362 (goto-char beg)
18363 (delete-region beg end)
18364 (insert (org-format-latex-as-mathml
18365 txt block-type prefix dir)))
18367 (error "Unknown conversion type %s for LaTeX fragments"
18368 processing-type)))))))))
18370 (defun org-create-math-formula (latex-frag &optional mathml-file)
18371 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18372 Use `org-latex-to-mathml-convert-command'. If the conversion is
18373 sucessful, return the portion between \"<math...> </math>\"
18374 elements otherwise return nil. When MATHML-FILE is specified,
18375 write the results in to that file. When invoked as an
18376 interactive command, prompt for LATEX-FRAG, with initial value
18377 set to the current active region and echo the results for user
18378 inspection."
18379 (interactive (list (let ((frag (when (org-region-active-p)
18380 (buffer-substring-no-properties
18381 (region-beginning) (region-end)))))
18382 (read-string "LaTeX Fragment: " frag nil frag))))
18383 (unless latex-frag (error "Invalid LaTeX fragment"))
18384 (let* ((tmp-in-file (file-relative-name
18385 (make-temp-name (expand-file-name "ltxmathml-in"))))
18386 (ignore (write-region latex-frag nil tmp-in-file))
18387 (tmp-out-file (file-relative-name
18388 (make-temp-name (expand-file-name "ltxmathml-out"))))
18389 (cmd (format-spec
18390 org-latex-to-mathml-convert-command
18391 `((?j . ,(shell-quote-argument
18392 (expand-file-name org-latex-to-mathml-jar-file)))
18393 (?I . ,(shell-quote-argument tmp-in-file))
18394 (?o . ,(shell-quote-argument tmp-out-file)))))
18395 mathml shell-command-output)
18396 (when (org-called-interactively-p 'any)
18397 (unless (org-format-latex-mathml-available-p)
18398 (user-error "LaTeX to MathML converter not configured")))
18399 (message "Running %s" cmd)
18400 (setq shell-command-output (shell-command-to-string cmd))
18401 (setq mathml
18402 (when (file-readable-p tmp-out-file)
18403 (with-current-buffer (find-file-noselect tmp-out-file t)
18404 (goto-char (point-min))
18405 (when (re-search-forward
18406 (concat
18407 (regexp-quote
18408 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18409 "\\(.\\|\n\\)*"
18410 (regexp-quote "</math>")) nil t)
18411 (prog1 (match-string 0) (kill-buffer))))))
18412 (cond
18413 (mathml
18414 (setq mathml
18415 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18416 (when mathml-file
18417 (write-region mathml nil mathml-file))
18418 (when (org-called-interactively-p 'any)
18419 (message mathml)))
18420 ((message "LaTeX to MathML conversion failed")
18421 (message shell-command-output)))
18422 (delete-file tmp-in-file)
18423 (when (file-exists-p tmp-out-file)
18424 (delete-file tmp-out-file))
18425 mathml))
18427 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18428 prefix &optional dir)
18429 "Use `org-create-math-formula' but check local cache first."
18430 (let* ((absprefix (expand-file-name prefix dir))
18431 (print-length nil) (print-level nil)
18432 (formula-id (concat
18433 "formula-"
18434 (sha1
18435 (prin1-to-string
18436 (list latex-frag
18437 org-latex-to-mathml-convert-command)))))
18438 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18439 (formula-cache-dir (file-name-directory formula-cache)))
18441 (unless (file-directory-p formula-cache-dir)
18442 (make-directory formula-cache-dir t))
18444 (unless (file-exists-p formula-cache)
18445 (org-create-math-formula latex-frag formula-cache))
18447 (if (file-exists-p formula-cache)
18448 ;; Successful conversion. Return the link to MathML file.
18449 (org-add-props
18450 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18451 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18452 'org-latex-src-embed-type (if latex-frag-type
18453 'paragraph 'character)))
18454 ;; Failed conversion. Return the LaTeX fragment verbatim
18455 latex-frag)))
18457 (defun org-create-formula-image (string tofile options buffer &optional type)
18458 "Create an image from LaTeX source using dvipng or convert.
18459 This function calls either `org-create-formula-image-with-dvipng'
18460 or `org-create-formula-image-with-imagemagick' depending on the
18461 value of `org-latex-create-formula-image-program' or on the value
18462 of the optional TYPE variable.
18464 Note: ultimately these two function should be combined as they
18465 share a good deal of logic."
18466 (org-check-external-command
18467 "latex" "needed to convert LaTeX fragments to images")
18468 (funcall
18469 (case (or type org-latex-create-formula-image-program)
18470 ('dvipng
18471 (org-check-external-command
18472 "dvipng" "needed to convert LaTeX fragments to images")
18473 #'org-create-formula-image-with-dvipng)
18474 ('imagemagick
18475 (org-check-external-command
18476 "convert" "you need to install imagemagick")
18477 #'org-create-formula-image-with-imagemagick)
18478 (t (error
18479 "Invalid value of `org-latex-create-formula-image-program'")))
18480 string tofile options buffer))
18482 (declare-function org-export--get-global-options "ox" (&optional backend))
18483 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18484 (defun org-create-formula--latex-header ()
18485 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18486 (org-latex-guess-inputenc
18487 (org-splice-latex-header
18488 org-format-latex-header
18489 org-latex-default-packages-alist
18490 org-latex-packages-alist t
18491 (plist-get
18492 (org-combine-plists
18493 (org-export--get-global-options 'latex)
18494 (org-export--get-inbuffer-options 'latex))
18495 :latex-header))))
18497 ;; This function borrows from Ganesh Swami's latex2png.el
18498 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18499 "This calls dvipng."
18500 (require 'ox-latex)
18501 (let* ((tmpdir (if (featurep 'xemacs)
18502 (temp-directory)
18503 temporary-file-directory))
18504 (texfilebase (make-temp-name
18505 (expand-file-name "orgtex" tmpdir)))
18506 (texfile (concat texfilebase ".tex"))
18507 (dvifile (concat texfilebase ".dvi"))
18508 (pngfile (concat texfilebase ".png"))
18509 (fnh (if (featurep 'xemacs)
18510 (font-height (face-font 'default))
18511 (face-attribute 'default :height nil)))
18512 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18513 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18514 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18515 "Black"))
18516 (bg (or (plist-get options (if buffer :background :html-background))
18517 "Transparent")))
18518 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18519 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18520 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18521 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18522 (let ((latex-header (org-create-formula--latex-header)))
18523 (with-temp-file texfile
18524 (insert latex-header)
18525 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18526 (let ((dir default-directory))
18527 (condition-case nil
18528 (progn
18529 (cd tmpdir)
18530 (call-process "latex" nil nil nil texfile))
18531 (error nil))
18532 (cd dir))
18533 (if (not (file-exists-p dvifile))
18534 (progn (message "Failed to create dvi file from %s" texfile) nil)
18535 (condition-case nil
18536 (if (featurep 'xemacs)
18537 (call-process "dvipng" nil nil nil
18538 "-fg" fg "-bg" bg
18539 "-T" "tight"
18540 "-o" pngfile
18541 dvifile)
18542 (call-process "dvipng" nil nil nil
18543 "-fg" fg "-bg" bg
18544 "-D" dpi
18545 ;;"-x" scale "-y" scale
18546 "-T" "tight"
18547 "-o" pngfile
18548 dvifile))
18549 (error nil))
18550 (if (not (file-exists-p pngfile))
18551 (if org-format-latex-signal-error
18552 (error "Failed to create png file from %s" texfile)
18553 (message "Failed to create png file from %s" texfile)
18554 nil)
18555 ;; Use the requested file name and clean up
18556 (copy-file pngfile tofile 'replace)
18557 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18558 (if (file-exists-p (concat texfilebase e))
18559 (delete-file (concat texfilebase e))))
18560 pngfile))))
18562 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18563 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18564 "This calls convert, which is included into imagemagick."
18565 (require 'ox-latex)
18566 (let* ((tmpdir (if (featurep 'xemacs)
18567 (temp-directory)
18568 temporary-file-directory))
18569 (texfilebase (make-temp-name
18570 (expand-file-name "orgtex" tmpdir)))
18571 (texfile (concat texfilebase ".tex"))
18572 (pdffile (concat texfilebase ".pdf"))
18573 (pngfile (concat texfilebase ".png"))
18574 (fnh (if (featurep 'xemacs)
18575 (font-height (face-font 'default))
18576 (face-attribute 'default :height nil)))
18577 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18578 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18579 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18580 "black"))
18581 (bg (or (plist-get options (if buffer :background :html-background))
18582 "white")))
18583 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18584 (setq fg (org-latex-color-format fg)))
18585 (if (eq bg 'default) (setq bg (org-latex-color :background))
18586 (setq bg (org-latex-color-format
18587 (if (string= bg "Transparent") "white" bg))))
18588 (let ((latex-header (org-create-formula--latex-header)))
18589 (with-temp-file texfile
18590 (insert latex-header)
18591 (insert "\n\\begin{document}\n"
18592 "\\definecolor{fg}{rgb}{" fg "}\n"
18593 "\\definecolor{bg}{rgb}{" bg "}\n"
18594 "\n\\pagecolor{bg}\n"
18595 "\n{\\color{fg}\n"
18596 string
18597 "\n}\n"
18598 "\n\\end{document}\n")))
18599 (org-latex-compile texfile t)
18600 (if (not (file-exists-p pdffile))
18601 (progn (message "Failed to create pdf file from %s" texfile) nil)
18602 (condition-case nil
18603 (if (featurep 'xemacs)
18604 (call-process "convert" nil nil nil
18605 "-density" "96"
18606 "-trim"
18607 "-antialias"
18608 pdffile
18609 "-quality" "100"
18610 ;; "-sharpen" "0x1.0"
18611 pngfile)
18612 (call-process "convert" nil nil nil
18613 "-density" dpi
18614 "-trim"
18615 "-antialias"
18616 pdffile
18617 "-quality" "100"
18618 ;; "-sharpen" "0x1.0"
18619 pngfile))
18620 (error nil))
18621 (if (not (file-exists-p pngfile))
18622 (if org-format-latex-signal-error
18623 (error "Failed to create png file from %s" texfile)
18624 (message "Failed to create png file from %s" texfile)
18625 nil)
18626 ;; Use the requested file name and clean up
18627 (copy-file pngfile tofile 'replace)
18628 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18629 (if (file-exists-p (concat texfilebase e))
18630 (delete-file (concat texfilebase e))))
18631 pngfile))))
18633 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18634 "Fill a LaTeX header template TPL.
18635 In the template, the following place holders will be recognized:
18637 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18638 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18639 [PACKAGES] \\usepackage statements for PKG
18640 [NO-PACKAGES] do not include PKG
18641 [EXTRA] the string EXTRA
18642 [NO-EXTRA] do not include EXTRA
18644 For backward compatibility, if both the positive and the negative place
18645 holder is missing, the positive one (without the \"NO-\") will be
18646 assumed to be present at the end of the template.
18647 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18648 EXTRA is a string.
18649 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18650 (let (rpl (end ""))
18651 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18652 (setq rpl (if (or (match-end 1) (not def-pkg))
18653 "" (org-latex-packages-to-string def-pkg snippets-p t))
18654 tpl (replace-match rpl t t tpl))
18655 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18657 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18658 (setq rpl (if (or (match-end 1) (not pkg))
18659 "" (org-latex-packages-to-string pkg snippets-p t))
18660 tpl (replace-match rpl t t tpl))
18661 (if pkg (setq end
18662 (concat end "\n"
18663 (org-latex-packages-to-string pkg snippets-p)))))
18665 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18666 (setq rpl (if (or (match-end 1) (not extra))
18667 "" (concat extra "\n"))
18668 tpl (replace-match rpl t t tpl))
18669 (if (and extra (string-match "\\S-" extra))
18670 (setq end (concat end "\n" extra))))
18672 (if (string-match "\\S-" end)
18673 (concat tpl "\n" end)
18674 tpl)))
18676 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18677 "Turn an alist of packages into a string with the \\usepackage macros."
18678 (setq pkg (mapconcat (lambda(p)
18679 (cond
18680 ((stringp p) p)
18681 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18682 (format "%% Package %s omitted" (cadr p)))
18683 ((equal "" (car p))
18684 (format "\\usepackage{%s}" (cadr p)))
18686 (format "\\usepackage[%s]{%s}"
18687 (car p) (cadr p)))))
18689 "\n"))
18690 (if newline (concat pkg "\n") pkg))
18692 (defun org-dvipng-color (attr)
18693 "Return a RGB color specification for dvipng."
18694 (apply 'format "rgb %s %s %s"
18695 (mapcar 'org-normalize-color
18696 (if (featurep 'xemacs)
18697 (color-rgb-components
18698 (face-property 'default
18699 (cond ((eq attr :foreground) 'foreground)
18700 ((eq attr :background) 'background))))
18701 (color-values (face-attribute 'default attr nil))))))
18703 (defun org-dvipng-color-format (color-name)
18704 "Convert COLOR-NAME to a RGB color value for dvipng."
18705 (apply 'format "rgb %s %s %s"
18706 (mapcar 'org-normalize-color
18707 (color-values color-name))))
18709 (defun org-latex-color (attr)
18710 "Return a RGB color for the LaTeX color package."
18711 (apply 'format "%s,%s,%s"
18712 (mapcar 'org-normalize-color
18713 (if (featurep 'xemacs)
18714 (color-rgb-components
18715 (face-property 'default
18716 (cond ((eq attr :foreground) 'foreground)
18717 ((eq attr :background) 'background))))
18718 (color-values (face-attribute 'default attr nil))))))
18720 (defun org-latex-color-format (color-name)
18721 "Convert COLOR-NAME to a RGB color value."
18722 (apply 'format "%s,%s,%s"
18723 (mapcar 'org-normalize-color
18724 (color-values color-name))))
18726 (defun org-normalize-color (value)
18727 "Return string to be used as color value for an RGB component."
18728 (format "%g" (/ value 65535.0)))
18732 ;; Image display
18734 (defvar org-inline-image-overlays nil)
18735 (make-variable-buffer-local 'org-inline-image-overlays)
18737 (defun org-toggle-inline-images (&optional include-linked)
18738 "Toggle the display of inline images.
18739 INCLUDE-LINKED is passed to `org-display-inline-images'."
18740 (interactive "P")
18741 (if org-inline-image-overlays
18742 (progn
18743 (org-remove-inline-images)
18744 (message "Inline image display turned off"))
18745 (org-display-inline-images include-linked)
18746 (if (and (org-called-interactively-p)
18747 org-inline-image-overlays)
18748 (message "%d images displayed inline"
18749 (length org-inline-image-overlays))
18750 (message "No images to display inline"))))
18752 (defun org-redisplay-inline-images ()
18753 "Refresh the display of inline images."
18754 (interactive)
18755 (if (not org-inline-image-overlays)
18756 (org-toggle-inline-images)
18757 (org-toggle-inline-images)
18758 (org-toggle-inline-images)))
18760 (defun org-display-inline-images (&optional include-linked refresh beg end)
18761 "Display inline images.
18762 Normally only links without a description part are inlined, because this
18763 is how it will work for export. When INCLUDE-LINKED is set, also links
18764 with a description part will be inlined. This can be nice for a quick
18765 look at those images, but it does not reflect what exported files will look
18766 like.
18767 When REFRESH is set, refresh existing images between BEG and END.
18768 This will create new image displays only if necessary.
18769 BEG and END default to the buffer boundaries."
18770 (interactive "P")
18771 (unless refresh
18772 (org-remove-inline-images)
18773 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18774 (save-excursion
18775 (save-restriction
18776 (widen)
18777 (setq beg (or beg (point-min)) end (or end (point-max)))
18778 (goto-char beg)
18779 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18780 (substring (org-image-file-name-regexp) 0 -2)
18781 "\\)\\]" (if include-linked "" "\\]")))
18782 (case-fold-search t)
18783 old file ov img type attrwidth width)
18784 (while (re-search-forward re end t)
18785 (setq old (get-char-property-and-overlay (match-beginning 1)
18786 'org-image-overlay)
18787 file (expand-file-name
18788 (concat (or (match-string 3) "") (match-string 4))))
18789 (when (image-type-available-p 'imagemagick)
18790 (setq attrwidth (if (or (listp org-image-actual-width)
18791 (null org-image-actual-width))
18792 (save-excursion
18793 (save-match-data
18794 (when (re-search-backward
18795 "#\\+attr.*:width[ \t]+\\([^ ]+\\)"
18796 (save-excursion
18797 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18798 (string-to-number (match-string 1))))))
18799 width (cond ((eq org-image-actual-width t) nil)
18800 ((null org-image-actual-width) attrwidth)
18801 ((numberp org-image-actual-width)
18802 org-image-actual-width)
18803 ((listp org-image-actual-width)
18804 (or attrwidth (car org-image-actual-width))))
18805 type (if width 'imagemagick)))
18806 (when (file-exists-p file)
18807 (if (and (car-safe old) refresh)
18808 (image-refresh (overlay-get (cdr old) 'display))
18809 (setq img (save-match-data (create-image file type nil :width width)))
18810 (when img
18811 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18812 (overlay-put ov 'display img)
18813 (overlay-put ov 'face 'default)
18814 (overlay-put ov 'org-image-overlay t)
18815 (overlay-put ov 'modification-hooks
18816 (list 'org-display-inline-remove-overlay))
18817 (push ov org-inline-image-overlays)))))))))
18819 (define-obsolete-function-alias
18820 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18822 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18823 "Remove inline-display overlay if a corresponding region is modified."
18824 (let ((inhibit-modification-hooks t))
18825 (when (and ov after)
18826 (delete ov org-inline-image-overlays)
18827 (delete-overlay ov))))
18829 (defun org-remove-inline-images ()
18830 "Remove inline display of images."
18831 (interactive)
18832 (mapc 'delete-overlay org-inline-image-overlays)
18833 (setq org-inline-image-overlays nil))
18835 ;;;; Key bindings
18837 ;; Outline functions from `outline-mode-prefix-map'
18838 ;; that can be remapped in Org:
18839 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18840 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18841 (define-key org-mode-map [remap outline-forward-same-level]
18842 'org-forward-heading-same-level)
18843 (define-key org-mode-map [remap outline-backward-same-level]
18844 'org-backward-heading-same-level)
18845 (define-key org-mode-map [remap show-branches]
18846 'org-kill-note-or-show-branches)
18847 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18848 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18849 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18851 ;; Outline functions from `outline-mode-prefix-map' that can not
18852 ;; be remapped in Org:
18854 ;; - the column "key binding" shows whether the Outline function is still
18855 ;; available in Org mode on the same key that it has been bound to in
18856 ;; Outline mode:
18857 ;; - "overridden": key used for a different functionality in Org mode
18858 ;; - else: key still bound to the same Outline function in Org mode
18860 ;; | Outline function | key binding | Org replacement |
18861 ;; |------------------------------------+-------------+-----------------------|
18862 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18863 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18864 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18865 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18866 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18867 ;; | `show-entry' | overridden | no replacement |
18868 ;; | `show-children' | `C-c C-i' | visibility cycling |
18869 ;; | `show-branches' | `C-c C-k' | still same function |
18870 ;; | `show-subtree' | overridden | visibility cycling |
18871 ;; | `show-all' | overridden | no replacement |
18872 ;; | `hide-subtree' | overridden | visibility cycling |
18873 ;; | `hide-body' | overridden | no replacement |
18874 ;; | `hide-entry' | overridden | visibility cycling |
18875 ;; | `hide-leaves' | overridden | no replacement |
18876 ;; | `hide-sublevels' | overridden | no replacement |
18877 ;; | `hide-other' | overridden | no replacement |
18879 ;; Make `C-c C-x' a prefix key
18880 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18882 ;; TAB key with modifiers
18883 (org-defkey org-mode-map "\C-i" 'org-cycle)
18884 (org-defkey org-mode-map [(tab)] 'org-cycle)
18885 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18886 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18887 ;; The following line is necessary under Suse GNU/Linux
18888 (unless (featurep 'xemacs)
18889 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18890 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18891 (define-key org-mode-map [backtab] 'org-shifttab)
18893 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18894 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18895 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18897 ;; Cursor keys with modifiers
18898 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18899 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18900 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18901 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18903 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18904 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18905 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18906 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18908 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18909 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18910 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18911 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18913 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18914 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18915 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18916 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18918 ;; Babel keys
18919 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18920 (mapc (lambda (pair)
18921 (define-key org-babel-map (car pair) (cdr pair)))
18922 org-babel-key-bindings)
18924 ;;; Extra keys for tty access.
18925 ;; We only set them when really needed because otherwise the
18926 ;; menus don't show the simple keys
18928 (when (or org-use-extra-keys
18929 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18930 (not window-system))
18931 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18932 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18933 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18934 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18935 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18936 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18937 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18938 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18939 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18940 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18941 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18942 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18943 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18944 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18945 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18946 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18947 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18948 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18949 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18950 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18951 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18952 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18953 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18954 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18955 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18956 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18957 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18958 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18960 ;; All the other keys
18962 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18963 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18964 (if (boundp 'narrow-map)
18965 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18966 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18967 (if (boundp 'narrow-map)
18968 (org-defkey narrow-map "b" 'org-narrow-to-block)
18969 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18970 (if (boundp 'narrow-map)
18971 (org-defkey narrow-map "e" 'org-narrow-to-element)
18972 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18973 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18974 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18975 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18976 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18977 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18978 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18979 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18980 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
18981 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
18982 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18983 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18984 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18985 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18986 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18987 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18988 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18989 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
18990 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18991 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18992 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18993 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18994 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18995 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18996 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18997 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18998 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18999 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19000 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19001 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19002 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19003 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19004 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19005 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19006 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19007 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19008 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19009 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19010 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19011 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19012 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19013 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19014 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19015 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19016 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19017 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19018 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19019 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19020 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19021 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19022 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19023 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19024 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19025 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19026 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19027 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19028 (org-defkey org-mode-map "\C-c^" 'org-sort)
19029 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19030 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19031 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19032 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19033 (org-defkey org-mode-map "\C-m" 'org-return)
19034 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19035 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19036 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19037 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19038 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19039 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19040 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19041 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19042 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19043 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19044 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19045 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19046 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19047 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19048 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
19049 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19050 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19051 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19052 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19053 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19054 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19055 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19056 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19058 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19059 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19060 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19062 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19063 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19064 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19065 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19066 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19067 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19068 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19069 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19070 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19071 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19072 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
19073 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19074 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19075 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19076 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19077 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19078 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19079 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19080 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19081 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19082 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19083 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19084 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19086 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19087 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19088 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19089 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19090 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19092 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19094 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19096 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19097 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19099 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19102 (when (featurep 'xemacs)
19103 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19106 (defconst org-speed-commands-default
19108 ("Outline Navigation")
19109 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19110 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19111 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19112 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19113 ("F" . org-next-block)
19114 ("B" . org-previous-block)
19115 ("u" . (org-speed-move-safe 'outline-up-heading))
19116 ("j" . org-goto)
19117 ("g" . (org-refile t))
19118 ("Outline Visibility")
19119 ("c" . org-cycle)
19120 ("C" . org-shifttab)
19121 (" " . org-display-outline-path)
19122 ("s" . org-narrow-to-subtree)
19123 ("=" . org-columns)
19124 ("Outline Structure Editing")
19125 ("U" . org-shiftmetaup)
19126 ("D" . org-shiftmetadown)
19127 ("r" . org-metaright)
19128 ("l" . org-metaleft)
19129 ("R" . org-shiftmetaright)
19130 ("L" . org-shiftmetaleft)
19131 ("i" . (progn (forward-char 1) (call-interactively
19132 'org-insert-heading-respect-content)))
19133 ("^" . org-sort)
19134 ("w" . org-refile)
19135 ("a" . org-archive-subtree-default-with-confirmation)
19136 ("@" . org-mark-subtree)
19137 ("#" . org-toggle-comment)
19138 ("Clock Commands")
19139 ("I" . org-clock-in)
19140 ("O" . org-clock-out)
19141 ("Meta Data Editing")
19142 ("t" . org-todo)
19143 ("," . (org-priority))
19144 ("0" . (org-priority ?\ ))
19145 ("1" . (org-priority ?A))
19146 ("2" . (org-priority ?B))
19147 ("3" . (org-priority ?C))
19148 (":" . org-set-tags-command)
19149 ("e" . org-set-effort)
19150 ("E" . org-inc-effort)
19151 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19152 (org-entry-put (point) "APPT_WARNTIME" m)))
19153 ("Agenda Views etc")
19154 ("v" . org-agenda)
19155 ("/" . org-sparse-tree)
19156 ("Misc")
19157 ("o" . org-open-at-point)
19158 ("?" . org-speed-command-help)
19159 ("<" . (org-agenda-set-restriction-lock 'subtree))
19160 (">" . (org-agenda-remove-restriction-lock))
19162 "The default speed commands.")
19164 (defun org-print-speed-command (e)
19165 (if (> (length (car e)) 1)
19166 (progn
19167 (princ "\n")
19168 (princ (car e))
19169 (princ "\n")
19170 (princ (make-string (length (car e)) ?-))
19171 (princ "\n"))
19172 (princ (car e))
19173 (princ " ")
19174 (if (symbolp (cdr e))
19175 (princ (symbol-name (cdr e)))
19176 (prin1 (cdr e)))
19177 (princ "\n")))
19179 (defun org-speed-command-help ()
19180 "Show the available speed commands."
19181 (interactive)
19182 (if (not org-use-speed-commands)
19183 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19184 (with-output-to-temp-buffer "*Help*"
19185 (princ "User-defined Speed commands\n===========================\n")
19186 (mapc 'org-print-speed-command org-speed-commands-user)
19187 (princ "\n")
19188 (princ "Built-in Speed commands\n=======================\n")
19189 (mapc 'org-print-speed-command org-speed-commands-default))
19190 (with-current-buffer "*Help*"
19191 (setq truncate-lines t))))
19193 (defun org-speed-move-safe (cmd)
19194 "Execute CMD, but make sure that the cursor always ends up in a headline.
19195 If not, return to the original position and throw an error."
19196 (interactive)
19197 (let ((pos (point)))
19198 (call-interactively cmd)
19199 (unless (and (bolp) (org-at-heading-p))
19200 (goto-char pos)
19201 (error "Boundary reached while executing %s" cmd))))
19203 (defvar org-self-insert-command-undo-counter 0)
19205 (defvar org-table-auto-blank-field) ; defined in org-table.el
19206 (defvar org-speed-command nil)
19208 (define-obsolete-function-alias
19209 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19211 (defun org-speed-command-activate (keys)
19212 "Hook for activating single-letter speed commands.
19213 `org-speed-commands-default' specifies a minimal command set.
19214 Use `org-speed-commands-user' for further customization."
19215 (when (or (and (bolp) (looking-at org-outline-regexp))
19216 (and (functionp org-use-speed-commands)
19217 (funcall org-use-speed-commands)))
19218 (cdr (assoc keys (append org-speed-commands-user
19219 org-speed-commands-default)))))
19221 (define-obsolete-function-alias
19222 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19224 (defun org-babel-speed-command-activate (keys)
19225 "Hook for activating single-letter code block commands."
19226 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19227 (cdr (assoc keys org-babel-key-bindings))))
19229 (defcustom org-speed-command-hook
19230 '(org-speed-command-default-hook org-babel-speed-command-hook)
19231 "Hook for activating speed commands at strategic locations.
19232 Hook functions are called in sequence until a valid handler is
19233 found.
19235 Each hook takes a single argument, a user-pressed command key
19236 which is also a `self-insert-command' from the global map.
19238 Within the hook, examine the cursor position and the command key
19239 and return nil or a valid handler as appropriate. Handler could
19240 be one of an interactive command, a function, or a form.
19242 Set `org-use-speed-commands' to non-nil value to enable this
19243 hook. The default setting is `org-speed-command-activate'."
19244 :group 'org-structure
19245 :version "24.1"
19246 :type 'hook)
19248 (defun org-self-insert-command (N)
19249 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19250 If the cursor is in a table looking at whitespace, the whitespace is
19251 overwritten, and the table is not marked as requiring realignment."
19252 (interactive "p")
19253 (org-check-before-invisible-edit 'insert)
19254 (cond
19255 ((and org-use-speed-commands
19256 (setq org-speed-command
19257 (run-hook-with-args-until-success
19258 'org-speed-command-hook (this-command-keys))))
19259 (cond
19260 ((commandp org-speed-command)
19261 (setq this-command org-speed-command)
19262 (call-interactively org-speed-command))
19263 ((functionp org-speed-command)
19264 (funcall org-speed-command))
19265 ((and org-speed-command (listp org-speed-command))
19266 (eval org-speed-command))
19267 (t (let (org-use-speed-commands)
19268 (call-interactively 'org-self-insert-command)))))
19269 ((and
19270 (org-table-p)
19271 (progn
19272 ;; check if we blank the field, and if that triggers align
19273 (and (featurep 'org-table) org-table-auto-blank-field
19274 (member last-command
19275 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19276 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19277 ;; got extra space, this field does not determine column width
19278 (let (org-table-may-need-update) (org-table-blank-field))
19279 ;; no extra space, this field may determine column width
19280 (org-table-blank-field)))
19282 (eq N 1)
19283 (looking-at "[^|\n]* |"))
19284 (let (org-table-may-need-update)
19285 (goto-char (1- (match-end 0)))
19286 (backward-delete-char 1)
19287 (goto-char (match-beginning 0))
19288 (self-insert-command N)))
19290 (setq org-table-may-need-update t)
19291 (self-insert-command N)
19292 (org-fix-tags-on-the-fly)
19293 (if org-self-insert-cluster-for-undo
19294 (if (not (eq last-command 'org-self-insert-command))
19295 (setq org-self-insert-command-undo-counter 1)
19296 (if (>= org-self-insert-command-undo-counter 20)
19297 (setq org-self-insert-command-undo-counter 1)
19298 (and (> org-self-insert-command-undo-counter 0)
19299 buffer-undo-list (listp buffer-undo-list)
19300 (not (cadr buffer-undo-list)) ; remove nil entry
19301 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19302 (setq org-self-insert-command-undo-counter
19303 (1+ org-self-insert-command-undo-counter))))))))
19305 (defun org-check-before-invisible-edit (kind)
19306 "Check is editing if kind KIND would be dangerous with invisible text around.
19307 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19308 ;; First, try to get out of here as quickly as possible, to reduce overhead
19309 (if (and org-catch-invisible-edits
19310 (or (not (boundp 'visible-mode)) (not visible-mode))
19311 (or (get-char-property (point) 'invisible)
19312 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19313 ;; OK, we need to take a closer look
19314 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19315 (invisible-before-point (if (bobp) nil (get-char-property
19316 (1- (point)) 'invisible)))
19317 (border-and-ok-direction
19319 ;; Check if we are acting predictably before invisible text
19320 (and invisible-at-point (not invisible-before-point)
19321 (memq kind '(insert delete-backward)))
19322 ;; Check if we are acting predictably after invisible text
19323 ;; This works not well, and I have turned it off. It seems
19324 ;; better to always show and stop after invisible text.
19325 ;; (and (not invisible-at-point) invisible-before-point
19326 ;; (memq kind '(insert delete)))
19328 (when (or (memq invisible-at-point '(outline org-hide-block t))
19329 (memq invisible-before-point '(outline org-hide-block t)))
19330 (if (eq org-catch-invisible-edits 'error)
19331 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19332 (if (and org-custom-properties-overlays
19333 (y-or-n-p "Display invisible properties in this buffer? "))
19334 (org-toggle-custom-properties-visibility)
19335 ;; Make the area visible
19336 (save-excursion
19337 (if invisible-before-point
19338 (goto-char (previous-single-char-property-change
19339 (point) 'invisible)))
19340 (org-cycle))
19341 (cond
19342 ((eq org-catch-invisible-edits 'show)
19343 ;; That's it, we do the edit after showing
19344 (message
19345 "Unfolding invisible region around point before editing")
19346 (sit-for 1))
19347 ((and (eq org-catch-invisible-edits 'smart)
19348 border-and-ok-direction)
19349 (message "Unfolding invisible region around point before editing"))
19351 ;; Don't do the edit, make the user repeat it in full visibility
19352 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19354 (defun org-fix-tags-on-the-fly ()
19355 (when (and (equal (char-after (point-at-bol)) ?*)
19356 (org-at-heading-p))
19357 (org-align-tags-here org-tags-column)))
19359 (defun org-delete-backward-char (N)
19360 "Like `delete-backward-char', insert whitespace at field end in tables.
19361 When deleting backwards, in tables this function will insert whitespace in
19362 front of the next \"|\" separator, to keep the table aligned. The table will
19363 still be marked for re-alignment if the field did fill the entire column,
19364 because, in this case the deletion might narrow the column."
19365 (interactive "p")
19366 (save-match-data
19367 (org-check-before-invisible-edit 'delete-backward)
19368 (if (and (org-table-p)
19369 (eq N 1)
19370 (string-match "|" (buffer-substring (point-at-bol) (point)))
19371 (looking-at ".*?|"))
19372 (let ((pos (point))
19373 (noalign (looking-at "[^|\n\r]* |"))
19374 (c org-table-may-need-update))
19375 (backward-delete-char N)
19376 (if (not overwrite-mode)
19377 (progn
19378 (skip-chars-forward "^|")
19379 (insert " ")
19380 (goto-char (1- pos))))
19381 ;; noalign: if there were two spaces at the end, this field
19382 ;; does not determine the width of the column.
19383 (if noalign (setq org-table-may-need-update c)))
19384 (backward-delete-char N)
19385 (org-fix-tags-on-the-fly))))
19387 (defun org-delete-char (N)
19388 "Like `delete-char', but insert whitespace at field end in tables.
19389 When deleting characters, in tables this function will insert whitespace in
19390 front of the next \"|\" separator, to keep the table aligned. The table will
19391 still be marked for re-alignment if the field did fill the entire column,
19392 because, in this case the deletion might narrow the column."
19393 (interactive "p")
19394 (save-match-data
19395 (org-check-before-invisible-edit 'delete)
19396 (if (and (org-table-p)
19397 (not (bolp))
19398 (not (= (char-after) ?|))
19399 (eq N 1))
19400 (if (looking-at ".*?|")
19401 (let ((pos (point))
19402 (noalign (looking-at "[^|\n\r]* |"))
19403 (c org-table-may-need-update))
19404 (replace-match
19405 (concat (substring (match-string 0) 1 -1) " |") nil t)
19406 (goto-char pos)
19407 ;; noalign: if there were two spaces at the end, this field
19408 ;; does not determine the width of the column.
19409 (if noalign (setq org-table-may-need-update c)))
19410 (delete-char N))
19411 (delete-char N)
19412 (org-fix-tags-on-the-fly))))
19414 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19415 (put 'org-self-insert-command 'delete-selection t)
19416 (put 'orgtbl-self-insert-command 'delete-selection t)
19417 (put 'org-delete-char 'delete-selection 'supersede)
19418 (put 'org-delete-backward-char 'delete-selection 'supersede)
19419 (put 'org-yank 'delete-selection 'yank)
19421 ;; Make `flyspell-mode' delay after some commands
19422 (put 'org-self-insert-command 'flyspell-delayed t)
19423 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19424 (put 'org-delete-char 'flyspell-delayed t)
19425 (put 'org-delete-backward-char 'flyspell-delayed t)
19427 ;; Make pabbrev-mode expand after org-mode commands
19428 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19429 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19431 ;; How to do this: Measure non-white length of current string
19432 ;; If equal to column width, we should realign.
19434 (defun org-remap (map &rest commands)
19435 "In MAP, remap the functions given in COMMANDS.
19436 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19437 (let (new old)
19438 (while commands
19439 (setq old (pop commands) new (pop commands))
19440 (if (fboundp 'command-remapping)
19441 (org-defkey map (vector 'remap old) new)
19442 (substitute-key-definition old new map global-map)))))
19444 (defun org-transpose-words ()
19445 "Transpose words for Org.
19446 This uses the `org-mode-transpose-word-syntax-table' syntax
19447 table, which interprets characters in `org-emphasis-alist' as
19448 word constituants."
19449 (interactive)
19450 (with-syntax-table org-mode-transpose-word-syntax-table
19451 (call-interactively 'transpose-words)))
19452 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19454 (when (eq org-enable-table-editor 'optimized)
19455 ;; If the user wants maximum table support, we need to hijack
19456 ;; some standard editing functions
19457 (org-remap org-mode-map
19458 'self-insert-command 'org-self-insert-command
19459 'delete-char 'org-delete-char
19460 'delete-backward-char 'org-delete-backward-char)
19461 (org-defkey org-mode-map "|" 'org-force-self-insert))
19463 (defvar org-ctrl-c-ctrl-c-hook nil
19464 "Hook for functions attaching themselves to `C-c C-c'.
19466 This can be used to add additional functionality to the C-c C-c
19467 key which executes context-dependent commands. This hook is run
19468 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19469 run after the last test.
19471 Each function will be called with no arguments. The function
19472 must check if the context is appropriate for it to act. If yes,
19473 it should do its thing and then return a non-nil value. If the
19474 context is wrong, just do nothing and return nil.")
19476 (defvar org-ctrl-c-ctrl-c-final-hook nil
19477 "Hook for functions attaching themselves to `C-c C-c'.
19479 This can be used to add additional functionality to the C-c C-c
19480 key which executes context-dependent commands. This hook is run
19481 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19482 before the first test.
19484 Each function will be called with no arguments. The function
19485 must check if the context is appropriate for it to act. If yes,
19486 it should do its thing and then return a non-nil value. If the
19487 context is wrong, just do nothing and return nil.")
19489 (defvar org-tab-first-hook nil
19490 "Hook for functions to attach themselves to TAB.
19491 See `org-ctrl-c-ctrl-c-hook' for more information.
19492 This hook runs as the first action when TAB is pressed, even before
19493 `org-cycle' messes around with the `outline-regexp' to cater for
19494 inline tasks and plain list item folding.
19495 If any function in this hook returns t, any other actions that
19496 would have been caused by TAB (such as table field motion or visibility
19497 cycling) will not occur.")
19499 (defvar org-tab-after-check-for-table-hook nil
19500 "Hook for functions to attach themselves to TAB.
19501 See `org-ctrl-c-ctrl-c-hook' for more information.
19502 This hook runs after it has been established that the cursor is not in a
19503 table, but before checking if the cursor is in a headline or if global cycling
19504 should be done.
19505 If any function in this hook returns t, not other actions like visibility
19506 cycling will be done.")
19508 (defvar org-tab-after-check-for-cycling-hook nil
19509 "Hook for functions to attach themselves to TAB.
19510 See `org-ctrl-c-ctrl-c-hook' for more information.
19511 This hook runs after it has been established that not table field motion and
19512 not visibility should be done because of current context. This is probably
19513 the place where a package like yasnippets can hook in.")
19515 (defvar org-tab-before-tab-emulation-hook nil
19516 "Hook for functions to attach themselves to TAB.
19517 See `org-ctrl-c-ctrl-c-hook' for more information.
19518 This hook runs after every other options for TAB have been exhausted, but
19519 before indentation and \t insertion takes place.")
19521 (defvar org-metaleft-hook nil
19522 "Hook for functions attaching themselves to `M-left'.
19523 See `org-ctrl-c-ctrl-c-hook' for more information.")
19524 (defvar org-metaright-hook nil
19525 "Hook for functions attaching themselves to `M-right'.
19526 See `org-ctrl-c-ctrl-c-hook' for more information.")
19527 (defvar org-metaup-hook nil
19528 "Hook for functions attaching themselves to `M-up'.
19529 See `org-ctrl-c-ctrl-c-hook' for more information.")
19530 (defvar org-metadown-hook nil
19531 "Hook for functions attaching themselves to `M-down'.
19532 See `org-ctrl-c-ctrl-c-hook' for more information.")
19533 (defvar org-shiftmetaleft-hook nil
19534 "Hook for functions attaching themselves to `M-S-left'.
19535 See `org-ctrl-c-ctrl-c-hook' for more information.")
19536 (defvar org-shiftmetaright-hook nil
19537 "Hook for functions attaching themselves to `M-S-right'.
19538 See `org-ctrl-c-ctrl-c-hook' for more information.")
19539 (defvar org-shiftmetaup-hook nil
19540 "Hook for functions attaching themselves to `M-S-up'.
19541 See `org-ctrl-c-ctrl-c-hook' for more information.")
19542 (defvar org-shiftmetadown-hook nil
19543 "Hook for functions attaching themselves to `M-S-down'.
19544 See `org-ctrl-c-ctrl-c-hook' for more information.")
19545 (defvar org-metareturn-hook nil
19546 "Hook for functions attaching themselves to `M-RET'.
19547 See `org-ctrl-c-ctrl-c-hook' for more information.")
19548 (defvar org-shiftup-hook nil
19549 "Hook for functions attaching themselves to `S-up'.
19550 See `org-ctrl-c-ctrl-c-hook' for more information.")
19551 (defvar org-shiftup-final-hook nil
19552 "Hook for functions attaching themselves to `S-up'.
19553 This one runs after all other options except shift-select have been excluded.
19554 See `org-ctrl-c-ctrl-c-hook' for more information.")
19555 (defvar org-shiftdown-hook nil
19556 "Hook for functions attaching themselves to `S-down'.
19557 See `org-ctrl-c-ctrl-c-hook' for more information.")
19558 (defvar org-shiftdown-final-hook nil
19559 "Hook for functions attaching themselves to `S-down'.
19560 This one runs after all other options except shift-select have been excluded.
19561 See `org-ctrl-c-ctrl-c-hook' for more information.")
19562 (defvar org-shiftleft-hook nil
19563 "Hook for functions attaching themselves to `S-left'.
19564 See `org-ctrl-c-ctrl-c-hook' for more information.")
19565 (defvar org-shiftleft-final-hook nil
19566 "Hook for functions attaching themselves to `S-left'.
19567 This one runs after all other options except shift-select have been excluded.
19568 See `org-ctrl-c-ctrl-c-hook' for more information.")
19569 (defvar org-shiftright-hook nil
19570 "Hook for functions attaching themselves to `S-right'.
19571 See `org-ctrl-c-ctrl-c-hook' for more information.")
19572 (defvar org-shiftright-final-hook nil
19573 "Hook for functions attaching themselves to `S-right'.
19574 This one runs after all other options except shift-select have been excluded.
19575 See `org-ctrl-c-ctrl-c-hook' for more information.")
19577 (defun org-modifier-cursor-error ()
19578 "Throw an error, a modified cursor command was applied in wrong context."
19579 (user-error "This command is active in special context like tables, headlines or items"))
19581 (defun org-shiftselect-error ()
19582 "Throw an error because Shift-Cursor command was applied in wrong context."
19583 (if (and (boundp 'shift-select-mode) shift-select-mode)
19584 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19585 (user-error "This command works only in special context like headlines or timestamps")))
19587 (defun org-call-for-shift-select (cmd)
19588 (let ((this-command-keys-shift-translated t))
19589 (call-interactively cmd)))
19591 (defun org-shifttab (&optional arg)
19592 "Global visibility cycling or move to previous table field.
19593 Call `org-table-previous-field' within a table.
19594 When ARG is nil, cycle globally through visibility states.
19595 When ARG is a numeric prefix, show contents of this level."
19596 (interactive "P")
19597 (cond
19598 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19599 ((integerp arg)
19600 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19601 (message "Content view to level: %d" arg)
19602 (org-content (prefix-numeric-value arg2))
19603 (org-cycle-show-empty-lines t)
19604 (setq org-cycle-global-status 'overview)))
19605 (t (call-interactively 'org-global-cycle))))
19607 (defun org-shiftmetaleft ()
19608 "Promote subtree or delete table column.
19609 Calls `org-promote-subtree', `org-outdent-item-tree', or
19610 `org-table-delete-column', depending on context. See the
19611 individual commands for more information."
19612 (interactive)
19613 (cond
19614 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19615 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19616 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19617 ((if (not (org-region-active-p)) (org-at-item-p)
19618 (save-excursion (goto-char (region-beginning))
19619 (org-at-item-p)))
19620 (call-interactively 'org-outdent-item-tree))
19621 (t (org-modifier-cursor-error))))
19623 (defun org-shiftmetaright ()
19624 "Demote subtree or insert table column.
19625 Calls `org-demote-subtree', `org-indent-item-tree', or
19626 `org-table-insert-column', depending on context. See the
19627 individual commands for more information."
19628 (interactive)
19629 (cond
19630 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19631 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19632 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19633 ((if (not (org-region-active-p)) (org-at-item-p)
19634 (save-excursion (goto-char (region-beginning))
19635 (org-at-item-p)))
19636 (call-interactively 'org-indent-item-tree))
19637 (t (org-modifier-cursor-error))))
19639 (defun org-shiftmetaup (&optional arg)
19640 "Move subtree up or kill table row.
19641 Calls `org-move-subtree-up' or `org-table-kill-row' or
19642 `org-move-item-up' or `org-timestamp-up', depending on context.
19643 See the individual commands for more information."
19644 (interactive "P")
19645 (cond
19646 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19647 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19648 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19649 ((org-at-item-p) (call-interactively 'org-move-item-up))
19650 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19651 (call-interactively 'org-timestamp-up)))
19652 (t (call-interactively 'org-drag-line-backward))))
19654 (defun org-shiftmetadown (&optional arg)
19655 "Move subtree down or insert table row.
19656 Calls `org-move-subtree-down' or `org-table-insert-row' or
19657 `org-move-item-down' or `org-timestamp-up', depending on context.
19658 See the individual commands for more information."
19659 (interactive "P")
19660 (cond
19661 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19662 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19663 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19664 ((org-at-item-p) (call-interactively 'org-move-item-down))
19665 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19666 (call-interactively 'org-timestamp-down)))
19667 (t (call-interactively 'org-drag-line-forward))))
19669 (defsubst org-hidden-tree-error ()
19670 (user-error
19671 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19673 (defun org-metaleft (&optional arg)
19674 "Promote heading or move table column to left.
19675 Calls `org-do-promote' or `org-table-move-column', depending on context.
19676 With no specific context, calls the Emacs default `backward-word'.
19677 See the individual commands for more information."
19678 (interactive "P")
19679 (cond
19680 ((run-hook-with-args-until-success 'org-metaleft-hook))
19681 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19682 ((org-with-limited-levels
19683 (or (org-at-heading-p)
19684 (and (org-region-active-p)
19685 (save-excursion
19686 (goto-char (region-beginning))
19687 (org-at-heading-p)))))
19688 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19689 (call-interactively 'org-do-promote))
19690 ;; At an inline task.
19691 ((org-at-heading-p)
19692 (call-interactively 'org-inlinetask-promote))
19693 ((or (org-at-item-p)
19694 (and (org-region-active-p)
19695 (save-excursion
19696 (goto-char (region-beginning))
19697 (org-at-item-p))))
19698 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19699 (call-interactively 'org-outdent-item))
19700 (t (call-interactively 'backward-word))))
19702 (defun org-metaright (&optional arg)
19703 "Demote a subtree, a list item or move table column to right.
19704 In front of a drawer or a block keyword, indent it correctly.
19705 With no specific context, calls the Emacs default `forward-word'.
19706 See the individual commands for more information."
19707 (interactive "P")
19708 (cond
19709 ((run-hook-with-args-until-success 'org-metaright-hook))
19710 ((org-at-table-p) (call-interactively 'org-table-move-column))
19711 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19712 ((org-at-block-p) (call-interactively 'org-indent-block))
19713 ((org-with-limited-levels
19714 (or (org-at-heading-p)
19715 (and (org-region-active-p)
19716 (save-excursion
19717 (goto-char (region-beginning))
19718 (org-at-heading-p)))))
19719 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19720 (call-interactively 'org-do-demote))
19721 ;; At an inline task.
19722 ((org-at-heading-p)
19723 (call-interactively 'org-inlinetask-demote))
19724 ((or (org-at-item-p)
19725 (and (org-region-active-p)
19726 (save-excursion
19727 (goto-char (region-beginning))
19728 (org-at-item-p))))
19729 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19730 (call-interactively 'org-indent-item))
19731 (t (call-interactively 'forward-word))))
19733 (defun org-check-for-hidden (what)
19734 "Check if there are hidden headlines/items in the current visual line.
19735 WHAT can be either `headlines' or `items'. If the current line is
19736 an outline or item heading and it has a folded subtree below it,
19737 this function returns t, nil otherwise."
19738 (let ((re (cond
19739 ((eq what 'headlines) org-outline-regexp-bol)
19740 ((eq what 'items) (org-item-beginning-re))
19741 (t (error "This should not happen"))))
19742 beg end)
19743 (save-excursion
19744 (catch 'exit
19745 (unless (org-region-active-p)
19746 (setq beg (point-at-bol))
19747 (beginning-of-line 2)
19748 (while (and (not (eobp)) ;; this is like `next-line'
19749 (get-char-property (1- (point)) 'invisible))
19750 (beginning-of-line 2))
19751 (setq end (point))
19752 (goto-char beg)
19753 (goto-char (point-at-eol))
19754 (setq end (max end (point)))
19755 (while (re-search-forward re end t)
19756 (if (get-char-property (match-beginning 0) 'invisible)
19757 (throw 'exit t))))
19758 nil))))
19760 (defun org-metaup (&optional arg)
19761 "Move subtree up or move table row up.
19762 Calls `org-move-subtree-up' or `org-table-move-row' or
19763 `org-move-item-up', depending on context. See the individual commands
19764 for more information."
19765 (interactive "P")
19766 (cond
19767 ((run-hook-with-args-until-success 'org-metaup-hook))
19768 ((org-region-active-p)
19769 (let* ((a (min (region-beginning) (region-end)))
19770 (b (1- (max (region-beginning) (region-end))))
19771 (c (save-excursion (goto-char a)
19772 (move-beginning-of-line 0)))
19773 (d (save-excursion (goto-char a)
19774 (move-end-of-line 0) (point))))
19775 (transpose-regions a b c d)
19776 (goto-char c)))
19777 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19778 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19779 ((org-at-item-p) (call-interactively 'org-move-item-up))
19780 (t (org-drag-element-backward))))
19782 (defun org-metadown (&optional arg)
19783 "Move subtree down or move table row down.
19784 Calls `org-move-subtree-down' or `org-table-move-row' or
19785 `org-move-item-down', depending on context. See the individual
19786 commands for more information."
19787 (interactive "P")
19788 (cond
19789 ((run-hook-with-args-until-success 'org-metadown-hook))
19790 ((org-region-active-p)
19791 (let* ((a (min (region-beginning) (region-end)))
19792 (b (max (region-beginning) (region-end)))
19793 (c (save-excursion (goto-char b)
19794 (move-beginning-of-line 1)))
19795 (d (save-excursion (goto-char b)
19796 (move-end-of-line 1) (1+ (point)))))
19797 (transpose-regions a b c d)
19798 (goto-char d)))
19799 ((org-at-table-p) (call-interactively 'org-table-move-row))
19800 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19801 ((org-at-item-p) (call-interactively 'org-move-item-down))
19802 (t (org-drag-element-forward))))
19804 (defun org-shiftup (&optional arg)
19805 "Increase item in timestamp or increase priority of current headline.
19806 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19807 depending on context. See the individual commands for more information."
19808 (interactive "P")
19809 (cond
19810 ((run-hook-with-args-until-success 'org-shiftup-hook))
19811 ((and org-support-shift-select (org-region-active-p))
19812 (org-call-for-shift-select 'previous-line))
19813 ((org-at-timestamp-p t)
19814 (call-interactively (if org-edit-timestamp-down-means-later
19815 'org-timestamp-down 'org-timestamp-up)))
19816 ((and (not (eq org-support-shift-select 'always))
19817 org-enable-priority-commands
19818 (org-at-heading-p))
19819 (call-interactively 'org-priority-up))
19820 ((and (not org-support-shift-select) (org-at-item-p))
19821 (call-interactively 'org-previous-item))
19822 ((org-clocktable-try-shift 'up arg))
19823 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19824 (org-support-shift-select
19825 (org-call-for-shift-select 'previous-line))
19826 (t (org-shiftselect-error))))
19828 (defun org-shiftdown (&optional arg)
19829 "Decrease item in timestamp or decrease priority of current headline.
19830 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19831 depending on context. See the individual commands for more information."
19832 (interactive "P")
19833 (cond
19834 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19835 ((and org-support-shift-select (org-region-active-p))
19836 (org-call-for-shift-select 'next-line))
19837 ((org-at-timestamp-p t)
19838 (call-interactively (if org-edit-timestamp-down-means-later
19839 'org-timestamp-up 'org-timestamp-down)))
19840 ((and (not (eq org-support-shift-select 'always))
19841 org-enable-priority-commands
19842 (org-at-heading-p))
19843 (call-interactively 'org-priority-down))
19844 ((and (not org-support-shift-select) (org-at-item-p))
19845 (call-interactively 'org-next-item))
19846 ((org-clocktable-try-shift 'down arg))
19847 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19848 (org-support-shift-select
19849 (org-call-for-shift-select 'next-line))
19850 (t (org-shiftselect-error))))
19852 (defun org-shiftright (&optional arg)
19853 "Cycle the thing at point or in the current line, depending on context.
19854 Depending on context, this does one of the following:
19856 - switch a timestamp at point one day into the future
19857 - on a headline, switch to the next TODO keyword.
19858 - on an item, switch entire list to the next bullet type
19859 - on a property line, switch to the next allowed value
19860 - on a clocktable definition line, move time block into the future"
19861 (interactive "P")
19862 (cond
19863 ((run-hook-with-args-until-success 'org-shiftright-hook))
19864 ((and org-support-shift-select (org-region-active-p))
19865 (org-call-for-shift-select 'forward-char))
19866 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19867 ((and (not (eq org-support-shift-select 'always))
19868 (org-at-heading-p))
19869 (let ((org-inhibit-logging
19870 (not org-treat-S-cursor-todo-selection-as-state-change))
19871 (org-inhibit-blocking
19872 (not org-treat-S-cursor-todo-selection-as-state-change)))
19873 (org-call-with-arg 'org-todo 'right)))
19874 ((or (and org-support-shift-select
19875 (not (eq org-support-shift-select 'always))
19876 (org-at-item-bullet-p))
19877 (and (not org-support-shift-select) (org-at-item-p)))
19878 (org-call-with-arg 'org-cycle-list-bullet nil))
19879 ((and (not (eq org-support-shift-select 'always))
19880 (org-at-property-p))
19881 (call-interactively 'org-property-next-allowed-value))
19882 ((org-clocktable-try-shift 'right arg))
19883 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19884 (org-support-shift-select
19885 (org-call-for-shift-select 'forward-char))
19886 (t (org-shiftselect-error))))
19888 (defun org-shiftleft (&optional arg)
19889 "Cycle the thing at point or in the current line, depending on context.
19890 Depending on context, this does one of the following:
19892 - switch a timestamp at point one day into the past
19893 - on a headline, switch to the previous TODO keyword.
19894 - on an item, switch entire list to the previous bullet type
19895 - on a property line, switch to the previous allowed value
19896 - on a clocktable definition line, move time block into the past"
19897 (interactive "P")
19898 (cond
19899 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19900 ((and org-support-shift-select (org-region-active-p))
19901 (org-call-for-shift-select 'backward-char))
19902 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19903 ((and (not (eq org-support-shift-select 'always))
19904 (org-at-heading-p))
19905 (let ((org-inhibit-logging
19906 (not org-treat-S-cursor-todo-selection-as-state-change))
19907 (org-inhibit-blocking
19908 (not org-treat-S-cursor-todo-selection-as-state-change)))
19909 (org-call-with-arg 'org-todo 'left)))
19910 ((or (and org-support-shift-select
19911 (not (eq org-support-shift-select 'always))
19912 (org-at-item-bullet-p))
19913 (and (not org-support-shift-select) (org-at-item-p)))
19914 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19915 ((and (not (eq org-support-shift-select 'always))
19916 (org-at-property-p))
19917 (call-interactively 'org-property-previous-allowed-value))
19918 ((org-clocktable-try-shift 'left arg))
19919 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19920 (org-support-shift-select
19921 (org-call-for-shift-select 'backward-char))
19922 (t (org-shiftselect-error))))
19924 (defun org-shiftcontrolright ()
19925 "Switch to next TODO set."
19926 (interactive)
19927 (cond
19928 ((and org-support-shift-select (org-region-active-p))
19929 (org-call-for-shift-select 'forward-word))
19930 ((and (not (eq org-support-shift-select 'always))
19931 (org-at-heading-p))
19932 (org-call-with-arg 'org-todo 'nextset))
19933 (org-support-shift-select
19934 (org-call-for-shift-select 'forward-word))
19935 (t (org-shiftselect-error))))
19937 (defun org-shiftcontrolleft ()
19938 "Switch to previous TODO set."
19939 (interactive)
19940 (cond
19941 ((and org-support-shift-select (org-region-active-p))
19942 (org-call-for-shift-select 'backward-word))
19943 ((and (not (eq org-support-shift-select 'always))
19944 (org-at-heading-p))
19945 (org-call-with-arg 'org-todo 'previousset))
19946 (org-support-shift-select
19947 (org-call-for-shift-select 'backward-word))
19948 (t (org-shiftselect-error))))
19950 (defun org-shiftcontrolup (&optional n)
19951 "Change timestamps synchronously up in CLOCK log lines.
19952 Optional argument N tells to change by that many units."
19953 (interactive "P")
19954 (cond ((and (not org-support-shift-select)
19955 (org-at-clock-log-p)
19956 (org-at-timestamp-p t))
19957 (org-clock-timestamps-up n))
19958 (t (org-shiftselect-error))))
19960 (defun org-shiftcontroldown (&optional n)
19961 "Change timestamps synchronously down in CLOCK log lines.
19962 Optional argument N tells to change by that many units."
19963 (interactive "P")
19964 (cond ((and (not org-support-shift-select)
19965 (org-at-clock-log-p)
19966 (org-at-timestamp-p t))
19967 (org-clock-timestamps-down n))
19968 (t (org-shiftselect-error))))
19970 (defun org-ctrl-c-ret ()
19971 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19972 (interactive)
19973 (cond
19974 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19975 (t (call-interactively 'org-insert-heading))))
19977 (defun org-find-visible ()
19978 (let ((s (point)))
19979 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19980 (get-char-property s 'invisible)))
19982 (defun org-find-invisible ()
19983 (let ((s (point)))
19984 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19985 (not (get-char-property s 'invisible))))
19988 (defun org-copy-visible (beg end)
19989 "Copy the visible parts of the region."
19990 (interactive "r")
19991 (let (snippets s)
19992 (save-excursion
19993 (save-restriction
19994 (narrow-to-region beg end)
19995 (setq s (goto-char (point-min)))
19996 (while (not (= (point) (point-max)))
19997 (goto-char (org-find-invisible))
19998 (push (buffer-substring s (point)) snippets)
19999 (setq s (goto-char (org-find-visible))))))
20000 (kill-new (apply 'concat (nreverse snippets)))))
20002 (defun org-copy-special ()
20003 "Copy region in table or copy current subtree.
20004 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20005 See the individual commands for more information."
20006 (interactive)
20007 (call-interactively
20008 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20010 (defun org-cut-special ()
20011 "Cut region in table or cut current subtree.
20012 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20013 See the individual commands for more information."
20014 (interactive)
20015 (call-interactively
20016 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20018 (defun org-paste-special (arg)
20019 "Paste rectangular region into table, or past subtree relative to level.
20020 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20021 See the individual commands for more information."
20022 (interactive "P")
20023 (if (org-at-table-p)
20024 (org-table-paste-rectangle)
20025 (org-paste-subtree arg)))
20027 (defsubst org-in-fixed-width-region-p ()
20028 "Is point in a fixed-width region?"
20029 (save-match-data
20030 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20032 (defun org-edit-special (&optional arg)
20033 "Call a special editor for the element at point.
20034 When at a table, call the formula editor with `org-table-edit-formulas'.
20035 When in a source code block, call `org-edit-src-code'.
20036 When in a fixed-width region, call `org-edit-fixed-width-region'.
20037 When at an #+INCLUDE keyword, visit the included file.
20038 On a link, call `ffap' to visit the link at point.
20039 Otherwise, return a user error."
20040 (interactive "P")
20041 (let ((element (org-element-at-point)))
20042 (assert (not buffer-read-only) nil
20043 "Buffer is read-only: %s" (buffer-name))
20044 (case (org-element-type element)
20045 (src-block
20046 (if (not arg) (org-edit-src-code)
20047 (let* ((info (org-babel-get-src-block-info))
20048 (lang (nth 0 info))
20049 (params (nth 2 info))
20050 (session (cdr (assq :session params))))
20051 (if (not session) (org-edit-src-code)
20052 ;; At a src-block with a session and function called with
20053 ;; an ARG: switch to the buffer related to the inferior
20054 ;; process.
20055 (switch-to-buffer
20056 (funcall (intern (concat "org-babel-prep-session:" lang))
20057 session params))))))
20058 (keyword
20059 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20060 (find-file
20061 (org-remove-double-quotes
20062 (car (org-split-string (org-element-property :value element)))))
20063 (user-error "No special environment to edit here")))
20064 (table
20065 (if (eq (org-element-property :type element) 'table.el)
20066 (org-edit-src-code)
20067 (call-interactively 'org-table-edit-formulas)))
20068 ;; Only Org tables contain `table-row' type elements.
20069 (table-row (call-interactively 'org-table-edit-formulas))
20070 ((example-block export-block) (org-edit-src-code))
20071 (fixed-width (org-edit-fixed-width-region))
20072 (otherwise
20073 ;; No notable element at point. Though, we may be at a link,
20074 ;; which is an object. Thus, scan deeper.
20075 (if (eq (org-element-type (org-element-context element)) 'link)
20076 (call-interactively 'ffap)
20077 (user-error "No special environment to edit here"))))))
20079 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20080 (defun org-ctrl-c-ctrl-c (&optional arg)
20081 "Set tags in headline, or update according to changed information at point.
20083 This command does many different things, depending on context:
20085 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20086 this is what we do.
20088 - If the cursor is on a statistics cookie, update it.
20090 - If the cursor is in a headline, prompt for tags and insert them
20091 into the current line, aligned to `org-tags-column'. When called
20092 with prefix arg, realign all tags in the current buffer.
20094 - If the cursor is in one of the special #+KEYWORD lines, this
20095 triggers scanning the buffer for these lines and updating the
20096 information.
20098 - If the cursor is inside a table, realign the table. This command
20099 works even if the automatic table editor has been turned off.
20101 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20102 the entire table.
20104 - If the cursor is at a footnote reference or definition, jump to
20105 the corresponding definition or references, respectively.
20107 - If the cursor is a the beginning of a dynamic block, update it.
20109 - If the current buffer is a capture buffer, close note and file it.
20111 - If the cursor is on a <<<target>>>, update radio targets and
20112 corresponding links in this buffer.
20114 - If the cursor is on a numbered item in a plain list, renumber the
20115 ordered list.
20117 - If the cursor is on a checkbox, toggle it.
20119 - If the cursor is on a code block, evaluate it. The variable
20120 `org-confirm-babel-evaluate' can be used to control prompting
20121 before code block evaluation, by default every code block
20122 evaluation requires confirmation. Code block evaluation can be
20123 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20124 (interactive "P")
20125 (cond
20126 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20127 org-occur-highlights
20128 org-latex-fragment-image-overlays)
20129 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20130 (org-remove-occur-highlights)
20131 (org-remove-latex-fragment-image-overlays)
20132 (message "Temporary highlights/overlays removed from current buffer"))
20133 ((and (local-variable-p 'org-finish-function (current-buffer))
20134 (fboundp org-finish-function))
20135 (funcall org-finish-function))
20136 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20138 (let* ((context (org-element-context)) (type (org-element-type context)))
20139 ;; Test if point is within a blank line.
20140 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20141 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20142 (user-error "C-c C-c can do nothing useful at this location"))
20143 ;; For convenience: at the first line of a paragraph on the
20144 ;; same line as an item, apply function on that item instead.
20145 (when (eq type 'paragraph)
20146 (let ((parent (org-element-property :parent context)))
20147 (when (and (eq (org-element-type parent) 'item)
20148 (= (point-at-bol) (org-element-property :begin parent)))
20149 (setq context parent type 'item))))
20150 ;; Act according to type of element or object at point.
20151 (case type
20152 (clock (org-clock-update-time-maybe))
20153 (dynamic-block
20154 (save-excursion
20155 (goto-char (org-element-property :post-affiliated context))
20156 (org-update-dblock)))
20157 (footnote-definition
20158 (goto-char (org-element-property :post-affiliated context))
20159 (call-interactively 'org-footnote-action))
20160 (footnote-reference (call-interactively 'org-footnote-action))
20161 ((headline inlinetask)
20162 (save-excursion (goto-char (org-element-property :begin context))
20163 (call-interactively 'org-set-tags)))
20164 (item
20165 ;; At an item: a double C-u set checkbox to "[-]"
20166 ;; unconditionally, whereas a single one will toggle its
20167 ;; presence. Without an universal argument, if the item
20168 ;; has a checkbox, toggle it. Otherwise repair the list.
20169 (let* ((box (org-element-property :checkbox context))
20170 (struct (org-element-property :structure context))
20171 (old-struct (copy-tree struct))
20172 (parents (org-list-parents-alist struct))
20173 (prevs (org-list-prevs-alist struct))
20174 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20175 (org-list-set-checkbox
20176 (org-element-property :begin context) struct
20177 (cond ((equal arg '(16)) "[-]")
20178 ((and (not box) (equal arg '(4))) "[ ]")
20179 ((or (not box) (equal arg '(4))) nil)
20180 ((eq box 'on) "[ ]")
20181 (t "[X]")))
20182 ;; Mimic `org-list-write-struct' but with grabbing
20183 ;; a return value from `org-list-struct-fix-box'.
20184 (org-list-struct-fix-ind struct parents 2)
20185 (org-list-struct-fix-item-end struct)
20186 (org-list-struct-fix-bul struct prevs)
20187 (org-list-struct-fix-ind struct parents)
20188 (let ((block-item
20189 (org-list-struct-fix-box struct parents prevs orderedp)))
20190 (if (and box (equal struct old-struct))
20191 (if (equal arg '(16))
20192 (message "Checkboxes already reset")
20193 (user-error "Cannot toggle this checkbox: %s"
20194 (if (eq box 'on)
20195 "all subitems checked"
20196 "unchecked subitems")))
20197 (org-list-struct-apply-struct struct old-struct)
20198 (org-update-checkbox-count-maybe))
20199 (when block-item
20200 (message "Checkboxes were removed due to empty box at line %d"
20201 (org-current-line block-item))))))
20202 (keyword
20203 (let ((org-inhibit-startup-visibility-stuff t)
20204 (org-startup-align-all-tables nil))
20205 (when (boundp 'org-table-coordinate-overlays)
20206 (mapc 'delete-overlay org-table-coordinate-overlays)
20207 (setq org-table-coordinate-overlays nil))
20208 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20209 (message "Local setup has been refreshed"))
20210 (plain-list
20211 ;; At a plain list, with a double C-u argument, set
20212 ;; checkboxes of each item to "[-]", whereas a single one
20213 ;; will toggle their presence according to the state of the
20214 ;; first item in the list. Without an argument, repair the
20215 ;; list.
20216 (let* ((begin (org-element-property :contents-begin context))
20217 (beginm (move-marker (make-marker) begin))
20218 (struct (org-element-property :structure context))
20219 (old-struct (copy-tree struct))
20220 (first-box (save-excursion
20221 (goto-char begin)
20222 (looking-at org-list-full-item-re)
20223 (match-string-no-properties 3)))
20224 (new-box (cond ((equal arg '(16)) "[-]")
20225 ((equal arg '(4)) (unless first-box "[ ]"))
20226 ((equal first-box "[X]") "[ ]")
20227 (t "[X]"))))
20228 (cond
20229 (arg
20230 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20231 (org-list-get-all-items
20232 begin struct (org-list-prevs-alist struct))))
20233 ((and first-box (eq (point) begin))
20234 ;; For convenience, when point is at bol on the first
20235 ;; item of the list and no argument is provided, simply
20236 ;; toggle checkbox of that item, if any.
20237 (org-list-set-checkbox begin struct new-box)))
20238 (org-list-write-struct
20239 struct (org-list-parents-alist struct) old-struct)
20240 (org-update-checkbox-count-maybe)
20241 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20242 ((property-drawer node-property)
20243 (call-interactively 'org-property-action))
20244 ((radio-target target)
20245 (call-interactively 'org-update-radio-target-regexp))
20246 (statistics-cookie
20247 (call-interactively 'org-update-statistics-cookies))
20248 ((table table-cell table-row)
20249 ;; At a table, recalculate every field and align it. Also
20250 ;; send the table if necessary. If the table has
20251 ;; a `table.el' type, just give up. At a table row or
20252 ;; cell, maybe recalculate line but always align table.
20253 (if (eq (org-element-property :type context) 'table.el)
20254 (message "Use C-c ' to edit table.el tables")
20255 (let ((org-enable-table-editor t))
20256 (if (or (eq type 'table)
20257 ;; Check if point is at a TBLFM line.
20258 (and (eq type 'table-row)
20259 (= (point) (org-element-property :end context))))
20260 (save-excursion
20261 (if (org-at-TBLFM-p)
20262 (progn (require 'org-table)
20263 (org-table-calc-current-TBLFM))
20264 (goto-char (org-element-property :contents-begin context))
20265 (org-call-with-arg 'org-table-recalculate (or arg t))
20266 (orgtbl-send-table 'maybe)))
20267 (org-table-maybe-eval-formula)
20268 (cond (arg (call-interactively 'org-table-recalculate))
20269 ((org-table-maybe-recalculate-line))
20270 (t (org-table-align)))))))
20271 (timestamp (org-timestamp-change 0 'day))
20272 (otherwise
20273 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20274 (user-error
20275 "C-c C-c can do nothing useful at this location")))))))))
20277 (defun org-mode-restart ()
20278 "Restart Org-mode, to scan again for special lines.
20279 Also updates the keyword regular expressions."
20280 (interactive)
20281 (org-mode)
20282 (message "Org-mode restarted"))
20284 (defun org-kill-note-or-show-branches ()
20285 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20286 (interactive)
20287 (if (not org-finish-function)
20288 (progn
20289 (hide-subtree)
20290 (call-interactively 'show-branches))
20291 (let ((org-note-abort t))
20292 (funcall org-finish-function))))
20294 (defun org-open-line (n)
20295 "Insert a new row in tables, call `open-line' elsewhere."
20296 (interactive "*p")
20297 (if (org-at-table-p)
20298 (org-table-insert-row)
20299 (open-line n)))
20301 (defun org-return (&optional indent)
20302 "Goto next table row or insert a newline.
20303 Calls `org-table-next-row' or `newline', depending on context.
20304 See the individual commands for more information."
20305 (interactive)
20306 (let (org-ts-what)
20307 (cond
20308 ((or (bobp) (org-in-src-block-p))
20309 (if indent (newline-and-indent) (newline)))
20310 ((org-at-table-p)
20311 (org-table-justify-field-maybe)
20312 (call-interactively 'org-table-next-row))
20313 ;; when `newline-and-indent' is called within a list, make sure
20314 ;; text moved stays inside the item.
20315 ((and (org-in-item-p) indent)
20316 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20317 (progn
20318 (save-match-data (newline))
20319 (org-indent-line-to (length (match-string 0))))
20320 (let ((ind (org-get-indentation)))
20321 (newline)
20322 (if (org-looking-back org-list-end-re)
20323 (org-indent-line)
20324 (org-indent-line-to ind)))))
20325 ((and org-return-follows-link
20326 (org-at-timestamp-p t)
20327 (not (eq org-ts-what 'after)))
20328 (org-follow-timestamp-link))
20329 ((and org-return-follows-link
20330 (let ((tprop (get-text-property (point) 'face)))
20331 (or (eq tprop 'org-link)
20332 (and (listp tprop) (memq 'org-link tprop)))))
20333 (call-interactively 'org-open-at-point))
20334 ((and (org-at-heading-p)
20335 (looking-at
20336 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20337 (org-show-entry)
20338 (end-of-line 1)
20339 (newline))
20340 (t (if indent (newline-and-indent) (newline))))))
20342 (defun org-return-indent ()
20343 "Goto next table row or insert a newline and indent.
20344 Calls `org-table-next-row' or `newline-and-indent', depending on
20345 context. See the individual commands for more information."
20346 (interactive)
20347 (org-return t))
20349 (defun org-ctrl-c-star ()
20350 "Compute table, or change heading status of lines.
20351 Calls `org-table-recalculate' or `org-toggle-heading',
20352 depending on context."
20353 (interactive)
20354 (cond
20355 ((org-at-table-p)
20356 (call-interactively 'org-table-recalculate))
20358 ;; Convert all lines in region to list items
20359 (call-interactively 'org-toggle-heading))))
20361 (defun org-ctrl-c-minus ()
20362 "Insert separator line in table or modify bullet status of line.
20363 Also turns a plain line or a region of lines into list items.
20364 Calls `org-table-insert-hline', `org-toggle-item', or
20365 `org-cycle-list-bullet', depending on context."
20366 (interactive)
20367 (cond
20368 ((org-at-table-p)
20369 (call-interactively 'org-table-insert-hline))
20370 ((org-region-active-p)
20371 (call-interactively 'org-toggle-item))
20372 ((org-in-item-p)
20373 (call-interactively 'org-cycle-list-bullet))
20375 (call-interactively 'org-toggle-item))))
20377 (defun org-toggle-item (arg)
20378 "Convert headings or normal lines to items, items to normal lines.
20379 If there is no active region, only the current line is considered.
20381 If the first non blank line in the region is a headline, convert
20382 all headlines to items, shifting text accordingly.
20384 If it is an item, convert all items to normal lines.
20386 If it is normal text, change region into a list of items.
20387 With a prefix argument ARG, change the region in a single item."
20388 (interactive "P")
20389 (let ((shift-text
20390 (function
20391 ;; Shift text in current section to IND, from point to END.
20392 ;; The function leaves point to END line.
20393 (lambda (ind end)
20394 (let ((min-i 1000) (end (copy-marker end)))
20395 ;; First determine the minimum indentation (MIN-I) of
20396 ;; the text.
20397 (save-excursion
20398 (catch 'exit
20399 (while (< (point) end)
20400 (let ((i (org-get-indentation)))
20401 (cond
20402 ;; Skip blank lines and inline tasks.
20403 ((looking-at "^[ \t]*$"))
20404 ((looking-at org-outline-regexp-bol))
20405 ;; We can't find less than 0 indentation.
20406 ((zerop i) (throw 'exit (setq min-i 0)))
20407 ((< i min-i) (setq min-i i))))
20408 (forward-line))))
20409 ;; Then indent each line so that a line indented to
20410 ;; MIN-I becomes indented to IND. Ignore blank lines
20411 ;; and inline tasks in the process.
20412 (let ((delta (- ind min-i)))
20413 (while (< (point) end)
20414 (unless (or (looking-at "^[ \t]*$")
20415 (looking-at org-outline-regexp-bol))
20416 (org-indent-line-to (+ (org-get-indentation) delta)))
20417 (forward-line)))))))
20418 (skip-blanks
20419 (function
20420 ;; Return beginning of first non-blank line, starting from
20421 ;; line at POS.
20422 (lambda (pos)
20423 (save-excursion
20424 (goto-char pos)
20425 (skip-chars-forward " \r\t\n")
20426 (point-at-bol)))))
20427 beg end)
20428 ;; Determine boundaries of changes.
20429 (if (org-region-active-p)
20430 (setq beg (funcall skip-blanks (region-beginning))
20431 end (copy-marker (region-end)))
20432 (setq beg (funcall skip-blanks (point-at-bol))
20433 end (copy-marker (point-at-eol))))
20434 ;; Depending on the starting line, choose an action on the text
20435 ;; between BEG and END.
20436 (org-with-limited-levels
20437 (save-excursion
20438 (goto-char beg)
20439 (cond
20440 ;; Case 1. Start at an item: de-itemize. Note that it only
20441 ;; happens when a region is active: `org-ctrl-c-minus'
20442 ;; would call `org-cycle-list-bullet' otherwise.
20443 ((org-at-item-p)
20444 (while (< (point) end)
20445 (when (org-at-item-p)
20446 (skip-chars-forward " \t")
20447 (delete-region (point) (match-end 0)))
20448 (forward-line)))
20449 ;; Case 2. Start at an heading: convert to items.
20450 ((org-at-heading-p)
20451 (let* ((bul (org-list-bullet-string "-"))
20452 (bul-len (length bul))
20453 ;; Indentation of the first heading. It should be
20454 ;; relative to the indentation of its parent, if any.
20455 (start-ind (save-excursion
20456 (cond
20457 ((not org-adapt-indentation) 0)
20458 ((not (outline-previous-heading)) 0)
20459 (t (length (match-string 0))))))
20460 ;; Level of first heading. Further headings will be
20461 ;; compared to it to determine hierarchy in the list.
20462 (ref-level (org-reduced-level (org-outline-level))))
20463 (while (< (point) end)
20464 (let* ((level (org-reduced-level (org-outline-level)))
20465 (delta (max 0 (- level ref-level))))
20466 ;; If current headline is less indented than the first
20467 ;; one, set it as reference, in order to preserve
20468 ;; subtrees.
20469 (when (< level ref-level) (setq ref-level level))
20470 (replace-match bul t t)
20471 (org-indent-line-to (+ start-ind (* delta bul-len)))
20472 ;; Ensure all text down to END (or SECTION-END) belongs
20473 ;; to the newly created item.
20474 (let ((section-end (save-excursion
20475 (or (outline-next-heading) (point)))))
20476 (forward-line)
20477 (funcall shift-text
20478 (+ start-ind (* (1+ delta) bul-len))
20479 (min end section-end)))))))
20480 ;; Case 3. Normal line with ARG: make the first line of region
20481 ;; an item, and shift indentation of others lines to
20482 ;; set them as item's body.
20483 (arg (let* ((bul (org-list-bullet-string "-"))
20484 (bul-len (length bul))
20485 (ref-ind (org-get-indentation)))
20486 (skip-chars-forward " \t")
20487 (insert bul)
20488 (forward-line)
20489 (while (< (point) end)
20490 ;; Ensure that lines less indented than first one
20491 ;; still get included in item body.
20492 (funcall shift-text
20493 (+ ref-ind bul-len)
20494 (min end (save-excursion (or (outline-next-heading)
20495 (point)))))
20496 (forward-line))))
20497 ;; Case 4. Normal line without ARG: turn each non-item line
20498 ;; into an item.
20500 (while (< (point) end)
20501 (unless (or (org-at-heading-p) (org-at-item-p))
20502 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20503 (replace-match
20504 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20505 (forward-line))))))))
20507 (defun org-toggle-heading (&optional nstars)
20508 "Convert headings to normal text, or items or text to headings.
20509 If there is no active region, only convert the current line.
20511 With a \\[universal-argument] prefix, convert the whole list at
20512 point into heading.
20514 In a region:
20516 - If the first non blank line is a headline, remove the stars
20517 from all headlines in the region.
20519 - If it is a normal line, turn each and every normal line (i.e.,
20520 not an heading or an item) in the region into headings. If you
20521 want to convert only the first line of this region, use one
20522 universal prefix argument.
20524 - If it is a plain list item, turn all plain list items into headings.
20526 When converting a line into a heading, the number of stars is chosen
20527 such that the lines become children of the current entry. However,
20528 when a numeric prefix argument is given, its value determines the
20529 number of stars to add."
20530 (interactive "P")
20531 (let ((skip-blanks
20532 (function
20533 ;; Return beginning of first non-blank line, starting from
20534 ;; line at POS.
20535 (lambda (pos)
20536 (save-excursion
20537 (goto-char pos)
20538 (while (org-at-comment-p) (forward-line))
20539 (skip-chars-forward " \r\t\n")
20540 (point-at-bol)))))
20541 beg end toggled)
20542 ;; Determine boundaries of changes. If a universal prefix has
20543 ;; been given, put the list in a region. If region ends at a bol,
20544 ;; do not consider the last line to be in the region.
20546 (when (and current-prefix-arg (org-at-item-p))
20547 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20548 (org-mark-element))
20550 (if (org-region-active-p)
20551 (setq beg (funcall skip-blanks (region-beginning))
20552 end (copy-marker (save-excursion
20553 (goto-char (region-end))
20554 (if (bolp) (point) (point-at-eol)))))
20555 (setq beg (funcall skip-blanks (point-at-bol))
20556 end (copy-marker (point-at-eol))))
20557 ;; Ensure inline tasks don't count as headings.
20558 (org-with-limited-levels
20559 (save-excursion
20560 (goto-char beg)
20561 (cond
20562 ;; Case 1. Started at an heading: de-star headings.
20563 ((org-at-heading-p)
20564 (while (< (point) end)
20565 (when (org-at-heading-p t)
20566 (looking-at org-outline-regexp) (replace-match "")
20567 (setq toggled t))
20568 (forward-line)))
20569 ;; Case 2. Started at an item: change items into headlines.
20570 ;; One star will be added by `org-list-to-subtree'.
20571 ((org-at-item-p)
20572 (let* ((stars (make-string
20573 ;; subtract the star that will be added again by
20574 ;; `org-list-to-subtree'
20575 (if (numberp nstars) (1- nstars)
20576 (or (org-current-level) 0))
20577 ?*))
20578 (add-stars
20579 (cond (nstars "") ; stars from prefix only
20580 ((equal stars "") "") ; before first heading
20581 (org-odd-levels-only "*") ; inside heading, odd
20582 (t "")))) ; inside heading, oddeven
20583 (while (< (point) end)
20584 (when (org-at-item-p)
20585 ;; Pay attention to cases when region ends before list.
20586 (let* ((struct (org-list-struct))
20587 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20588 (save-restriction
20589 (narrow-to-region (point) list-end)
20590 (insert
20591 (org-list-to-subtree
20592 (org-list-parse-list t)
20593 '(:istart (concat stars add-stars (funcall get-stars depth))
20594 :icount (concat stars add-stars (funcall get-stars depth)))))))
20595 (setq toggled t))
20596 (forward-line))))
20597 ;; Case 3. Started at normal text: make every line an heading,
20598 ;; skipping headlines and items.
20599 (t (let* ((stars
20600 (make-string
20601 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20602 (add-stars
20603 (cond (nstars "") ; stars from prefix only
20604 ((equal stars "") "*") ; before first heading
20605 (org-odd-levels-only "**") ; inside heading, odd
20606 (t "*"))) ; inside heading, oddeven
20607 (rpl (concat stars add-stars " "))
20608 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20609 (while (< (point) (if (equal nstars '(4)) lend end))
20610 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20611 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20612 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20613 (forward-line)))))))
20614 (unless toggled (message "Cannot toggle heading from here"))))
20616 (defun org-meta-return (&optional arg)
20617 "Insert a new heading or wrap a region in a table.
20618 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
20619 See the individual commands for more information."
20620 (interactive "P")
20621 (org-check-before-invisible-edit 'insert)
20622 (cond
20623 ((run-hook-with-args-until-success 'org-metareturn-hook))
20624 ((or (org-at-drawer-p) (org-in-drawer-p) (org-at-property-p))
20625 (newline-and-indent))
20626 ((org-at-table-p)
20627 (call-interactively 'org-table-wrap-region))
20628 (t (call-interactively 'org-insert-heading))))
20630 ;;; Menu entries
20632 (defsubst org-in-subtree-not-table-p ()
20633 "Are we in a subtree and not in a table?"
20634 (and (not (org-before-first-heading-p))
20635 (not (org-at-table-p))))
20637 ;; Define the Org-mode menus
20638 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20639 '("Tbl"
20640 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20641 ["Next Field" org-cycle (org-at-table-p)]
20642 ["Previous Field" org-shifttab (org-at-table-p)]
20643 ["Next Row" org-return (org-at-table-p)]
20644 "--"
20645 ["Blank Field" org-table-blank-field (org-at-table-p)]
20646 ["Edit Field" org-table-edit-field (org-at-table-p)]
20647 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20648 "--"
20649 ("Column"
20650 ["Move Column Left" org-metaleft (org-at-table-p)]
20651 ["Move Column Right" org-metaright (org-at-table-p)]
20652 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20653 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20654 ("Row"
20655 ["Move Row Up" org-metaup (org-at-table-p)]
20656 ["Move Row Down" org-metadown (org-at-table-p)]
20657 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20658 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20659 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20660 "--"
20661 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20662 ("Rectangle"
20663 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20664 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20665 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20666 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20667 "--"
20668 ("Calculate"
20669 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20670 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20671 ["Edit Formulas" org-edit-special (org-at-table-p)]
20672 "--"
20673 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20674 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20675 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20676 "--"
20677 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20678 "--"
20679 ["Sum Column/Rectangle" org-table-sum
20680 (or (org-at-table-p) (org-region-active-p))]
20681 ["Which Column?" org-table-current-column (org-at-table-p)])
20682 ["Debug Formulas"
20683 org-table-toggle-formula-debugger
20684 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20685 ["Show Col/Row Numbers"
20686 org-table-toggle-coordinate-overlays
20687 :style toggle
20688 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20689 "--"
20690 ["Create" org-table-create (and (not (org-at-table-p))
20691 org-enable-table-editor)]
20692 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20693 ["Import from File" org-table-import (not (org-at-table-p))]
20694 ["Export to File" org-table-export (org-at-table-p)]
20695 "--"
20696 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20698 (easy-menu-define org-org-menu org-mode-map "Org menu"
20699 '("Org"
20700 ("Show/Hide"
20701 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20702 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20703 ["Sparse Tree..." org-sparse-tree t]
20704 ["Reveal Context" org-reveal t]
20705 ["Show All" show-all t]
20706 "--"
20707 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20708 "--"
20709 ["New Heading" org-insert-heading t]
20710 ("Navigate Headings"
20711 ["Up" outline-up-heading t]
20712 ["Next" outline-next-visible-heading t]
20713 ["Previous" outline-previous-visible-heading t]
20714 ["Next Same Level" outline-forward-same-level t]
20715 ["Previous Same Level" outline-backward-same-level t]
20716 "--"
20717 ["Jump" org-goto t])
20718 ("Edit Structure"
20719 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20720 "--"
20721 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20722 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20723 "--"
20724 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20725 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20726 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20727 "--"
20728 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20729 "--"
20730 ["Copy visible text" org-copy-visible t]
20731 "--"
20732 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20733 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20734 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20735 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20736 "--"
20737 ["Sort Region/Children" org-sort t]
20738 "--"
20739 ["Convert to odd levels" org-convert-to-odd-levels t]
20740 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20741 ("Editing"
20742 ["Emphasis..." org-emphasize t]
20743 ["Edit Source Example" org-edit-special t]
20744 "--"
20745 ["Footnote new/jump" org-footnote-action t]
20746 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20747 ("Archive"
20748 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20749 "--"
20750 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20751 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20752 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20754 "--"
20755 ("Hyperlinks"
20756 ["Store Link (Global)" org-store-link t]
20757 ["Find existing link to here" org-occur-link-in-agenda-files t]
20758 ["Insert Link" org-insert-link t]
20759 ["Follow Link" org-open-at-point t]
20760 "--"
20761 ["Next link" org-next-link t]
20762 ["Previous link" org-previous-link t]
20763 "--"
20764 ["Descriptive Links"
20765 org-toggle-link-display
20766 :style radio
20767 :selected org-descriptive-links
20769 ["Literal Links"
20770 org-toggle-link-display
20771 :style radio
20772 :selected (not org-descriptive-links)])
20773 "--"
20774 ("TODO Lists"
20775 ["TODO/DONE/-" org-todo t]
20776 ("Select keyword"
20777 ["Next keyword" org-shiftright (org-at-heading-p)]
20778 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20779 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20780 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20781 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20782 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20783 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20784 "--"
20785 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20786 :selected org-enforce-todo-dependencies :style toggle :active t]
20787 "Settings for tree at point"
20788 ["Do Children sequentially" org-toggle-ordered-property :style radio
20789 :selected (org-entry-get nil "ORDERED")
20790 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20791 ["Do Children parallel" org-toggle-ordered-property :style radio
20792 :selected (not (org-entry-get nil "ORDERED"))
20793 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20794 "--"
20795 ["Set Priority" org-priority t]
20796 ["Priority Up" org-shiftup t]
20797 ["Priority Down" org-shiftdown t]
20798 "--"
20799 ["Get news from all feeds" org-feed-update-all t]
20800 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20801 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20802 ("TAGS and Properties"
20803 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20804 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20805 "--"
20806 ["Set property" org-set-property (not (org-before-first-heading-p))]
20807 ["Column view of properties" org-columns t]
20808 ["Insert Column View DBlock" org-insert-columns-dblock t])
20809 ("Dates and Scheduling"
20810 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20811 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20812 ("Change Date"
20813 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20814 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20815 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20816 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20817 ["Compute Time Range" org-evaluate-time-range t]
20818 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20819 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20820 "--"
20821 ["Custom time format" org-toggle-time-stamp-overlays
20822 :style radio :selected org-display-custom-times]
20823 "--"
20824 ["Goto Calendar" org-goto-calendar t]
20825 ["Date from Calendar" org-date-from-calendar t]
20826 "--"
20827 ["Start/Restart Timer" org-timer-start t]
20828 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20829 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20830 ["Insert Timer String" org-timer t]
20831 ["Insert Timer Item" org-timer-item t])
20832 ("Logging work"
20833 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20834 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20835 ["Clock out" org-clock-out t]
20836 ["Clock cancel" org-clock-cancel t]
20837 "--"
20838 ["Mark as default task" org-clock-mark-default-task t]
20839 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20840 ["Goto running clock" org-clock-goto t]
20841 "--"
20842 ["Display times" org-clock-display t]
20843 ["Create clock table" org-clock-report t]
20844 "--"
20845 ["Record DONE time"
20846 (progn (setq org-log-done (not org-log-done))
20847 (message "Switching to %s will %s record a timestamp"
20848 (car org-done-keywords)
20849 (if org-log-done "automatically" "not")))
20850 :style toggle :selected org-log-done])
20851 "--"
20852 ["Agenda Command..." org-agenda t]
20853 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20854 ("File List for Agenda")
20855 ("Special views current file"
20856 ["TODO Tree" org-show-todo-tree t]
20857 ["Check Deadlines" org-check-deadlines t]
20858 ["Timeline" org-timeline t]
20859 ["Tags/Property tree" org-match-sparse-tree t])
20860 "--"
20861 ["Export/Publish..." org-export-dispatch t]
20862 ("LaTeX"
20863 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20864 :selected org-cdlatex-mode]
20865 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20866 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20867 ["Modify math symbol" org-cdlatex-math-modify
20868 (org-inside-LaTeX-fragment-p)]
20869 ["Insert citation" org-reftex-citation t]
20870 "--"
20871 ["Template for BEAMER" (org-beamer-insert-options-template) t])
20872 "--"
20873 ("MobileOrg"
20874 ["Push Files and Views" org-mobile-push t]
20875 ["Get Captured and Flagged" org-mobile-pull t]
20876 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20877 "--"
20878 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20879 "--"
20880 ("Documentation"
20881 ["Show Version" org-version t]
20882 ["Info Documentation" org-info t])
20883 ("Customize"
20884 ["Browse Org Group" org-customize t]
20885 "--"
20886 ["Expand This Menu" org-create-customize-menu
20887 (fboundp 'customize-menu-create)])
20888 ["Send bug report" org-submit-bug-report t]
20889 "--"
20890 ("Refresh/Reload"
20891 ["Refresh setup current buffer" org-mode-restart t]
20892 ["Reload Org (after update)" org-reload t]
20893 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
20896 (defun org-info (&optional node)
20897 "Read documentation for Org-mode in the info system.
20898 With optional NODE, go directly to that node."
20899 (interactive)
20900 (info (format "(org)%s" (or node ""))))
20902 ;;;###autoload
20903 (defun org-submit-bug-report ()
20904 "Submit a bug report on Org-mode via mail.
20906 Don't hesitate to report any problems or inaccurate documentation.
20908 If you don't have setup sending mail from (X)Emacs, please copy the
20909 output buffer into your mail program, as it gives us important
20910 information about your Org-mode version and configuration."
20911 (interactive)
20912 (require 'reporter)
20913 (org-load-modules-maybe)
20914 (org-require-autoloaded-modules)
20915 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20916 (reporter-submit-bug-report
20917 "emacs-orgmode@gnu.org"
20918 (org-version nil 'full)
20919 (let (list)
20920 (save-window-excursion
20921 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20922 (delete-other-windows)
20923 (erase-buffer)
20924 (insert "You are about to submit a bug report to the Org-mode mailing list.
20926 We would like to add your full Org-mode and Outline configuration to the
20927 bug report. This greatly simplifies the work of the maintainer and
20928 other experts on the mailing list.
20930 HOWEVER, some variables you have customized may contain private
20931 information. The names of customers, colleagues, or friends, might
20932 appear in the form of file names, tags, todo states, or search strings.
20933 If you answer yes to the prompt, you might want to check and remove
20934 such private information before sending the email.")
20935 (add-text-properties (point-min) (point-max) '(face org-warning))
20936 (when (yes-or-no-p "Include your Org-mode configuration ")
20937 (mapatoms
20938 (lambda (v)
20939 (and (boundp v)
20940 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20941 (or (and (symbol-value v)
20942 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20943 (and
20944 (get v 'custom-type) (get v 'standard-value)
20945 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20946 (push v list)))))
20947 (kill-buffer (get-buffer "*Warn about privacy*"))
20948 list))
20949 nil nil
20950 "Remember to cover the basics, that is, what you expected to happen and
20951 what in fact did happen. You don't know how to make a good report? See
20953 http://orgmode.org/manual/Feedback.html#Feedback
20955 Your bug report will be posted to the Org-mode mailing list.
20956 ------------------------------------------------------------------------")
20957 (save-excursion
20958 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20959 (replace-match "\\1Bug: \\3 [\\2]")))))
20962 (defun org-install-agenda-files-menu ()
20963 (let ((bl (buffer-list)))
20964 (save-excursion
20965 (while bl
20966 (set-buffer (pop bl))
20967 (if (derived-mode-p 'org-mode) (setq bl nil)))
20968 (when (derived-mode-p 'org-mode)
20969 (easy-menu-change
20970 '("Org") "File List for Agenda"
20971 (append
20972 (list
20973 ["Edit File List" (org-edit-agenda-file-list) t]
20974 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20975 ["Remove Current File from List" org-remove-file t]
20976 ["Cycle through agenda files" org-cycle-agenda-files t]
20977 ["Occur in all agenda files" org-occur-in-agenda-files t]
20978 "--")
20979 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20981 ;;;; Documentation
20983 (defun org-require-autoloaded-modules ()
20984 (interactive)
20985 (mapc 'require
20986 '(org-agenda org-archive org-attach org-clock org-colview org-id
20987 org-remember org-table org-timer)))
20989 ;;;###autoload
20990 (defun org-reload (&optional uncompiled)
20991 "Reload all org lisp files.
20992 With prefix arg UNCOMPILED, load the uncompiled versions."
20993 (interactive "P")
20994 (require 'loadhist)
20995 (let* ((org-dir (org-find-library-dir "org"))
20996 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20997 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
20998 (remove-re (mapconcat 'identity
20999 (mapcar (lambda (f) (concat "^" f "$"))
21000 (list (if (featurep 'xemacs)
21001 "org-colview"
21002 "org-colview-xemacs")
21003 "org" "org-loaddefs" "org-version"))
21004 "\\|"))
21005 (feats (delete-dups
21006 (mapcar 'file-name-sans-extension
21007 (mapcar 'file-name-nondirectory
21008 (delq nil
21009 (mapcar 'feature-file
21010 features))))))
21011 (lfeat (append
21012 (sort
21013 (setq feats
21014 (delq nil (mapcar
21015 (lambda (f)
21016 (if (and (string-match feature-re f)
21017 (not (string-match remove-re f)))
21018 f nil))
21019 feats)))
21020 'string-lessp)
21021 (list "org-version" "org")))
21022 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21023 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21024 load-uncore load-misses)
21025 (setq load-misses
21026 (delq 't
21027 (mapcar (lambda (f)
21028 (or (org-load-noerror-mustsuffix (concat org-dir f))
21029 (and (string= org-dir contrib-dir)
21030 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21031 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21032 (add-to-list 'load-uncore f 'append)
21035 lfeat)))
21036 (if load-uncore
21037 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21038 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21039 (if load-misses
21040 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21041 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21042 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21044 ;;;###autoload
21045 (defun org-customize ()
21046 "Call the customize function with org as argument."
21047 (interactive)
21048 (org-load-modules-maybe)
21049 (org-require-autoloaded-modules)
21050 (customize-browse 'org))
21052 (defun org-create-customize-menu ()
21053 "Create a full customization menu for Org-mode, insert it into the menu."
21054 (interactive)
21055 (org-load-modules-maybe)
21056 (org-require-autoloaded-modules)
21057 (if (fboundp 'customize-menu-create)
21058 (progn
21059 (easy-menu-change
21060 '("Org") "Customize"
21061 `(["Browse Org group" org-customize t]
21062 "--"
21063 ,(customize-menu-create 'org)
21064 ["Set" Custom-set t]
21065 ["Save" Custom-save t]
21066 ["Reset to Current" Custom-reset-current t]
21067 ["Reset to Saved" Custom-reset-saved t]
21068 ["Reset to Standard Settings" Custom-reset-standard t]))
21069 (message "\"Org\"-menu now contains full customization menu"))
21070 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21072 ;;;; Miscellaneous stuff
21074 ;;; Generally useful functions
21076 (defun org-get-at-bol (property)
21077 "Get text property PROPERTY at beginning of line."
21078 (get-text-property (point-at-bol) property))
21080 (defun org-find-text-property-in-string (prop s)
21081 "Return the first non-nil value of property PROP in string S."
21082 (or (get-text-property 0 prop s)
21083 (get-text-property (or (next-single-property-change 0 prop s) 0)
21084 prop s)))
21086 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21087 "Display the given MESSAGE as a warning."
21088 (if (fboundp 'display-warning)
21089 (display-warning 'org message
21090 (if (featurep 'xemacs) 'warning :warning))
21091 (let ((buf (get-buffer-create "*Org warnings*")))
21092 (with-current-buffer buf
21093 (goto-char (point-max))
21094 (insert "Warning (Org): " message)
21095 (unless (bolp)
21096 (newline)))
21097 (display-buffer buf)
21098 (sit-for 0))))
21100 (defun org-eval (form)
21101 "Eval FORM and return result."
21102 (condition-case error
21103 (eval form)
21104 (error (format "%%![Error: %s]" error))))
21106 (defun org-in-clocktable-p ()
21107 "Check if the cursor is in a clocktable."
21108 (let ((pos (point)) start)
21109 (save-excursion
21110 (end-of-line 1)
21111 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21112 (setq start (match-beginning 0))
21113 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21114 (>= (match-end 0) pos)
21115 start))))
21117 (defun org-in-commented-line ()
21118 "Is point in a line starting with `#'?"
21119 (equal (char-after (point-at-bol)) ?#))
21121 (defun org-in-indented-comment-line ()
21122 "Is point in a line starting with `#' after some white space?"
21123 (save-excursion
21124 (save-match-data
21125 (goto-char (point-at-bol))
21126 (looking-at "[ \t]*#"))))
21128 (defun org-in-verbatim-emphasis ()
21129 (save-match-data
21130 (and (org-in-regexp org-emph-re 2)
21131 (>= (point) (match-beginning 3))
21132 (<= (point) (match-end 4))
21133 (member (match-string 3) '("=" "~")))))
21135 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21136 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21137 (if (and marker (marker-buffer marker)
21138 (buffer-live-p (marker-buffer marker)))
21139 (progn
21140 (org-pop-to-buffer-same-window (marker-buffer marker))
21141 (if (or (> marker (point-max)) (< marker (point-min)))
21142 (widen))
21143 (goto-char marker)
21144 (org-show-context 'org-goto))
21145 (if bookmark
21146 (bookmark-jump bookmark)
21147 (error "Cannot find location"))))
21149 (defun org-quote-csv-field (s)
21150 "Quote field for inclusion in CSV material."
21151 (if (string-match "[\",]" s)
21152 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21155 (defun org-force-self-insert (N)
21156 "Needed to enforce self-insert under remapping."
21157 (interactive "p")
21158 (self-insert-command N))
21160 (defun org-string-width (s)
21161 "Compute width of string, ignoring invisible characters.
21162 This ignores character with invisibility property `org-link', and also
21163 characters with property `org-cwidth', because these will become invisible
21164 upon the next fontification round."
21165 (let (b l)
21166 (when (or (eq t buffer-invisibility-spec)
21167 (assq 'org-link buffer-invisibility-spec))
21168 (while (setq b (text-property-any 0 (length s)
21169 'invisible 'org-link s))
21170 (setq s (concat (substring s 0 b)
21171 (substring s (or (next-single-property-change
21172 b 'invisible s) (length s)))))))
21173 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21174 (setq s (concat (substring s 0 b)
21175 (substring s (or (next-single-property-change
21176 b 'org-cwidth s) (length s))))))
21177 (setq l (string-width s) b -1)
21178 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21179 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21182 (defun org-shorten-string (s maxlength)
21183 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21184 If the string is shorter or has length MAXLENGTH, just return the
21185 original string. If it is longer, the functions finds a space in the
21186 string, breaks this string off at that locations and adds three dots
21187 as ellipsis. Including the ellipsis, the string will not be longer
21188 than MAXLENGTH. If finding a good breaking point in the string does
21189 not work, the string is just chopped off in the middle of a word
21190 if necessary."
21191 (if (<= (length s) maxlength)
21193 (let* ((n (max (- maxlength 4) 1))
21194 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21195 (if (string-match re s)
21196 (concat (match-string 1 s) "...")
21197 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21199 (defun org-get-indentation (&optional line)
21200 "Get the indentation of the current line, interpreting tabs.
21201 When LINE is given, assume it represents a line and compute its indentation."
21202 (if line
21203 (if (string-match "^ *" (org-remove-tabs line))
21204 (match-end 0))
21205 (save-excursion
21206 (beginning-of-line 1)
21207 (skip-chars-forward " \t")
21208 (current-column))))
21210 (defun org-get-string-indentation (s)
21211 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21212 (let ((n -1) (i 0) (w tab-width) c)
21213 (catch 'exit
21214 (while (< (setq n (1+ n)) (length s))
21215 (setq c (aref s n))
21216 (cond ((= c ?\ ) (setq i (1+ i)))
21217 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21218 (t (throw 'exit t)))))
21221 (defun org-remove-tabs (s &optional width)
21222 "Replace tabulators in S with spaces.
21223 Assumes that s is a single line, starting in column 0."
21224 (setq width (or width tab-width))
21225 (while (string-match "\t" s)
21226 (setq s (replace-match
21227 (make-string
21228 (- (* width (/ (+ (match-beginning 0) width) width))
21229 (match-beginning 0)) ?\ )
21230 t t s)))
21233 (defun org-fix-indentation (line ind)
21234 "Fix indentation in LINE.
21235 IND is a cons cell with target and minimum indentation.
21236 If the current indentation in LINE is smaller than the minimum,
21237 leave it alone. If it is larger than ind, set it to the target."
21238 (let* ((l (org-remove-tabs line))
21239 (i (org-get-indentation l))
21240 (i1 (car ind)) (i2 (cdr ind)))
21241 (if (>= i i2) (setq l (substring line i2)))
21242 (if (> i1 0)
21243 (concat (make-string i1 ?\ ) l)
21244 l)))
21246 (defun org-remove-indentation (code &optional n)
21247 "Remove the maximum common indentation from the lines in CODE.
21248 N may optionally be the number of spaces to remove."
21249 (with-temp-buffer
21250 (insert code)
21251 (org-do-remove-indentation n)
21252 (buffer-string)))
21254 (defun org-do-remove-indentation (&optional n)
21255 "Remove the maximum common indentation from the buffer."
21256 (untabify (point-min) (point-max))
21257 (let ((min 10000) re)
21258 (if n
21259 (setq min n)
21260 (goto-char (point-min))
21261 (while (re-search-forward "^ *[^ \n]" nil t)
21262 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21263 (unless (or (= min 0) (= min 10000))
21264 (setq re (format "^ \\{%d\\}" min))
21265 (goto-char (point-min))
21266 (while (re-search-forward re nil t)
21267 (replace-match "")
21268 (end-of-line 1))
21269 min)))
21271 (defun org-fill-template (template alist)
21272 "Find each %key of ALIST in TEMPLATE and replace it."
21273 (let ((case-fold-search nil)
21274 entry key value)
21275 (setq alist (sort (copy-sequence alist)
21276 (lambda (a b) (< (length (car a)) (length (car b))))))
21277 (while (setq entry (pop alist))
21278 (setq template
21279 (replace-regexp-in-string
21280 (concat "%" (regexp-quote (car entry)))
21281 (or (cdr entry) "") template t t)))
21282 template))
21284 (defun org-base-buffer (buffer)
21285 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21286 (if (not buffer)
21287 buffer
21288 (or (buffer-base-buffer buffer)
21289 buffer)))
21291 (defun org-trim (s)
21292 "Remove whitespace at beginning and end of string."
21293 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
21294 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
21297 (defun org-wrap (string &optional width lines)
21298 "Wrap string to either a number of lines, or a width in characters.
21299 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21300 that costs. If there is a word longer than WIDTH, the text is actually
21301 wrapped to the length of that word.
21302 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21303 many lines, whatever width that takes.
21304 The return value is a list of lines, without newlines at the end."
21305 (let* ((words (org-split-string string "[ \t\n]+"))
21306 (maxword (apply 'max (mapcar 'org-string-width words)))
21307 w ll)
21308 (cond (width
21309 (org-do-wrap words (max maxword width)))
21310 (lines
21311 (setq w maxword)
21312 (setq ll (org-do-wrap words maxword))
21313 (if (<= (length ll) lines)
21315 (setq ll words)
21316 (while (> (length ll) lines)
21317 (setq w (1+ w))
21318 (setq ll (org-do-wrap words w)))
21319 ll))
21320 (t (error "Cannot wrap this")))))
21322 (defun org-do-wrap (words width)
21323 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21324 (let (lines line)
21325 (while words
21326 (setq line (pop words))
21327 (while (and words (< (+ (length line) (length (car words))) width))
21328 (setq line (concat line " " (pop words))))
21329 (setq lines (push line lines)))
21330 (nreverse lines)))
21332 (defun org-split-string (string &optional separators)
21333 "Splits STRING into substrings at SEPARATORS.
21334 No empty strings are returned if there are matches at the beginning
21335 and end of string."
21336 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21337 (start 0)
21338 notfirst
21339 (list nil))
21340 (while (and (string-match rexp string
21341 (if (and notfirst
21342 (= start (match-beginning 0))
21343 (< start (length string)))
21344 (1+ start) start))
21345 (< (match-beginning 0) (length string)))
21346 (setq notfirst t)
21347 (or (eq (match-beginning 0) 0)
21348 (and (eq (match-beginning 0) (match-end 0))
21349 (eq (match-beginning 0) start))
21350 (setq list
21351 (cons (substring string start (match-beginning 0))
21352 list)))
21353 (setq start (match-end 0)))
21354 (or (eq start (length string))
21355 (setq list
21356 (cons (substring string start)
21357 list)))
21358 (nreverse list)))
21360 (defun org-quote-vert (s)
21361 "Replace \"|\" with \"\\vert\"."
21362 (while (string-match "|" s)
21363 (setq s (replace-match "\\vert" t t s)))
21366 (defun org-uuidgen-p (s)
21367 "Is S an ID created by UUIDGEN?"
21368 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21370 (defun org-in-src-block-p (&optional inside)
21371 "Whether point is in a code source block.
21372 When INSIDE is non-nil, don't consider we are within a src block
21373 when point is at #+BEGIN_SRC or #+END_SRC."
21374 (let ((case-fold-search t) ov)
21375 (or (and (setq ov (overlays-at (point)))
21376 (memq 'org-block-background
21377 (overlay-properties (car ov))))
21378 (and (not inside)
21379 (save-match-data
21380 (save-excursion
21381 (beginning-of-line)
21382 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21384 (defun org-context ()
21385 "Return a list of contexts of the current cursor position.
21386 If several contexts apply, all are returned.
21387 Each context entry is a list with a symbol naming the context, and
21388 two positions indicating start and end of the context. Possible
21389 contexts are:
21391 :headline anywhere in a headline
21392 :headline-stars on the leading stars in a headline
21393 :todo-keyword on a TODO keyword (including DONE) in a headline
21394 :tags on the TAGS in a headline
21395 :priority on the priority cookie in a headline
21396 :item on the first line of a plain list item
21397 :item-bullet on the bullet/number of a plain list item
21398 :checkbox on the checkbox in a plain list item
21399 :table in an org-mode table
21400 :table-special on a special filed in a table
21401 :table-table in a table.el table
21402 :clocktable in a clocktable
21403 :src-block in a source block
21404 :link on a hyperlink
21405 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21406 :target on a <<target>>
21407 :radio-target on a <<<radio-target>>>
21408 :latex-fragment on a LaTeX fragment
21409 :latex-preview on a LaTeX fragment with overlaid preview image
21411 This function expects the position to be visible because it uses font-lock
21412 faces as a help to recognize the following contexts: :table-special, :link,
21413 and :keyword."
21414 (let* ((f (get-text-property (point) 'face))
21415 (faces (if (listp f) f (list f)))
21416 (case-fold-search t)
21417 (p (point)) clist o)
21418 ;; First the large context
21419 (cond
21420 ((org-at-heading-p t)
21421 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21422 (when (progn
21423 (beginning-of-line 1)
21424 (looking-at org-todo-line-tags-regexp))
21425 (push (org-point-in-group p 1 :headline-stars) clist)
21426 (push (org-point-in-group p 2 :todo-keyword) clist)
21427 (push (org-point-in-group p 4 :tags) clist))
21428 (goto-char p)
21429 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21430 (if (looking-at "\\[#[A-Z0-9]\\]")
21431 (push (org-point-in-group p 0 :priority) clist)))
21433 ((org-at-item-p)
21434 (push (org-point-in-group p 2 :item-bullet) clist)
21435 (push (list :item (point-at-bol)
21436 (save-excursion (org-end-of-item) (point)))
21437 clist)
21438 (and (org-at-item-checkbox-p)
21439 (push (org-point-in-group p 0 :checkbox) clist)))
21441 ((org-at-table-p)
21442 (push (list :table (org-table-begin) (org-table-end)) clist)
21443 (if (memq 'org-formula faces)
21444 (push (list :table-special
21445 (previous-single-property-change p 'face)
21446 (next-single-property-change p 'face)) clist)))
21447 ((org-at-table-p 'any)
21448 (push (list :table-table) clist)))
21449 (goto-char p)
21451 (let ((case-fold-search t))
21452 ;; New the "medium" contexts: clocktables, source blocks
21453 (cond ((org-in-clocktable-p)
21454 (push (list :clocktable
21455 (and (or (looking-at "#\\+BEGIN: clocktable")
21456 (search-backward "#+BEGIN: clocktable" nil t))
21457 (match-beginning 0))
21458 (and (re-search-forward "#\\+END:?" nil t)
21459 (match-end 0))) clist))
21460 ((org-in-src-block-p)
21461 (push (list :src-block
21462 (and (or (looking-at "#\\+BEGIN_SRC")
21463 (search-backward "#+BEGIN_SRC" nil t))
21464 (match-beginning 0))
21465 (and (search-forward "#+END_SRC" nil t)
21466 (match-beginning 0))) clist))))
21467 (goto-char p)
21469 ;; Now the small context
21470 (cond
21471 ((org-at-timestamp-p)
21472 (push (org-point-in-group p 0 :timestamp) clist))
21473 ((memq 'org-link faces)
21474 (push (list :link
21475 (previous-single-property-change p 'face)
21476 (next-single-property-change p 'face)) clist))
21477 ((memq 'org-special-keyword faces)
21478 (push (list :keyword
21479 (previous-single-property-change p 'face)
21480 (next-single-property-change p 'face)) clist))
21481 ((org-at-target-p)
21482 (push (org-point-in-group p 0 :target) clist)
21483 (goto-char (1- (match-beginning 0)))
21484 (if (looking-at org-radio-target-regexp)
21485 (push (org-point-in-group p 0 :radio-target) clist))
21486 (goto-char p))
21487 ((setq o (car (delq nil
21488 (mapcar
21489 (lambda (x)
21490 (if (memq x org-latex-fragment-image-overlays) x))
21491 (overlays-at (point))))))
21492 (push (list :latex-fragment
21493 (overlay-start o) (overlay-end o)) clist)
21494 (push (list :latex-preview
21495 (overlay-start o) (overlay-end o)) clist))
21496 ((org-inside-LaTeX-fragment-p)
21497 ;; FIXME: positions wrong.
21498 (push (list :latex-fragment (point) (point)) clist)))
21500 (setq clist (nreverse (delq nil clist)))
21501 clist))
21503 ;; FIXME: Compare with at-regexp-p Do we need both?
21504 (defun org-in-regexp (re &optional nlines visually)
21505 "Check if point is inside a match of regexp.
21506 Normally only the current line is checked, but you can include NLINES extra
21507 lines both before and after point into the search.
21508 If VISUALLY is set, require that the cursor is not after the match but
21509 really on, so that the block visually is on the match."
21510 (catch 'exit
21511 (let ((pos (point))
21512 (eol (point-at-eol (+ 1 (or nlines 0))))
21513 (inc (if visually 1 0)))
21514 (save-excursion
21515 (beginning-of-line (- 1 (or nlines 0)))
21516 (while (re-search-forward re eol t)
21517 (if (and (<= (match-beginning 0) pos)
21518 (>= (+ inc (match-end 0)) pos))
21519 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21521 (defun org-at-regexp-p (regexp)
21522 "Is point inside a match of REGEXP in the current line?"
21523 (catch 'exit
21524 (save-excursion
21525 (let ((pos (point)) (end (point-at-eol)))
21526 (beginning-of-line 1)
21527 (while (re-search-forward regexp end t)
21528 (if (and (<= (match-beginning 0) pos)
21529 (>= (match-end 0) pos))
21530 (throw 'exit t)))
21531 nil))))
21533 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21534 "Non-nil when point is between matches of START-RE and END-RE.
21536 Also return a non-nil value when point is on one of the matches.
21538 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21539 buffer positions. Default values are the positions of headlines
21540 surrounding the point.
21542 The functions returns a cons cell whose car (resp. cdr) is the
21543 position before START-RE (resp. after END-RE)."
21544 (save-match-data
21545 (let ((pos (point))
21546 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21547 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21548 beg end)
21549 (save-excursion
21550 ;; Point is on a block when on START-RE or if START-RE can be
21551 ;; found before it...
21552 (and (or (org-at-regexp-p start-re)
21553 (re-search-backward start-re limit-up t))
21554 (setq beg (match-beginning 0))
21555 ;; ... and END-RE after it...
21556 (goto-char (match-end 0))
21557 (re-search-forward end-re limit-down t)
21558 (> (setq end (match-end 0)) pos)
21559 ;; ... without another START-RE in-between.
21560 (goto-char (match-beginning 0))
21561 (not (re-search-backward start-re (1+ beg) t))
21562 ;; Return value.
21563 (cons beg end))))))
21565 (defun org-in-block-p (names)
21566 "Non-nil when point belongs to a block whose name belongs to NAMES.
21568 NAMES is a list of strings containing names of blocks.
21570 Return first block name matched, or nil. Beware that in case of
21571 nested blocks, the returned name may not belong to the closest
21572 block from point."
21573 (save-match-data
21574 (catch 'exit
21575 (let ((case-fold-search t)
21576 (lim-up (save-excursion (outline-previous-heading)))
21577 (lim-down (save-excursion (outline-next-heading))))
21578 (mapc (lambda (name)
21579 (let ((n (regexp-quote name)))
21580 (when (org-between-regexps-p
21581 (concat "^[ \t]*#\\+begin_" n)
21582 (concat "^[ \t]*#\\+end_" n)
21583 lim-up lim-down)
21584 (throw 'exit n))))
21585 names))
21586 nil)))
21588 (defun org-in-drawer-p ()
21589 "Is point within a drawer?"
21590 (save-match-data
21591 (let ((case-fold-search t)
21592 (lim-up (save-excursion (outline-previous-heading)))
21593 (lim-down (save-excursion (outline-next-heading))))
21594 (org-between-regexps-p
21595 (concat "^[ \t]*:" (regexp-opt org-drawers) ":")
21596 "^[ \t]*:end:.*$"
21597 lim-up lim-down))))
21599 (defun org-occur-in-agenda-files (regexp &optional nlines)
21600 "Call `multi-occur' with buffers for all agenda files."
21601 (interactive "sOrg-files matching: \np")
21602 (let* ((files (org-agenda-files))
21603 (tnames (mapcar 'file-truename files))
21604 (extra org-agenda-text-search-extra-files)
21606 (when (eq (car extra) 'agenda-archives)
21607 (setq extra (cdr extra))
21608 (setq files (org-add-archive-files files)))
21609 (while (setq f (pop extra))
21610 (unless (member (file-truename f) tnames)
21611 (add-to-list 'files f 'append)
21612 (add-to-list 'tnames (file-truename f) 'append)))
21613 (multi-occur
21614 (mapcar (lambda (x)
21615 (with-current-buffer
21616 (or (get-file-buffer x) (find-file-noselect x))
21617 (widen)
21618 (current-buffer)))
21619 files)
21620 regexp)))
21622 (if (boundp 'occur-mode-find-occurrence-hook)
21623 ;; Emacs 23
21624 (add-hook 'occur-mode-find-occurrence-hook
21625 (lambda ()
21626 (when (derived-mode-p 'org-mode)
21627 (org-reveal))))
21628 ;; Emacs 22
21629 (defadvice occur-mode-goto-occurrence
21630 (after org-occur-reveal activate)
21631 (and (derived-mode-p 'org-mode) (org-reveal)))
21632 (defadvice occur-mode-goto-occurrence-other-window
21633 (after org-occur-reveal activate)
21634 (and (derived-mode-p 'org-mode) (org-reveal)))
21635 (defadvice occur-mode-display-occurrence
21636 (after org-occur-reveal activate)
21637 (when (derived-mode-p 'org-mode)
21638 (let ((pos (occur-mode-find-occurrence)))
21639 (with-current-buffer (marker-buffer pos)
21640 (save-excursion
21641 (goto-char pos)
21642 (org-reveal)))))))
21644 (defun org-occur-link-in-agenda-files ()
21645 "Create a link and search for it in the agendas.
21646 The link is not stored in `org-stored-links', it is just created
21647 for the search purpose."
21648 (interactive)
21649 (let ((link (condition-case nil
21650 (org-store-link nil)
21651 (error "Unable to create a link to here"))))
21652 (org-occur-in-agenda-files (regexp-quote link))))
21654 (defun org-reverse-string (string)
21655 "Return the reverse of STRING."
21656 (apply 'string (reverse (string-to-list string))))
21658 (defsubst org-uniquify (list)
21659 "Non-destructively remove duplicate elements from LIST."
21660 (let ((res (copy-sequence list))) (delete-dups res)))
21662 (defun org-uniquify-alist (alist)
21663 "Merge elements of ALIST with the same key.
21665 For example, in this alist:
21667 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
21668 => '((a 1 3) (b 2))
21670 merge (a 1) and (a 3) into (a 1 3).
21672 The function returns the new ALIST."
21673 (let (rtn)
21674 (mapc
21675 (lambda (e)
21676 (let (n)
21677 (if (not (assoc (car e) rtn))
21678 (push e rtn)
21679 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
21680 (setq rtn (assq-delete-all (car e) rtn))
21681 (push n rtn))))
21682 alist)
21683 rtn))
21685 (defun org-delete-all (elts list)
21686 "Remove all elements in ELTS from LIST."
21687 (while elts
21688 (setq list (delete (pop elts) list)))
21689 list)
21691 (defun org-count (cl-item cl-seq)
21692 "Count the number of occurrences of ITEM in SEQ.
21693 Taken from `count' in cl-seq.el with all keyword arguments removed."
21694 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21695 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21696 (while (< cl-start cl-end)
21697 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21698 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21699 (setq cl-start (1+ cl-start)))
21700 cl-count))
21702 (defun org-remove-if (predicate seq)
21703 "Remove everything from SEQ that fulfills PREDICATE."
21704 (let (res e)
21705 (while seq
21706 (setq e (pop seq))
21707 (if (not (funcall predicate e)) (push e res)))
21708 (nreverse res)))
21710 (defun org-remove-if-not (predicate seq)
21711 "Remove everything from SEQ that does not fulfill PREDICATE."
21712 (let (res e)
21713 (while seq
21714 (setq e (pop seq))
21715 (if (funcall predicate e) (push e res)))
21716 (nreverse res)))
21718 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21719 "Reduce two-argument FUNCTION across SEQ.
21720 Taken from `reduce' in cl-seq.el with all keyword arguments but
21721 \":initial-value\" removed."
21722 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21723 (cadr (memq :initial-value cl-keys)))
21724 (cl-seq (pop cl-seq))
21725 (t (funcall cl-func)))))
21726 (while cl-seq
21727 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21728 cl-accum))
21730 (defun org-back-over-empty-lines ()
21731 "Move backwards over whitespace, to the beginning of the first empty line.
21732 Returns the number of empty lines passed."
21733 (let ((pos (point)))
21734 (if (cdr (assoc 'heading org-blank-before-new-entry))
21735 (skip-chars-backward " \t\n\r")
21736 (unless (eobp)
21737 (forward-line -1)))
21738 (beginning-of-line 2)
21739 (goto-char (min (point) pos))
21740 (count-lines (point) pos)))
21742 (defun org-skip-whitespace ()
21743 (skip-chars-forward " \t\n\r"))
21745 (defun org-point-in-group (point group &optional context)
21746 "Check if POINT is in match-group GROUP.
21747 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21748 match. If the match group does not exist or point is not inside it,
21749 return nil."
21750 (and (match-beginning group)
21751 (>= point (match-beginning group))
21752 (<= point (match-end group))
21753 (if context
21754 (list context (match-beginning group) (match-end group))
21755 t)))
21757 (defun org-switch-to-buffer-other-window (&rest args)
21758 "Switch to buffer in a second window on the current frame.
21759 In particular, do not allow pop-up frames.
21760 Returns the newly created buffer."
21761 (org-no-popups
21762 (apply 'switch-to-buffer-other-window args)))
21764 (defun org-combine-plists (&rest plists)
21765 "Create a single property list from all plists in PLISTS.
21766 The process starts by copying the first list, and then setting properties
21767 from the other lists. Settings in the last list are the most significant
21768 ones and overrule settings in the other lists."
21769 (let ((rtn (copy-sequence (pop plists)))
21770 p v ls)
21771 (while plists
21772 (setq ls (pop plists))
21773 (while ls
21774 (setq p (pop ls) v (pop ls))
21775 (setq rtn (plist-put rtn p v))))
21776 rtn))
21778 (defun org-replace-escapes (string table)
21779 "Replace %-escapes in STRING with values in TABLE.
21780 TABLE is an association list with keys like \"%a\" and string values.
21781 The sequences in STRING may contain normal field width and padding information,
21782 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21783 so values can contain further %-escapes if they are define later in TABLE."
21784 (let ((tbl (copy-alist table))
21785 (case-fold-search nil)
21786 (pchg 0)
21787 e re rpl)
21788 (while (setq e (pop tbl))
21789 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21790 (when (and (cdr e) (string-match re (cdr e)))
21791 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21792 (safe "SREF"))
21793 (add-text-properties 0 3 (list 'sref sref) safe)
21794 (setcdr e (replace-match safe t t (cdr e)))))
21795 (while (string-match re string)
21796 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21797 (cdr e)))
21798 (setq string (replace-match rpl t t string))))
21799 (while (setq pchg (next-property-change pchg string))
21800 (let ((sref (get-text-property pchg 'sref string)))
21801 (when (and sref (string-match "SREF" string pchg))
21802 (setq string (replace-match sref t t string)))))
21803 string))
21805 (defun org-sublist (list start end)
21806 "Return a section of LIST, from START to END.
21807 Counting starts at 1."
21808 (let (rtn (c start))
21809 (setq list (nthcdr (1- start) list))
21810 (while (and list (<= c end))
21811 (push (pop list) rtn)
21812 (setq c (1+ c)))
21813 (nreverse rtn)))
21815 (defun org-find-base-buffer-visiting (file)
21816 "Like `find-buffer-visiting' but always return the base buffer and
21817 not an indirect buffer."
21818 (let ((buf (or (get-file-buffer file)
21819 (find-buffer-visiting file))))
21820 (if buf
21821 (or (buffer-base-buffer buf) buf)
21822 nil)))
21824 (defun org-image-file-name-regexp (&optional extensions)
21825 "Return regexp matching the file names of images.
21826 If EXTENSIONS is given, only match these."
21827 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21828 (image-file-name-regexp)
21829 (let ((image-file-name-extensions
21830 (or extensions
21831 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21832 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21833 (concat "\\."
21834 (regexp-opt (nconc (mapcar 'upcase
21835 image-file-name-extensions)
21836 image-file-name-extensions)
21838 "\\'"))))
21840 (defun org-file-image-p (file &optional extensions)
21841 "Return non-nil if FILE is an image."
21842 (save-match-data
21843 (string-match (org-image-file-name-regexp extensions) file)))
21845 (defun org-get-cursor-date (&optional with-time)
21846 "Return the date at cursor in as a time.
21847 This works in the calendar and in the agenda, anywhere else it just
21848 returns the current time.
21849 If WITH-TIME is non-nil, returns the time of the event at point (in
21850 the agenda) or the current time of the day."
21851 (let (date day defd tp tm hod mod)
21852 (when with-time
21853 (setq tp (get-text-property (point) 'time))
21854 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21855 (setq hod (string-to-number (match-string 1 tp))
21856 mod (string-to-number (match-string 2 tp))))
21857 (or tp (setq hod (nth 2 (decode-time (current-time)))
21858 mod (nth 1 (decode-time (current-time))))))
21859 (cond
21860 ((eq major-mode 'calendar-mode)
21861 (setq date (calendar-cursor-to-date)
21862 defd (encode-time 0 (or mod 0) (or hod 0)
21863 (nth 1 date) (nth 0 date) (nth 2 date))))
21864 ((eq major-mode 'org-agenda-mode)
21865 (setq day (get-text-property (point) 'day))
21866 (if day
21867 (setq date (calendar-gregorian-from-absolute day)
21868 defd (encode-time 0 (or mod 0) (or hod 0)
21869 (nth 1 date) (nth 0 date) (nth 2 date))))))
21870 (or defd (current-time))))
21872 (defun org-mark-subtree (&optional up)
21873 "Mark the current subtree.
21874 This puts point at the start of the current subtree, and mark at
21875 the end. If a numeric prefix UP is given, move up into the
21876 hierarchy of headlines by UP levels before marking the subtree."
21877 (interactive "P")
21878 (org-with-limited-levels
21879 (cond ((org-at-heading-p) (beginning-of-line))
21880 ((org-before-first-heading-p) (user-error "Not in a subtree"))
21881 (t (outline-previous-visible-heading 1))))
21882 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21883 (if (org-called-interactively-p 'any)
21884 (call-interactively 'org-mark-element)
21885 (org-mark-element)))
21888 ;;; Indentation
21890 (defun org-indent-line ()
21891 "Indent line depending on context."
21892 (interactive)
21893 (let* ((pos (point))
21894 (itemp (org-at-item-p))
21895 (case-fold-search t)
21896 (org-drawer-regexp (or org-drawer-regexp "\000"))
21897 (inline-task-p (and (featurep 'org-inlinetask)
21898 (org-inlinetask-in-task-p)))
21899 (inline-re (and inline-task-p
21900 (org-inlinetask-outline-regexp)))
21901 column)
21902 (if (and orgstruct-is-++ (eq pos (point)))
21903 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21904 (indent-according-to-mode))
21905 (beginning-of-line 1)
21906 (cond
21907 ;; Headings
21908 ((looking-at org-outline-regexp) (setq column 0))
21909 ;; Footnote definition
21910 ((looking-at org-footnote-definition-re) (setq column 0))
21911 ;; Literal examples
21912 ((looking-at "[ \t]*:\\( \\|$\\)")
21913 (setq column (org-get-indentation))) ; do nothing
21914 ;; Lists
21915 ((ignore-errors (goto-char (org-in-item-p)))
21916 (setq column (if itemp
21917 (org-get-indentation)
21918 (org-list-item-body-column (point))))
21919 (goto-char pos))
21920 ;; Drawers
21921 ((and (looking-at "[ \t]*:END:")
21922 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21923 (save-excursion
21924 (goto-char (1- (match-beginning 1)))
21925 (setq column (current-column))))
21926 ;; Special blocks
21927 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21928 (save-excursion
21929 (re-search-backward
21930 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21931 (setq column (org-get-indentation (match-string 0))))
21932 ((and (not (looking-at "[ \t]*#\\+begin_"))
21933 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21934 (save-excursion
21935 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21936 (setq column
21937 (cond ((equal (downcase (match-string 1)) "src")
21938 ;; src blocks: let `org-edit-src-exit' handle them
21939 (org-get-indentation))
21940 ((equal (downcase (match-string 1)) "example")
21941 (max (org-get-indentation)
21942 (org-get-indentation (match-string 0))))
21944 (org-get-indentation (match-string 0))))))
21945 ;; This line has nothing special, look at the previous relevant
21946 ;; line to compute indentation
21948 (beginning-of-line 0)
21949 (while (and (not (bobp))
21950 (not (looking-at org-table-line-regexp))
21951 (not (looking-at org-drawer-regexp))
21952 ;; When point started in an inline task, do not move
21953 ;; above task starting line.
21954 (not (and inline-task-p (looking-at inline-re)))
21955 ;; Skip drawers, blocks, empty lines, verbatim,
21956 ;; comments, tables, footnotes definitions, lists,
21957 ;; inline tasks.
21958 (or (and (looking-at "[ \t]*:END:")
21959 (re-search-backward org-drawer-regexp nil t))
21960 (and (looking-at "[ \t]*#\\+end_")
21961 (re-search-backward "[ \t]*#\\+begin_"nil t))
21962 (looking-at "[ \t]*[\n:#|]")
21963 (looking-at org-footnote-definition-re)
21964 (and (not inline-task-p)
21965 (featurep 'org-inlinetask)
21966 (org-inlinetask-in-task-p)
21967 (or (org-inlinetask-goto-beginning) t))))
21968 (beginning-of-line 0))
21969 (cond
21970 ;; There was a list item above.
21971 ((save-excursion
21972 (and (ignore-errors (goto-char (org-in-item-p)))
21973 (goto-char
21974 (org-list-get-top-point (org-list-struct)))))
21975 (looking-at org-list-full-item-re)
21976 (setq column (length (match-string 0))))
21977 ;; There was an heading above.
21978 ((looking-at "\\*+[ \t]+")
21979 (if (not org-adapt-indentation)
21980 (setq column 0)
21981 (goto-char (match-end 0))
21982 (setq column (current-column))))
21983 ;; A drawer had started and is unfinished
21984 ((looking-at org-drawer-regexp)
21985 (goto-char (1- (match-beginning 1)))
21986 (setq column (current-column)))
21987 ;; Else, nothing noticeable found: get indentation and go on.
21988 (t (setq column (org-get-indentation))))))
21989 ;; Now apply indentation and move cursor accordingly
21990 (goto-char pos)
21991 (if (<= (current-column) (current-indentation))
21992 (org-indent-line-to column)
21993 (save-excursion (org-indent-line-to column)))
21994 ;; Special polishing for properties, see `org-property-format'
21995 (setq column (current-column))
21996 (beginning-of-line 1)
21997 (if (looking-at
21998 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21999 (replace-match (concat (match-string 1)
22000 (format org-property-format
22001 (match-string 2) (match-string 3)))
22002 t t))
22003 (org-move-to-column column))))
22005 (defun org-indent-drawer ()
22006 "Indent the drawer at point."
22007 (interactive)
22008 (let ((p (point))
22009 (e (and (save-excursion (re-search-forward ":END:" nil t))
22010 (match-end 0)))
22011 (folded
22012 (save-excursion
22013 (end-of-line)
22014 (when (overlays-at (point))
22015 (member 'invisible (overlay-properties
22016 (car (overlays-at (point)))))))))
22017 (when folded (org-cycle))
22018 (indent-for-tab-command)
22019 (while (and (move-beginning-of-line 2) (< (point) e))
22020 (indent-for-tab-command))
22021 (goto-char p)
22022 (when folded (org-cycle)))
22023 (message "Drawer at point indented"))
22025 (defun org-indent-block ()
22026 "Indent the block at point."
22027 (interactive)
22028 (let ((p (point))
22029 (case-fold-search t)
22030 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
22031 (match-end 0)))
22032 (folded
22033 (save-excursion
22034 (end-of-line)
22035 (when (overlays-at (point))
22036 (member 'invisible (overlay-properties
22037 (car (overlays-at (point)))))))))
22038 (when folded (org-cycle))
22039 (indent-for-tab-command)
22040 (while (and (move-beginning-of-line 2) (< (point) e))
22041 (indent-for-tab-command))
22042 (goto-char p)
22043 (when folded (org-cycle)))
22044 (message "Block at point indented"))
22046 (defun org-indent-region (start end)
22047 "Indent region."
22048 (interactive "r")
22049 (save-excursion
22050 (let ((line-end (org-current-line end)))
22051 (goto-char start)
22052 (while (< (org-current-line) line-end)
22053 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
22054 (t (call-interactively 'org-indent-line)))
22055 (move-beginning-of-line 2)))))
22058 ;;; Filling
22060 ;; We use our own fill-paragraph and auto-fill functions.
22062 ;; `org-fill-paragraph' relies on adaptive filling and context
22063 ;; checking. Appropriate `fill-prefix' is computed with
22064 ;; `org-adaptive-fill-function'.
22066 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22067 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22068 ;; `org-adaptive-fill-function' value. Internally,
22069 ;; `org-comment-line-break-function' breaks the line.
22071 ;; `org-setup-filling' installs filling and auto-filling related
22072 ;; variables during `org-mode' initialization.
22074 (defun org-setup-filling ()
22075 (interactive)
22076 ;; Prevent auto-fill from inserting unwanted new items.
22077 (when (boundp 'fill-nobreak-predicate)
22078 (org-set-local
22079 'fill-nobreak-predicate
22080 (org-uniquify
22081 (append fill-nobreak-predicate
22082 '(org-fill-paragraph-separate-nobreak-p
22083 org-fill-line-break-nobreak-p
22084 org-fill-paragraph-with-timestamp-nobreak-p)))))
22085 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22086 (org-set-local 'auto-fill-inhibit-regexp nil)
22087 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22088 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22089 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22091 (defvar org-element-paragraph-separate) ; org-element.el
22092 (defun org-fill-paragraph-separate-nobreak-p ()
22093 "Non-nil when a new line at point would end current paragraph."
22094 (looking-at (substring org-element-paragraph-separate 1)))
22096 (defun org-fill-line-break-nobreak-p ()
22097 "Non-nil when a new line at point would create an Org line break."
22098 (save-excursion
22099 (skip-chars-backward "[ \t]")
22100 (skip-chars-backward "\\\\")
22101 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22103 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22104 "Non-nil when a new line at point would split a timestamp."
22105 (and (org-at-timestamp-p t)
22106 (not (looking-at org-ts-regexp-both))))
22108 (declare-function message-in-body-p "message" ())
22109 (defvar orgtbl-line-start-regexp) ; From org-table.el
22110 (defun org-adaptive-fill-function ()
22111 "Compute a fill prefix for the current line.
22112 Return fill prefix, as a string, or nil if current line isn't
22113 meant to be filled."
22114 (let (prefix)
22115 (catch 'exit
22116 (when (derived-mode-p 'message-mode)
22117 (save-excursion
22118 (beginning-of-line)
22119 (cond ((or (not (message-in-body-p))
22120 (looking-at orgtbl-line-start-regexp))
22121 (throw 'exit nil))
22122 ((looking-at message-cite-prefix-regexp)
22123 (throw 'exit (match-string-no-properties 0)))
22124 ((looking-at org-outline-regexp)
22125 (throw 'exit (make-string (length (match-string 0)) ? ))))))
22126 (org-with-wide-buffer
22127 (let* ((p (line-beginning-position))
22128 (element (save-excursion
22129 (beginning-of-line)
22130 (or (ignore-errors (org-element-at-point))
22131 (user-error "An element cannot be parsed line %d"
22132 (line-number-at-pos (point))))))
22133 (type (org-element-type element))
22134 (post-affiliated (org-element-property :post-affiliated element)))
22135 (unless (and post-affiliated (< p post-affiliated))
22136 (case type
22137 (comment (looking-at "[ \t]*# ?") (match-string 0))
22138 (footnote-definition "")
22139 ((item plain-list)
22140 (make-string (org-list-item-body-column
22141 (or post-affiliated
22142 (org-element-property :begin element)))
22143 ? ))
22144 (paragraph
22145 ;; Fill prefix is usually the same as the current line,
22146 ;; except if the paragraph is at the beginning of an item.
22147 (let ((parent (org-element-property :parent element)))
22148 (cond ((eq (org-element-type parent) 'item)
22149 (make-string (org-list-item-body-column
22150 (org-element-property :begin parent))
22151 ? ))
22152 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22153 (match-string 0))
22154 (t ""))))
22155 (comment-block
22156 ;; Only fill contents if P is within block boundaries.
22157 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22158 (forward-line)
22159 (point)))
22160 (cend (save-excursion
22161 (goto-char (org-element-property :end element))
22162 (skip-chars-backward " \r\t\n")
22163 (line-beginning-position))))
22164 (when (and (>= p cbeg) (< p cend))
22165 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22166 (match-string 0)
22167 "")))))))))))
22169 (declare-function message-goto-body "message" ())
22170 (defvar message-cite-prefix-regexp) ; From message.el
22171 (defun org-fill-paragraph (&optional justify)
22172 "Fill element at point, when applicable.
22174 This function only applies to comment blocks, comments, example
22175 blocks and paragraphs. Also, as a special case, re-align table
22176 when point is at one.
22178 If JUSTIFY is non-nil (interactively, with prefix argument),
22179 justify as well. If `sentence-end-double-space' is non-nil, then
22180 period followed by one space does not end a sentence, so don't
22181 break a line there. The variable `fill-column' controls the
22182 width for filling.
22184 For convenience, when point is at a plain list, an item or
22185 a footnote definition, try to fill the first paragraph within."
22186 (interactive)
22187 (if (and (derived-mode-p 'message-mode)
22188 (or (not (message-in-body-p))
22189 (save-excursion (move-beginning-of-line 1)
22190 (looking-at message-cite-prefix-regexp))))
22191 ;; First ensure filling is correct in message-mode.
22192 (let ((fill-paragraph-function
22193 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22194 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22195 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22196 (paragraph-separate
22197 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22198 (fill-paragraph nil))
22199 (with-syntax-table org-mode-transpose-word-syntax-table
22200 ;; Move to end of line in order to get the first paragraph
22201 ;; within a plain list or a footnote definition.
22202 (let ((element (save-excursion
22203 (end-of-line)
22204 (or (ignore-errors (org-element-at-point))
22205 (user-error "An element cannot be parsed line %d"
22206 (line-number-at-pos (point)))))))
22207 ;; First check if point is in a blank line at the beginning of
22208 ;; the buffer. In that case, ignore filling.
22209 (case (org-element-type element)
22210 ;; Use major mode filling function is src blocks.
22211 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22212 ;; Align Org tables, leave table.el tables as-is.
22213 (table-row (org-table-align) t)
22214 (table
22215 (when (eq (org-element-property :type element) 'org)
22216 (save-excursion
22217 (goto-char (org-element-property :post-affiliated element))
22218 (org-table-align)))
22220 (paragraph
22221 ;; Paragraphs may contain `line-break' type objects.
22222 (let ((beg (max (point-min)
22223 (org-element-property :contents-begin element)))
22224 (end (min (point-max)
22225 (org-element-property :contents-end element))))
22226 ;; Do nothing if point is at an affiliated keyword.
22227 (if (< (line-end-position) beg) t
22228 (when (derived-mode-p 'message-mode)
22229 ;; In `message-mode', do not fill following citation
22230 ;; in current paragraph nor text before message body.
22231 (let ((body-start (save-excursion (message-goto-body))))
22232 (when body-start (setq beg (max body-start beg))))
22233 (when (save-excursion
22234 (re-search-forward
22235 (concat "^" message-cite-prefix-regexp) end t))
22236 (setq end (match-beginning 0))))
22237 ;; Fill paragraph, taking line breaks into account.
22238 ;; For that, slice the paragraph using line breaks as
22239 ;; separators, and fill the parts in reverse order to
22240 ;; avoid messing with markers.
22241 (save-excursion
22242 (goto-char end)
22243 (mapc
22244 (lambda (pos)
22245 (fill-region-as-paragraph pos (point) justify)
22246 (goto-char pos))
22247 ;; Find the list of ending positions for line breaks
22248 ;; in the current paragraph. Add paragraph
22249 ;; beginning to include first slice.
22250 (nreverse
22251 (cons beg
22252 (org-element-map
22253 (org-element--parse-objects
22254 beg end nil (org-element-restriction 'paragraph))
22255 'line-break
22256 (lambda (lb) (org-element-property :end lb)))))))
22257 t)))
22258 ;; Contents of `comment-block' type elements should be
22259 ;; filled as plain text, but only if point is within block
22260 ;; markers.
22261 (comment-block
22262 (let* ((case-fold-search t)
22263 (beg (save-excursion
22264 (goto-char (org-element-property :begin element))
22265 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22266 (forward-line)
22267 (point)))
22268 (end (save-excursion
22269 (goto-char (org-element-property :end element))
22270 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22271 (line-beginning-position))))
22272 (when (and (>= (point) beg) (< (point) end))
22273 (fill-region-as-paragraph
22274 (save-excursion
22275 (end-of-line)
22276 (re-search-backward "^[ \t]*$" beg 'move)
22277 (line-beginning-position))
22278 (save-excursion
22279 (beginning-of-line)
22280 (re-search-forward "^[ \t]*$" end 'move)
22281 (line-beginning-position))
22282 justify)))
22284 ;; Fill comments.
22285 (comment (fill-comment-paragraph justify))
22286 ;; Ignore every other element.
22287 (otherwise t))))))
22289 (defun org-auto-fill-function ()
22290 "Auto-fill function."
22291 ;; Check if auto-filling is meaningful.
22292 (let ((fc (current-fill-column)))
22293 (when (and fc (> (current-column) fc))
22294 (let* ((fill-prefix (org-adaptive-fill-function))
22295 ;; Enforce empty fill prefix, if required. Otherwise, it
22296 ;; will be computed again.
22297 (adaptive-fill-mode (not (equal fill-prefix ""))))
22298 (when fill-prefix (do-auto-fill))))))
22300 (defun org-comment-line-break-function (&optional soft)
22301 "Break line at point and indent, continuing comment if within one.
22302 The inserted newline is marked hard if variable
22303 `use-hard-newlines' is true, unless optional argument SOFT is
22304 non-nil."
22305 (if soft (insert-and-inherit ?\n) (newline 1))
22306 (save-excursion (forward-char -1) (delete-horizontal-space))
22307 (delete-horizontal-space)
22308 (indent-to-left-margin)
22309 (insert-before-markers-and-inherit fill-prefix))
22312 ;;; Comments
22314 ;; Org comments syntax is quite complex. It requires the entire line
22315 ;; to be just a comment. Also, even with the right syntax at the
22316 ;; beginning of line, some some elements (i.e. verse-block or
22317 ;; example-block) don't accept comments. Usual Emacs comment commands
22318 ;; cannot cope with those requirements. Therefore, Org replaces them.
22320 ;; Org still relies on `comment-dwim', but cannot trust
22321 ;; `comment-only-p'. So, `comment-region-function' and
22322 ;; `uncomment-region-function' both point
22323 ;; to`org-comment-or-uncomment-region'. Eventually,
22324 ;; `org-insert-comment' takes care of insertion of comments at the
22325 ;; beginning of line.
22327 ;; `org-setup-comments-handling' install comments related variables
22328 ;; during `org-mode' initialization.
22330 (defun org-setup-comments-handling ()
22331 (interactive)
22332 (org-set-local 'comment-use-syntax nil)
22333 (org-set-local 'comment-start "# ")
22334 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22335 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22336 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22337 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22339 (defun org-insert-comment ()
22340 "Insert an empty comment above current line.
22341 If the line is empty, insert comment at its beginning."
22342 (beginning-of-line)
22343 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
22344 (org-indent-line)
22345 (insert "# "))
22347 (defvar comment-empty-lines) ; From newcomment.el.
22348 (defun org-comment-or-uncomment-region (beg end &rest ignore)
22349 "Comment or uncomment each non-blank line in the region.
22350 Uncomment each non-blank line between BEG and END if it only
22351 contains commented lines. Otherwise, comment them."
22352 (save-restriction
22353 ;; Restrict region
22354 (narrow-to-region (save-excursion (goto-char beg)
22355 (skip-chars-forward " \r\t\n" end)
22356 (line-beginning-position))
22357 (save-excursion (goto-char end)
22358 (skip-chars-backward " \r\t\n" beg)
22359 (line-end-position)))
22360 (let ((uncommentp
22361 ;; UNCOMMENTP is non-nil when every non blank line between
22362 ;; BEG and END is a comment.
22363 (save-excursion
22364 (goto-char (point-min))
22365 (while (and (not (eobp))
22366 (let ((element (org-element-at-point)))
22367 (and (eq (org-element-type element) 'comment)
22368 (goto-char (min (point-max)
22369 (org-element-property
22370 :end element)))))))
22371 (eobp))))
22372 (if uncommentp
22373 ;; Only blank lines and comments in region: uncomment it.
22374 (save-excursion
22375 (goto-char (point-min))
22376 (while (not (eobp))
22377 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22378 (replace-match "" nil nil nil 1))
22379 (forward-line)))
22380 ;; Comment each line in region.
22381 (let ((min-indent (point-max)))
22382 ;; First find the minimum indentation across all lines.
22383 (save-excursion
22384 (goto-char (point-min))
22385 (while (and (not (eobp)) (not (zerop min-indent)))
22386 (unless (looking-at "[ \t]*$")
22387 (setq min-indent (min min-indent (current-indentation))))
22388 (forward-line)))
22389 ;; Then loop over all lines.
22390 (save-excursion
22391 (goto-char (point-min))
22392 (while (not (eobp))
22393 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22394 ;; Don't get fooled by invisible text (e.g. link path)
22395 ;; when moving to column MIN-INDENT.
22396 (let ((buffer-invisibility-spec nil))
22397 (org-move-to-column min-indent t))
22398 (insert comment-start))
22399 (forward-line))))))))
22402 ;;; Planning
22404 ;; This section contains tools to operate on timestamp objects, as
22405 ;; returned by, e.g. `org-element-context'.
22407 (defun org-timestamp-has-time-p (timestamp)
22408 "Non-nil when TIMESTAMP has a time specified."
22409 (org-element-property :hour-start timestamp))
22411 (defun org-timestamp-format (timestamp format &optional end utc)
22412 "Format a TIMESTAMP element into a string.
22414 FORMAT is a format specifier to be passed to
22415 `format-time-string'.
22417 When optional argument END is non-nil, use end of date-range or
22418 time-range, if possible.
22420 When optional argument UTC is non-nil, time will be expressed as
22421 Universal Time."
22422 (format-time-string
22423 format
22424 (apply 'encode-time
22425 (cons 0
22426 (mapcar
22427 (lambda (prop) (or (org-element-property prop timestamp) 0))
22428 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22429 '(:minute-start :hour-start :day-start :month-start
22430 :year-start)))))
22431 utc))
22433 (defun org-timestamp-split-range (timestamp &optional end)
22434 "Extract a timestamp object from a date or time range.
22436 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22437 the end of the range. Otherwise, extract its start.
22439 Return a new timestamp object sharing the same parent as
22440 TIMESTAMP."
22441 (let ((type (org-element-property :type timestamp)))
22442 (if (memq type '(active inactive diary)) timestamp
22443 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22444 ;; Set new type.
22445 (org-element-put-property
22446 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22447 ;; Copy start properties over end properties if END is
22448 ;; non-nil. Otherwise, copy end properties over `start' ones.
22449 (let ((p-alist '((:minute-start . :minute-end)
22450 (:hour-start . :hour-end)
22451 (:day-start . :day-end)
22452 (:month-start . :month-end)
22453 (:year-start . :year-end))))
22454 (dolist (p-cell p-alist)
22455 (org-element-put-property
22456 split-ts
22457 (funcall (if end 'car 'cdr) p-cell)
22458 (org-element-property
22459 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22460 ;; Eventually refresh `:raw-value'.
22461 (org-element-put-property split-ts :raw-value nil)
22462 (org-element-put-property
22463 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22465 (defun org-timestamp-translate (timestamp &optional boundary)
22466 "Apply `org-translate-time' on a TIMESTAMP object.
22467 When optional argument BOUNDARY is non-nil, it is either the
22468 symbol `start' or `end'. In this case, only translate the
22469 starting or ending part of TIMESTAMP if it is a date or time
22470 range. Otherwise, translate both parts."
22471 (if (and (not boundary)
22472 (memq (org-element-property :type timestamp)
22473 '(active-range inactive-range)))
22474 (concat
22475 (org-translate-time
22476 (org-element-property :raw-value
22477 (org-timestamp-split-range timestamp)))
22478 "--"
22479 (org-translate-time
22480 (org-element-property :raw-value
22481 (org-timestamp-split-range timestamp t))))
22482 (org-translate-time
22483 (org-element-property
22484 :raw-value
22485 (if (not boundary) timestamp
22486 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22490 ;;; Other stuff.
22492 (defun org-toggle-fixed-width-section (arg)
22493 "Toggle the fixed-width export.
22494 If there is no active region, the QUOTE keyword at the current headline is
22495 inserted or removed. When present, it causes the text between this headline
22496 and the next to be exported as fixed-width text, and unmodified.
22497 If there is an active region, this command adds or removes a colon as the
22498 first character of this line. If the first character of a line is a colon,
22499 this line is also exported in fixed-width font."
22500 (interactive "P")
22501 (let* ((cc 0)
22502 (regionp (org-region-active-p))
22503 (beg (if regionp (region-beginning) (point)))
22504 (end (if regionp (region-end)))
22505 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22506 (case-fold-search nil)
22507 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22508 off)
22509 (if regionp
22510 (save-excursion
22511 (goto-char beg)
22512 (setq cc (current-column))
22513 (beginning-of-line 1)
22514 (setq off (looking-at re))
22515 (while (> nlines 0)
22516 (setq nlines (1- nlines))
22517 (beginning-of-line 1)
22518 (cond
22519 (arg
22520 (org-move-to-column cc t)
22521 (insert ": \n")
22522 (forward-line -1))
22523 ((and off (looking-at re))
22524 (replace-match "" t t nil 1))
22525 ((not off) (org-move-to-column cc t) (insert ": ")))
22526 (forward-line 1)))
22527 (save-excursion
22528 (org-back-to-heading)
22529 (cond
22530 ((looking-at (format org-heading-keyword-regexp-format
22531 org-quote-string))
22532 (goto-char (match-end 1))
22533 (looking-at (concat " +" org-quote-string))
22534 (replace-match "" t t)
22535 (when (eolp) (insert " ")))
22536 ((looking-at org-outline-regexp)
22537 (goto-char (match-end 0))
22538 (insert org-quote-string " ")))))))
22540 (defun org-reftex-citation ()
22541 "Use reftex-citation to insert a citation into the buffer.
22542 This looks for a line like
22544 #+BIBLIOGRAPHY: foo plain option:-d
22546 and derives from it that foo.bib is the bibliography file relevant
22547 for this document. It then installs the necessary environment for RefTeX
22548 to work in this buffer and calls `reftex-citation' to insert a citation
22549 into the buffer.
22551 Export of such citations to both LaTeX and HTML is handled by the contributed
22552 package org-exp-bibtex by Taru Karttunen."
22553 (interactive)
22554 (let ((reftex-docstruct-symbol 'rds)
22555 (reftex-cite-format "\\cite{%l}")
22556 rds bib)
22557 (save-excursion
22558 (save-restriction
22559 (widen)
22560 (let ((case-fold-search t)
22561 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22562 (if (not (save-excursion
22563 (or (re-search-forward re nil t)
22564 (re-search-backward re nil t))))
22565 (error "No bibliography defined in file")
22566 (setq bib (concat (match-string 1) ".bib")
22567 rds (list (list 'bib bib)))))))
22568 (call-interactively 'reftex-citation)))
22570 ;;;; Functions extending outline functionality
22572 (defun org-beginning-of-line (&optional arg)
22573 "Go to the beginning of the current line. If that is invisible, continue
22574 to a visible line beginning. This makes the function of C-a more intuitive.
22575 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22576 first attempt, and only move to after the tags when the cursor is already
22577 beyond the end of the headline."
22578 (interactive "P")
22579 (let ((pos (point))
22580 (special (if (consp org-special-ctrl-a/e)
22581 (car org-special-ctrl-a/e)
22582 org-special-ctrl-a/e))
22583 refpos)
22584 (if (org-bound-and-true-p visual-line-mode)
22585 (beginning-of-visual-line 1)
22586 (beginning-of-line 1))
22587 (if (and arg (fboundp 'move-beginning-of-line))
22588 (call-interactively 'move-beginning-of-line)
22589 (if (bobp)
22591 (backward-char 1)
22592 (if (org-truely-invisible-p)
22593 (while (and (not (bobp)) (org-truely-invisible-p))
22594 (backward-char 1)
22595 (beginning-of-line 1))
22596 (forward-char 1))))
22597 (when special
22598 (cond
22599 ((and (looking-at org-complex-heading-regexp)
22600 (= (char-after (match-end 1)) ?\ ))
22601 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22602 (point-at-eol)))
22603 (goto-char
22604 (if (eq special t)
22605 (cond ((> pos refpos) refpos)
22606 ((= pos (point)) refpos)
22607 (t (point)))
22608 (cond ((> pos (point)) (point))
22609 ((not (eq last-command this-command)) (point))
22610 (t refpos)))))
22611 ((org-at-item-p)
22612 ;; Being at an item and not looking at an the item means point
22613 ;; was previously moved to beginning of a visual line, which
22614 ;; doesn't contain the item. Therefore, do nothing special,
22615 ;; just stay here.
22616 (when (looking-at org-list-full-item-re)
22617 ;; Set special position at first white space character after
22618 ;; bullet, and check-box, if any.
22619 (let ((after-bullet
22620 (let ((box (match-end 3)))
22621 (if (not box) (match-end 1)
22622 (let ((after (char-after box)))
22623 (if (and after (= after ? )) (1+ box) box))))))
22624 ;; Special case: Move point to special position when
22625 ;; currently after it or at beginning of line.
22626 (if (eq special t)
22627 (when (or (> pos after-bullet) (= (point) pos))
22628 (goto-char after-bullet))
22629 ;; Reversed case: Move point to special position when
22630 ;; point was already at beginning of line and command is
22631 ;; repeated.
22632 (when (and (= (point) pos) (eq last-command this-command))
22633 (goto-char after-bullet))))))))
22634 (org-no-warnings
22635 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22637 (defun org-end-of-line (&optional arg)
22638 "Go to the end of the line.
22639 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22640 tags on the first attempt, and only move to after the tags when
22641 the cursor is already beyond the end of the headline."
22642 (interactive "P")
22643 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22644 org-special-ctrl-a/e))
22645 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22646 'end-of-visual-line)
22647 ((fboundp 'move-end-of-line) 'move-end-of-line)
22648 (t 'end-of-line))))
22649 (if (or (not special) arg) (call-interactively move-fun)
22650 (let* ((element (save-excursion (beginning-of-line)
22651 (org-element-at-point)))
22652 (type (org-element-type element)))
22653 (cond
22654 ((memq type '(headline inlinetask))
22655 (let ((pos (point)))
22656 (beginning-of-line 1)
22657 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22658 (if (eq special t)
22659 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22660 (goto-char (match-beginning 1))
22661 (goto-char (match-end 0)))
22662 (if (or (< pos (match-end 0))
22663 (not (eq this-command last-command)))
22664 (goto-char (match-end 0))
22665 (goto-char (match-beginning 1))))
22666 (call-interactively move-fun))))
22667 ((org-element-property :hiddenp element)
22668 ;; If element is hidden, `move-end-of-line' would put point
22669 ;; after it. Use `end-of-line' to stay on current line.
22670 (call-interactively 'end-of-line))
22671 (t (call-interactively move-fun)))))
22672 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22674 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22675 (define-key org-mode-map "\C-e" 'org-end-of-line)
22677 (defun org-backward-sentence (&optional arg)
22678 "Go to beginning of sentence, or beginning of table field.
22679 This will call `backward-sentence' or `org-table-beginning-of-field',
22680 depending on context."
22681 (interactive "P")
22682 (cond
22683 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22684 (t (call-interactively 'backward-sentence))))
22686 (defun org-forward-sentence (&optional arg)
22687 "Go to end of sentence, or end of table field.
22688 This will call `forward-sentence' or `org-table-end-of-field',
22689 depending on context."
22690 (interactive "P")
22691 (cond
22692 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22693 (t (call-interactively 'forward-sentence))))
22695 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22696 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22698 (defun org-kill-line (&optional arg)
22699 "Kill line, to tags or end of line."
22700 (interactive "P")
22701 (cond
22702 ((or (not org-special-ctrl-k)
22703 (bolp)
22704 (not (org-at-heading-p)))
22705 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22706 org-ctrl-k-protect-subtree)
22707 (if (or (eq org-ctrl-k-protect-subtree 'error)
22708 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22709 (user-error "C-k aborted as it would kill a hidden subtree")))
22710 (call-interactively
22711 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22712 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22713 (kill-region (point) (match-beginning 1))
22714 (org-set-tags nil t))
22715 (t (kill-region (point) (point-at-eol)))))
22717 (define-key org-mode-map "\C-k" 'org-kill-line)
22719 (defun org-yank (&optional arg)
22720 "Yank. If the kill is a subtree, treat it specially.
22721 This command will look at the current kill and check if is a single
22722 subtree, or a series of subtrees[1]. If it passes the test, and if the
22723 cursor is at the beginning of a line or after the stars of a currently
22724 empty headline, then the yank is handled specially. How exactly depends
22725 on the value of the following variables, both set by default.
22727 org-yank-folded-subtrees
22728 When set, the subtree(s) will be folded after insertion, but only
22729 if doing so would now swallow text after the yanked text.
22731 org-yank-adjusted-subtrees
22732 When set, the subtree will be promoted or demoted in order to
22733 fit into the local outline tree structure, which means that the level
22734 will be adjusted so that it becomes the smaller one of the two
22735 *visible* surrounding headings.
22737 Any prefix to this command will cause `yank' to be called directly with
22738 no special treatment. In particular, a simple \\[universal-argument] prefix \
22739 will just
22740 plainly yank the text as it is.
22742 \[1] The test checks if the first non-white line is a heading
22743 and if there are no other headings with fewer stars."
22744 (interactive "P")
22745 (org-yank-generic 'yank arg))
22747 (defun org-yank-generic (command arg)
22748 "Perform some yank-like command.
22750 This function implements the behavior described in the `org-yank'
22751 documentation. However, it has been generalized to work for any
22752 interactive command with similar behavior."
22754 ;; pretend to be command COMMAND
22755 (setq this-command command)
22757 (if arg
22758 (call-interactively command)
22760 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22761 (and (org-kill-is-subtree-p)
22762 (or (bolp)
22763 (and (looking-at "[ \t]*$")
22764 (string-match
22765 "\\`\\*+\\'"
22766 (buffer-substring (point-at-bol) (point)))))))
22767 swallowp)
22768 (cond
22769 ((and subtreep org-yank-folded-subtrees)
22770 (let ((beg (point))
22771 end)
22772 (if (and subtreep org-yank-adjusted-subtrees)
22773 (org-paste-subtree nil nil 'for-yank)
22774 (call-interactively command))
22776 (setq end (point))
22777 (goto-char beg)
22778 (when (and (bolp) subtreep
22779 (not (setq swallowp
22780 (org-yank-folding-would-swallow-text beg end))))
22781 (org-with-limited-levels
22782 (or (looking-at org-outline-regexp)
22783 (re-search-forward org-outline-regexp-bol end t))
22784 (while (and (< (point) end) (looking-at org-outline-regexp))
22785 (hide-subtree)
22786 (org-cycle-show-empty-lines 'folded)
22787 (condition-case nil
22788 (outline-forward-same-level 1)
22789 (error (goto-char end))))))
22790 (when swallowp
22791 (message
22792 "Inserted text not folded because that would swallow text"))
22794 (goto-char end)
22795 (skip-chars-forward " \t\n\r")
22796 (beginning-of-line 1)
22797 (push-mark beg 'nomsg)))
22798 ((and subtreep org-yank-adjusted-subtrees)
22799 (let ((beg (point-at-bol)))
22800 (org-paste-subtree nil nil 'for-yank)
22801 (push-mark beg 'nomsg)))
22803 (call-interactively command))))))
22805 (defun org-yank-folding-would-swallow-text (beg end)
22806 "Would hide-subtree at BEG swallow any text after END?"
22807 (let (level)
22808 (org-with-limited-levels
22809 (save-excursion
22810 (goto-char beg)
22811 (when (or (looking-at org-outline-regexp)
22812 (re-search-forward org-outline-regexp-bol end t))
22813 (setq level (org-outline-level)))
22814 (goto-char end)
22815 (skip-chars-forward " \t\r\n\v\f")
22816 (if (or (eobp)
22817 (and (bolp) (looking-at org-outline-regexp)
22818 (<= (org-outline-level) level)))
22819 nil ; Nothing would be swallowed
22820 t))))) ; something would swallow
22822 (define-key org-mode-map "\C-y" 'org-yank)
22824 (defun org-truely-invisible-p ()
22825 "Check if point is at a character currently not visible.
22826 This version does not only check the character property, but also
22827 `visible-mode'."
22828 ;; Early versions of noutline don't have `outline-invisible-p'.
22829 (if (org-bound-and-true-p visible-mode)
22831 (outline-invisible-p)))
22833 (defun org-invisible-p2 ()
22834 "Check if point is at a character currently not visible."
22835 (save-excursion
22836 (if (and (eolp) (not (bobp))) (backward-char 1))
22837 ;; Early versions of noutline don't have `outline-invisible-p'.
22838 (outline-invisible-p)))
22840 (defun org-back-to-heading (&optional invisible-ok)
22841 "Call `outline-back-to-heading', but provide a better error message."
22842 (condition-case nil
22843 (outline-back-to-heading invisible-ok)
22844 (error (error "Before first headline at position %d in buffer %s"
22845 (point) (current-buffer)))))
22847 (defun org-before-first-heading-p ()
22848 "Before first heading?"
22849 (save-excursion
22850 (end-of-line)
22851 (null (re-search-backward org-outline-regexp-bol nil t))))
22853 (defun org-at-heading-p (&optional ignored)
22854 (outline-on-heading-p t))
22855 ;; Compatibility alias with Org versions < 7.8.03
22856 (defalias 'org-on-heading-p 'org-at-heading-p)
22858 (defun org-at-comment-p nil
22859 "Is cursor in a line starting with a # character?"
22860 (save-excursion
22861 (beginning-of-line)
22862 (looking-at "^#")))
22864 (defun org-at-drawer-p nil
22865 "Is cursor at a drawer keyword?"
22866 (save-excursion
22867 (move-beginning-of-line 1)
22868 (looking-at org-drawer-regexp)))
22870 (defun org-at-block-p nil
22871 "Is cursor at a block keyword?"
22872 (save-excursion
22873 (move-beginning-of-line 1)
22874 (looking-at org-block-regexp)))
22876 (defun org-point-at-end-of-empty-headline ()
22877 "If point is at the end of an empty headline, return t, else nil.
22878 If the heading only contains a TODO keyword, it is still still considered
22879 empty."
22880 (and (looking-at "[ \t]*$")
22881 (when org-todo-line-regexp
22882 (save-excursion
22883 (beginning-of-line 1)
22884 (let ((case-fold-search nil))
22885 (looking-at org-todo-line-regexp)
22886 (string= (match-string 3) ""))))))
22888 (defun org-at-heading-or-item-p ()
22889 (or (org-at-heading-p) (org-at-item-p)))
22891 (defun org-at-target-p ()
22892 (or (org-in-regexp org-radio-target-regexp)
22893 (org-in-regexp org-target-regexp)))
22894 ;; Compatibility alias with Org versions < 7.8.03
22895 (defalias 'org-on-target-p 'org-at-target-p)
22897 (defun org-up-heading-all (arg)
22898 "Move to the heading line of which the present line is a subheading.
22899 This function considers both visible and invisible heading lines.
22900 With argument, move up ARG levels."
22901 (if (fboundp 'outline-up-heading-all)
22902 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22903 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22905 (defun org-up-heading-safe ()
22906 "Move to the heading line of which the present line is a subheading.
22907 This version will not throw an error. It will return the level of the
22908 headline found, or nil if no higher level is found.
22910 Also, this function will be a lot faster than `outline-up-heading',
22911 because it relies on stars being the outline starters. This can really
22912 make a significant difference in outlines with very many siblings."
22913 (let (start-level re)
22914 (org-back-to-heading t)
22915 (setq start-level (funcall outline-level))
22916 (if (equal start-level 1)
22918 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22919 (if (re-search-backward re nil t)
22920 (funcall outline-level)))))
22922 (defun org-first-sibling-p ()
22923 "Is this heading the first child of its parents?"
22924 (interactive)
22925 (let ((re org-outline-regexp-bol)
22926 level l)
22927 (unless (org-at-heading-p t)
22928 (user-error "Not at a heading"))
22929 (setq level (funcall outline-level))
22930 (save-excursion
22931 (if (not (re-search-backward re nil t))
22933 (setq l (funcall outline-level))
22934 (< l level)))))
22936 (defun org-goto-sibling (&optional previous)
22937 "Goto the next sibling, even if it is invisible.
22938 When PREVIOUS is set, go to the previous sibling instead. Returns t
22939 when a sibling was found. When none is found, return nil and don't
22940 move point."
22941 (let ((fun (if previous 're-search-backward 're-search-forward))
22942 (pos (point))
22943 (re org-outline-regexp-bol)
22944 level l)
22945 (when (condition-case nil (org-back-to-heading t) (error nil))
22946 (setq level (funcall outline-level))
22947 (catch 'exit
22948 (or previous (forward-char 1))
22949 (while (funcall fun re nil t)
22950 (setq l (funcall outline-level))
22951 (when (< l level) (goto-char pos) (throw 'exit nil))
22952 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22953 (goto-char pos)
22954 nil))))
22956 (defun org-show-siblings ()
22957 "Show all siblings of the current headline."
22958 (save-excursion
22959 (while (org-goto-sibling) (org-flag-heading nil)))
22960 (save-excursion
22961 (while (org-goto-sibling 'previous)
22962 (org-flag-heading nil))))
22964 (defun org-goto-first-child ()
22965 "Goto the first child, even if it is invisible.
22966 Return t when a child was found. Otherwise don't move point and
22967 return nil."
22968 (let (level (pos (point)) (re org-outline-regexp-bol))
22969 (when (condition-case nil (org-back-to-heading t) (error nil))
22970 (setq level (outline-level))
22971 (forward-char 1)
22972 (if (and (re-search-forward re nil t) (> (outline-level) level))
22973 (progn (goto-char (match-beginning 0)) t)
22974 (goto-char pos) nil))))
22976 (defun org-show-hidden-entry ()
22977 "Show an entry where even the heading is hidden."
22978 (save-excursion
22979 (org-show-entry)))
22981 (defun org-flag-heading (flag &optional entry)
22982 "Flag the current heading. FLAG non-nil means make invisible.
22983 When ENTRY is non-nil, show the entire entry."
22984 (save-excursion
22985 (org-back-to-heading t)
22986 ;; Check if we should show the entire entry
22987 (if entry
22988 (progn
22989 (org-show-entry)
22990 (save-excursion
22991 (and (outline-next-heading)
22992 (org-flag-heading nil))))
22993 (outline-flag-region (max (point-min) (1- (point)))
22994 (save-excursion (outline-end-of-heading) (point))
22995 flag))))
22997 (defun org-get-next-sibling ()
22998 "Move to next heading of the same level, and return point.
22999 If there is no such heading, return nil.
23000 This is like outline-next-sibling, but invisible headings are ok."
23001 (let ((level (funcall outline-level)))
23002 (outline-next-heading)
23003 (while (and (not (eobp)) (> (funcall outline-level) level))
23004 (outline-next-heading))
23005 (if (or (eobp) (< (funcall outline-level) level))
23007 (point))))
23009 (defun org-get-last-sibling ()
23010 "Move to previous heading of the same level, and return point.
23011 If there is no such heading, return nil."
23012 (let ((opoint (point))
23013 (level (funcall outline-level)))
23014 (outline-previous-heading)
23015 (when (and (/= (point) opoint) (outline-on-heading-p t))
23016 (while (and (> (funcall outline-level) level)
23017 (not (bobp)))
23018 (outline-previous-heading))
23019 (if (< (funcall outline-level) level)
23021 (point)))))
23023 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23024 "Goto to the end of a subtree."
23025 ;; This contains an exact copy of the original function, but it uses
23026 ;; `org-back-to-heading', to make it work also in invisible
23027 ;; trees. And is uses an invisible-ok argument.
23028 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23029 ;; Furthermore, when used inside Org, finding the end of a large subtree
23030 ;; with many children and grandchildren etc, this can be much faster
23031 ;; than the outline version.
23032 (org-back-to-heading invisible-ok)
23033 (let ((first t)
23034 (level (funcall outline-level)))
23035 (if (and (derived-mode-p 'org-mode) (< level 1000))
23036 ;; A true heading (not a plain list item), in Org-mode
23037 ;; This means we can easily find the end by looking
23038 ;; only for the right number of stars. Using a regexp to do
23039 ;; this is so much faster than using a Lisp loop.
23040 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23041 (forward-char 1)
23042 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23043 ;; something else, do it the slow way
23044 (while (and (not (eobp))
23045 (or first (> (funcall outline-level) level)))
23046 (setq first nil)
23047 (outline-next-heading)))
23048 (unless to-heading
23049 (if (memq (preceding-char) '(?\n ?\^M))
23050 (progn
23051 ;; Go to end of line before heading
23052 (forward-char -1)
23053 (if (memq (preceding-char) '(?\n ?\^M))
23054 ;; leave blank line before heading
23055 (forward-char -1))))))
23056 (point))
23058 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
23059 "Use Org version in org-mode, for dramatic speed-up."
23060 (if (derived-mode-p 'org-mode)
23061 (progn
23062 (org-end-of-subtree nil t)
23063 (unless (eobp) (backward-char 1)))
23064 ad-do-it))
23066 (defun org-end-of-meta-data-and-drawers ()
23067 "Jump to the first text after meta data and drawers in the current entry.
23068 This will move over empty lines, lines with planning time stamps,
23069 clocking lines, and drawers."
23070 (org-back-to-heading t)
23071 (let ((end (save-excursion (outline-next-heading) (point)))
23072 (re (concat "\\(" org-drawer-regexp "\\)"
23073 "\\|" "[ \t]*" org-keyword-time-regexp)))
23074 (forward-line 1)
23075 (while (re-search-forward re end t)
23076 (if (not (match-end 1))
23077 ;; empty or planning line
23078 (forward-line 1)
23079 ;; a drawer, find the end
23080 (re-search-forward "^[ \t]*:END:" end 'move)
23081 (forward-line 1)))
23082 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23083 (point)))
23085 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23086 "Move forward to the ARG'th subheading at same level as this one.
23087 Stop at the first and last subheadings of a superior heading.
23088 Normally this only looks at visible headings, but when INVISIBLE-OK is
23089 non-nil it will also look at invisible ones."
23090 (interactive "p")
23091 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23092 (if (and arg (< arg 0))
23093 (goto-char (point-min))
23094 (outline-next-heading))
23095 (org-at-heading-p)
23096 (let ((level (- (match-end 0) (match-beginning 0) 1))
23097 (f (if (and arg (< arg 0))
23098 're-search-backward
23099 're-search-forward))
23100 (count (if arg (abs arg) 1))
23101 (result (point)))
23102 (while (and (prog1 (> count 0)
23103 (forward-char (if (and arg (< arg 0)) -1 1)))
23104 (funcall f org-outline-regexp-bol nil 'move))
23105 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23106 (cond ((< l level) (setq count 0))
23107 ((and (= l level)
23108 (or invisible-ok
23109 (progn
23110 (goto-char (line-beginning-position))
23111 (not (outline-invisible-p)))))
23112 (setq count (1- count))
23113 (when (eq l level)
23114 (setq result (point)))))))
23115 (goto-char result))
23116 (beginning-of-line 1)))
23118 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23119 "Move backward to the ARG'th subheading at same level as this one.
23120 Stop at the first and last subheadings of a superior heading."
23121 (interactive "p")
23122 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23124 (defun org-next-block (arg &optional backward block-regexp)
23125 "Jump to the next block.
23126 With a prefix argument ARG, jump forward ARG many source blocks.
23127 When BACKWARD is non-nil, jump to the previous block.
23128 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23129 (interactive "p")
23130 (let ((re (or block-regexp org-block-regexp))
23131 (re-search-fn (or (and backward 're-search-backward)
23132 're-search-forward)))
23133 (if (looking-at re) (forward-char 1))
23134 (condition-case nil
23135 (funcall re-search-fn re nil nil arg)
23136 (error (error "No %s code blocks" (if backward "previous" "further" ))))
23137 (goto-char (match-beginning 0)) (org-show-context)))
23139 (defun org-previous-block (arg &optional block-regexp)
23140 "Jump to the previous block.
23141 With a prefix argument ARG, jump backward ARG many source blocks.
23142 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23143 (interactive "p")
23144 (org-next-block arg t block-regexp))
23146 (defun org-forward-element ()
23147 "Move forward by one element.
23148 Move to the next element at the same level, when possible."
23149 (interactive)
23150 (cond ((eobp) (user-error "Cannot move further down"))
23151 ((org-with-limited-levels (org-at-heading-p))
23152 (let ((origin (point)))
23153 (goto-char (org-end-of-subtree nil t))
23154 (unless (org-with-limited-levels (org-at-heading-p))
23155 (goto-char origin)
23156 (user-error "Cannot move further down"))))
23158 (let* ((elem (org-element-at-point))
23159 (end (org-element-property :end elem))
23160 (parent (org-element-property :parent elem)))
23161 (if (and parent (= (org-element-property :contents-end parent) end))
23162 (goto-char (org-element-property :end parent))
23163 (goto-char end))))))
23165 (defun org-backward-element ()
23166 "Move backward by one element.
23167 Move to the previous element at the same level, when possible."
23168 (interactive)
23169 (cond ((bobp) (user-error "Cannot move further up"))
23170 ((org-with-limited-levels (org-at-heading-p))
23171 ;; At a headline, move to the previous one, if any, or stay
23172 ;; here.
23173 (let ((origin (point)))
23174 (org-with-limited-levels (org-backward-heading-same-level 1))
23175 ;; When current headline has no sibling above, move to its
23176 ;; parent.
23177 (when (= (point) origin)
23178 (or (org-with-limited-levels (org-up-heading-safe))
23179 (progn (goto-char origin)
23180 (user-error "Cannot move further up"))))))
23182 (let* ((trail (org-element-at-point 'keep-trail))
23183 (elem (car trail))
23184 (prev-elem (nth 1 trail))
23185 (beg (org-element-property :begin elem)))
23186 (cond
23187 ;; Move to beginning of current element if point isn't
23188 ;; there already.
23189 ((/= (point) beg) (goto-char beg))
23190 (prev-elem (goto-char (org-element-property :begin prev-elem)))
23191 ((org-before-first-heading-p) (goto-char (point-min)))
23192 (t (org-back-to-heading)))))))
23194 (defun org-up-element ()
23195 "Move to upper element."
23196 (interactive)
23197 (if (org-with-limited-levels (org-at-heading-p))
23198 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23199 (let* ((elem (org-element-at-point))
23200 (parent (org-element-property :parent elem)))
23201 (if parent (goto-char (org-element-property :begin parent))
23202 (if (org-with-limited-levels (org-before-first-heading-p))
23203 (user-error "No surrounding element")
23204 (org-with-limited-levels (org-back-to-heading)))))))
23206 (defvar org-element-greater-elements)
23207 (defun org-down-element ()
23208 "Move to inner element."
23209 (interactive)
23210 (let ((element (org-element-at-point)))
23211 (cond
23212 ((memq (org-element-type element) '(plain-list table))
23213 (goto-char (org-element-property :contents-begin element))
23214 (forward-char))
23215 ((memq (org-element-type element) org-element-greater-elements)
23216 ;; If contents are hidden, first disclose them.
23217 (when (org-element-property :hiddenp element) (org-cycle))
23218 (goto-char (or (org-element-property :contents-begin element)
23219 (user-error "No content for this element"))))
23220 (t (user-error "No inner element")))))
23222 (defun org-drag-element-backward ()
23223 "Move backward element at point."
23224 (interactive)
23225 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
23226 (let* ((trail (org-element-at-point 'keep-trail))
23227 (elem (car trail))
23228 (prev-elem (nth 1 trail)))
23229 ;; Error out if no previous element or previous element is
23230 ;; a parent of the current one.
23231 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23232 (user-error "Cannot drag element backward")
23233 (let ((pos (point)))
23234 (org-element-swap-A-B prev-elem elem)
23235 (goto-char (+ (org-element-property :begin prev-elem)
23236 (- pos (org-element-property :begin elem)))))))))
23238 (defun org-drag-element-forward ()
23239 "Move forward element at point."
23240 (interactive)
23241 (let* ((pos (point))
23242 (elem (org-element-at-point)))
23243 (when (= (point-max) (org-element-property :end elem))
23244 (user-error "Cannot drag element forward"))
23245 (goto-char (org-element-property :end elem))
23246 (let ((next-elem (org-element-at-point)))
23247 (when (or (org-element-nested-p elem next-elem)
23248 (and (eq (org-element-type next-elem) 'headline)
23249 (not (eq (org-element-type elem) 'headline))))
23250 (goto-char pos)
23251 (user-error "Cannot drag element forward"))
23252 ;; Compute new position of point: it's shifted by NEXT-ELEM
23253 ;; body's length (without final blanks) and by the length of
23254 ;; blanks between ELEM and NEXT-ELEM.
23255 (let ((size-next (- (save-excursion
23256 (goto-char (org-element-property :end next-elem))
23257 (skip-chars-backward " \r\t\n")
23258 (forward-line)
23259 ;; Small correction if buffer doesn't end
23260 ;; with a newline character.
23261 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23262 (org-element-property :begin next-elem)))
23263 (size-blank (- (org-element-property :end elem)
23264 (save-excursion
23265 (goto-char (org-element-property :end elem))
23266 (skip-chars-backward " \r\t\n")
23267 (forward-line)
23268 (point)))))
23269 (org-element-swap-A-B elem next-elem)
23270 (goto-char (+ pos size-next size-blank))))))
23272 (defun org-drag-line-forward (arg)
23273 "Drag the line at point ARG lines forward."
23274 (interactive "p")
23275 (dotimes (n (abs arg))
23276 (let ((c (current-column)))
23277 (if (< 0 arg)
23278 (progn
23279 (beginning-of-line 2)
23280 (transpose-lines 1)
23281 (beginning-of-line 0))
23282 (transpose-lines 1)
23283 (beginning-of-line -1))
23284 (org-move-to-column c))))
23286 (defun org-drag-line-backward (arg)
23287 "Drag the line at point ARG lines backward."
23288 (interactive "p")
23289 (org-drag-line-forward (- arg)))
23291 (defun org-mark-element ()
23292 "Put point at beginning of this element, mark at end.
23294 Interactively, if this command is repeated or (in Transient Mark
23295 mode) if the mark is active, it marks the next element after the
23296 ones already marked."
23297 (interactive)
23298 (let (deactivate-mark)
23299 (if (and (org-called-interactively-p 'any)
23300 (or (and (eq last-command this-command) (mark t))
23301 (and transient-mark-mode mark-active)))
23302 (set-mark
23303 (save-excursion
23304 (goto-char (mark))
23305 (goto-char (org-element-property :end (org-element-at-point)))))
23306 (let ((element (org-element-at-point)))
23307 (end-of-line)
23308 (push-mark (org-element-property :end element) t t)
23309 (goto-char (org-element-property :begin element))))))
23311 (defun org-narrow-to-element ()
23312 "Narrow buffer to current element."
23313 (interactive)
23314 (let ((elem (org-element-at-point)))
23315 (cond
23316 ((eq (car elem) 'headline)
23317 (narrow-to-region
23318 (org-element-property :begin elem)
23319 (org-element-property :end elem)))
23320 ((memq (car elem) org-element-greater-elements)
23321 (narrow-to-region
23322 (org-element-property :contents-begin elem)
23323 (org-element-property :contents-end elem)))
23325 (narrow-to-region
23326 (org-element-property :begin elem)
23327 (org-element-property :end elem))))))
23329 (defun org-transpose-element ()
23330 "Transpose current and previous elements, keeping blank lines between.
23331 Point is moved after both elements."
23332 (interactive)
23333 (org-skip-whitespace)
23334 (let ((end (org-element-property :end (org-element-at-point))))
23335 (org-drag-element-backward)
23336 (goto-char end)))
23338 (defun org-unindent-buffer ()
23339 "Un-indent the visible part of the buffer.
23340 Relative indentation (between items, inside blocks, etc.) isn't
23341 modified."
23342 (interactive)
23343 (unless (eq major-mode 'org-mode)
23344 (user-error "Cannot un-indent a buffer not in Org mode"))
23345 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
23346 unindent-tree ; For byte-compiler.
23347 (unindent-tree
23348 (function
23349 (lambda (contents)
23350 (mapc
23351 (lambda (element)
23352 (if (memq (org-element-type element) '(headline section))
23353 (funcall unindent-tree (org-element-contents element))
23354 (save-excursion
23355 (save-restriction
23356 (narrow-to-region
23357 (org-element-property :begin element)
23358 (org-element-property :end element))
23359 (org-do-remove-indentation)))))
23360 (reverse contents))))))
23361 (funcall unindent-tree (org-element-contents parse-tree))))
23363 (defun org-show-subtree ()
23364 "Show everything after this heading at deeper levels."
23365 (interactive)
23366 (outline-flag-region
23367 (point)
23368 (save-excursion
23369 (org-end-of-subtree t t))
23370 nil))
23372 (defun org-show-entry ()
23373 "Show the body directly following this heading.
23374 Show the heading too, if it is currently invisible."
23375 (interactive)
23376 (save-excursion
23377 (condition-case nil
23378 (progn
23379 (org-back-to-heading t)
23380 (outline-flag-region
23381 (max (point-min) (1- (point)))
23382 (save-excursion
23383 (if (re-search-forward
23384 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23385 (match-beginning 1)
23386 (point-max)))
23387 nil)
23388 (org-cycle-hide-drawers 'children))
23389 (error nil))))
23391 (defun org-make-options-regexp (kwds &optional extra)
23392 "Make a regular expression for keyword lines."
23393 (concat
23394 "^#\\+\\("
23395 (mapconcat 'regexp-quote kwds "\\|")
23396 (if extra (concat "\\|" extra))
23397 "\\):[ \t]*\\(.*\\)"))
23399 ;; Make isearch reveal the necessary context
23400 (defun org-isearch-end ()
23401 "Reveal context after isearch exits."
23402 (when isearch-success ; only if search was successful
23403 (if (featurep 'xemacs)
23404 ;; Under XEmacs, the hook is run in the correct place,
23405 ;; we directly show the context.
23406 (org-show-context 'isearch)
23407 ;; In Emacs the hook runs *before* restoring the overlays.
23408 ;; So we have to use a one-time post-command-hook to do this.
23409 ;; (Emacs 22 has a special variable, see function `org-mode')
23410 (unless (and (boundp 'isearch-mode-end-hook-quit)
23411 isearch-mode-end-hook-quit)
23412 ;; Only when the isearch was not quitted.
23413 (org-add-hook 'post-command-hook 'org-isearch-post-command
23414 'append 'local)))
23415 (org-fix-ellipsis-at-bol)))
23417 (defun org-isearch-post-command ()
23418 "Remove self from hook, and show context."
23419 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23420 (org-show-context 'isearch))
23423 ;;;; Integration with and fixes for other packages
23425 ;;; Imenu support
23427 (defvar org-imenu-markers nil
23428 "All markers currently used by Imenu.")
23429 (make-variable-buffer-local 'org-imenu-markers)
23431 (defun org-imenu-new-marker (&optional pos)
23432 "Return a new marker for use by Imenu, and remember the marker."
23433 (let ((m (make-marker)))
23434 (move-marker m (or pos (point)))
23435 (push m org-imenu-markers)
23438 (defun org-imenu-get-tree ()
23439 "Produce the index for Imenu."
23440 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23441 (setq org-imenu-markers nil)
23442 (let* ((n org-imenu-depth)
23443 (re (concat "^" (org-get-limited-outline-regexp)))
23444 (subs (make-vector (1+ n) nil))
23445 (last-level 0)
23446 m level head0 head)
23447 (save-excursion
23448 (save-restriction
23449 (widen)
23450 (goto-char (point-max))
23451 (while (re-search-backward re nil t)
23452 (setq level (org-reduced-level (funcall outline-level)))
23453 (when (and (<= level n)
23454 (looking-at org-complex-heading-regexp)
23455 (setq head0 (org-match-string-no-properties 4)))
23456 (setq head (org-link-display-format head0)
23457 m (org-imenu-new-marker))
23458 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23459 (if (>= level last-level)
23460 (push (cons head m) (aref subs level))
23461 (push (cons head (aref subs (1+ level))) (aref subs level))
23462 (loop for i from (1+ level) to n do (aset subs i nil)))
23463 (setq last-level level)))))
23464 (aref subs 1)))
23466 (eval-after-load "imenu"
23467 '(progn
23468 (add-hook 'imenu-after-jump-hook
23469 (lambda ()
23470 (if (derived-mode-p 'org-mode)
23471 (org-show-context 'org-goto))))))
23473 (defun org-link-display-format (link)
23474 "Replace a link with its the description.
23475 If there is no description, use the link target."
23476 (save-match-data
23477 (if (string-match org-bracket-link-analytic-regexp link)
23478 (replace-match (if (match-end 5)
23479 (match-string 5 link)
23480 (concat (match-string 1 link)
23481 (match-string 3 link)))
23482 nil t link)
23483 link)))
23485 (defun org-toggle-link-display ()
23486 "Toggle the literal or descriptive display of links."
23487 (interactive)
23488 (if org-descriptive-links
23489 (progn (org-remove-from-invisibility-spec '(org-link))
23490 (org-restart-font-lock)
23491 (setq org-descriptive-links nil))
23492 (progn (add-to-invisibility-spec '(org-link))
23493 (org-restart-font-lock)
23494 (setq org-descriptive-links t))))
23496 ;; Speedbar support
23498 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23499 "Overlay marking the agenda restriction line in speedbar.")
23500 (overlay-put org-speedbar-restriction-lock-overlay
23501 'face 'org-agenda-restriction-lock)
23502 (overlay-put org-speedbar-restriction-lock-overlay
23503 'help-echo "Agendas are currently limited to this item.")
23504 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23506 (defun org-speedbar-set-agenda-restriction ()
23507 "Restrict future agenda commands to the location at point in speedbar.
23508 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23509 (interactive)
23510 (require 'org-agenda)
23511 (let (p m tp np dir txt)
23512 (cond
23513 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23514 'org-imenu t))
23515 (setq m (get-text-property p 'org-imenu-marker))
23516 (with-current-buffer (marker-buffer m)
23517 (goto-char m)
23518 (org-agenda-set-restriction-lock 'subtree)))
23519 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23520 'speedbar-function 'speedbar-find-file))
23521 (setq tp (previous-single-property-change
23522 (1+ p) 'speedbar-function)
23523 np (next-single-property-change
23524 tp 'speedbar-function)
23525 dir (speedbar-line-directory)
23526 txt (buffer-substring-no-properties (or tp (point-min))
23527 (or np (point-max))))
23528 (with-current-buffer (find-file-noselect
23529 (let ((default-directory dir))
23530 (expand-file-name txt)))
23531 (unless (derived-mode-p 'org-mode)
23532 (user-error "Cannot restrict to non-Org-mode file"))
23533 (org-agenda-set-restriction-lock 'file)))
23534 (t (user-error "Don't know how to restrict Org-mode's agenda")))
23535 (move-overlay org-speedbar-restriction-lock-overlay
23536 (point-at-bol) (point-at-eol))
23537 (setq current-prefix-arg nil)
23538 (org-agenda-maybe-redo)))
23540 (eval-after-load "speedbar"
23541 '(progn
23542 (speedbar-add-supported-extension ".org")
23543 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23544 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23545 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23546 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23547 (add-hook 'speedbar-visiting-tag-hook
23548 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23550 ;;; Fixes and Hacks for problems with other packages
23552 ;; Make flyspell not check words in links, to not mess up our keymap
23553 (defvar org-element-affiliated-keywords) ; From org-element.el
23554 (defvar org-element-block-name-alist) ; From org-element.el
23555 (defun org-mode-flyspell-verify ()
23556 "Don't let flyspell put overlays at active buttons, or on
23557 {todo,all-time,additional-option-like}-keywords."
23558 (require 'org-element) ; For `org-element-affiliated-keywords'
23559 (let ((pos (max (1- (point)) (point-min)))
23560 (word (thing-at-point 'word)))
23561 (and (not (get-text-property pos 'keymap))
23562 (not (get-text-property pos 'org-no-flyspell))
23563 (not (member word org-todo-keywords-1))
23564 (not (member word org-all-time-keywords))
23565 (not (member word org-options-keywords))
23566 (not (member word (mapcar 'car org-startup-options)))
23567 (not (member-ignore-case word org-element-affiliated-keywords))
23568 (not (member-ignore-case word (org-get-export-keywords)))
23569 (not (member-ignore-case
23570 word (mapcar 'car org-element-block-name-alist)))
23571 (not (member-ignore-case word '("BEGIN" "END" "ATTR"))))))
23573 (defun org-remove-flyspell-overlays-in (beg end)
23574 "Remove flyspell overlays in region."
23575 (and (org-bound-and-true-p flyspell-mode)
23576 (fboundp 'flyspell-delete-region-overlays)
23577 (flyspell-delete-region-overlays beg end))
23578 (add-text-properties beg end '(org-no-flyspell t)))
23580 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23581 (eval-after-load "bookmark"
23582 '(if (boundp 'bookmark-after-jump-hook)
23583 ;; We can use the hook
23584 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23585 ;; Hook not available, use advice
23586 (defadvice bookmark-jump (after org-make-visible activate)
23587 "Make the position visible."
23588 (org-bookmark-jump-unhide))))
23590 ;; Make sure saveplace shows the location if it was hidden
23591 (eval-after-load "saveplace"
23592 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23593 "Make the position visible."
23594 (org-bookmark-jump-unhide)))
23596 ;; Make sure ecb shows the location if it was hidden
23597 (eval-after-load "ecb"
23598 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23599 "Make hierarchy visible when jumping into location from ECB tree buffer."
23600 (if (derived-mode-p 'org-mode)
23601 (org-show-context))))
23603 (defun org-bookmark-jump-unhide ()
23604 "Unhide the current position, to show the bookmark location."
23605 (and (derived-mode-p 'org-mode)
23606 (or (outline-invisible-p)
23607 (save-excursion (goto-char (max (point-min) (1- (point))))
23608 (outline-invisible-p)))
23609 (org-show-context 'bookmark-jump)))
23611 ;; Make session.el ignore our circular variable
23612 (eval-after-load "session"
23613 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23615 ;;;; Finish up
23617 (provide 'org)
23619 (run-hooks 'org-load-hook)
23621 ;;; org.el ends here